diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..ae200f1eb7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Prettier enforces LF line endings in all files +# If git is configured with core.autocrlf=true, it may convert LF to CRLF when +# checking out files depending on your OS. This will cause Prettier to change it +# causing Git to show every file as modified. +*.java text eol=lf diff --git a/.gitignore b/.gitignore index 204ca95f52..a4397c6105 100755 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ fitnesse/target/ daisy-integration/target/ war/target/ api/target/ +node_modules/ diff --git a/.prettierrc.yaml b/.prettierrc.yaml new file mode 100644 index 0000000000..f27fb6f122 --- /dev/null +++ b/.prettierrc.yaml @@ -0,0 +1,4 @@ +tabWidth: 4 +printWidth: 120 +plugins: + - prettier-plugin-java diff --git a/README.md b/README.md index 749d07cb72..dc2b0cb977 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,17 @@ and get an access token. Once the token has been obtained go to the [Swagger UI](http://localhost:8080/api/swagger) to interact with the API. Click the "Authorize" button in the top right and paste the access token to log in. + +## Code formatting +This project uses [prettier-java](https://github.com/jhipster/prettier-java) +to format all Java code. To reformat the code run +`./mvnw validate frontend:npm@reformat -pl .`. +Yes it's a mouthful but unfortunately the [prettier-maven-plugin](https://github.com/HubSpot/prettier-maven-plugin) +does not work due to an [outstanding issue](https://github.com/HubSpot/prettier-maven-plugin/issues/79). + +An easier way to reformat code is to set IntelliJ to do it on save. Go to +`Settings -> Language & Frameworks -> JavaScript -> Prettier` and then check +`Automatic Prettier Configuration`, set `Run for files` to `**/*.{java}`, +and finally check `Run on save`. + +The formatting is validated by CI, but you should do it beforehand with a simple `./mvnw verify -pl .`. diff --git a/api/src/main/java/se/su/dsv/scipro/api/ApiController.java b/api/src/main/java/se/su/dsv/scipro/api/ApiController.java index 8059cdde66..cfaab68826 100644 --- a/api/src/main/java/se/su/dsv/scipro/api/ApiController.java +++ b/api/src/main/java/se/su/dsv/scipro/api/ApiController.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.api; import jakarta.inject.Inject; +import java.util.Optional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import java.util.Optional; - @RestController public class ApiController { + private final UserService userService; @Inject @@ -21,9 +21,9 @@ public class ApiController { @GetMapping("/hello-world") public String helloWorld(@RequestParam(value = "username", required = false) String username) { String name = Optional.ofNullable(username) - .map(userService::findByUsername) - .map(User::getFullName) - .orElse("World"); + .map(userService::findByUsername) + .map(User::getFullName) + .orElse("World"); return "Hello, " + name + "!"; } } diff --git a/core/src/main/java/se/su/dsv/scipro/CoreConfig.java b/core/src/main/java/se/su/dsv/scipro/CoreConfig.java index 918df6478f..2dc8f54929 100644 --- a/core/src/main/java/se/su/dsv/scipro/CoreConfig.java +++ b/core/src/main/java/se/su/dsv/scipro/CoreConfig.java @@ -3,6 +3,8 @@ package se.su.dsv.scipro; import com.google.common.eventbus.EventBus; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import java.time.Clock; +import java.util.Set; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -201,11 +203,9 @@ import se.su.dsv.scipro.system.UserServiceImpl; import se.su.dsv.scipro.thesislink.ExternalLinkServiceImpl; import se.su.dsv.scipro.workerthreads.WorkerDataServiceImpl; -import java.time.Clock; -import java.util.Set; - @Configuration(proxyBeanMethods = false) public class CoreConfig { + @Bean public EventBus eventBus() { return new EventBus(); @@ -218,11 +218,11 @@ public class CoreConfig { @Bean public OAuthSettings oAuthSettings( - @Value("${oauth.uri}") String uri, - @Value("${oauth.redirectUri}") String redirectUri, - @Value("${oauth.clientId}") String clientId, - @Value("${oauth.clientSecret}") String clientSecret) - { + @Value("${oauth.uri}") String uri, + @Value("${oauth.redirectUri}") String redirectUri, + @Value("${oauth.clientId}") String clientId, + @Value("${oauth.clientSecret}") String clientSecret + ) { return new OAuthSettings(uri, redirectUri, clientId, clientSecret); } @@ -233,10 +233,10 @@ public class CoreConfig { @Bean public DaisyAPIImpl daisyAPI( - @Value("${daisy.api.url}") final String baseUrl, - @Value("${daisy.api.username}") final String user, - @Value("${daisy.api.password}") final String password) - { + @Value("${daisy.api.url}") final String baseUrl, + @Value("${daisy.api.username}") final String user, + @Value("${daisy.api.password}") final String password + ) { return new DaisyAPIImpl(baseUrl, user, password); } @@ -252,24 +252,36 @@ public class CoreConfig { @Bean public FinalSeminarApprovalServiceImpl finalSeminarApprovalService( - Provider em, - FileService fileDescriptionService, - EventBus eventBus, - DaysService daysService, - ReviewerDeadlineSettingsService reviewerDeadlineSettingsService) - { - return new FinalSeminarApprovalServiceImpl(em, fileDescriptionService, eventBus, daysService, reviewerDeadlineSettingsService); + Provider em, + FileService fileDescriptionService, + EventBus eventBus, + DaysService daysService, + ReviewerDeadlineSettingsService reviewerDeadlineSettingsService + ) { + return new FinalSeminarApprovalServiceImpl( + em, + fileDescriptionService, + eventBus, + daysService, + reviewerDeadlineSettingsService + ); } @Bean public RoughDraftApprovalServiceImpl roughDraftApprovalService( - Provider em, - FileService fileDescriptionService, - EventBus eventBus, - DaysService daysService, - ReviewerDeadlineSettingsService reviewerDeadlineSettingsService) - { - return new RoughDraftApprovalServiceImpl(em, eventBus, fileDescriptionService, daysService, reviewerDeadlineSettingsService); + Provider em, + FileService fileDescriptionService, + EventBus eventBus, + DaysService daysService, + ReviewerDeadlineSettingsService reviewerDeadlineSettingsService + ) { + return new RoughDraftApprovalServiceImpl( + em, + eventBus, + fileDescriptionService, + daysService, + reviewerDeadlineSettingsService + ); } @Bean @@ -289,15 +301,19 @@ public class CoreConfig { @Bean public ActivityPlanFacadeImpl activityPlanFacade( - EventBus eventBus, - ProjectFileService projectFileService, - ChecklistTemplateService checklistTemplateService, - DaysService daysService, - FileService fileService - ) - { - return new ActivityPlanFacadeImpl(eventBus, projectFileService, checklistTemplateService, daysService, - fileService); + EventBus eventBus, + ProjectFileService projectFileService, + ChecklistTemplateService checklistTemplateService, + DaysService daysService, + FileService fileService + ) { + return new ActivityPlanFacadeImpl( + eventBus, + projectFileService, + checklistTemplateService, + daysService, + fileService + ); } @Bean @@ -321,23 +337,25 @@ public class CoreConfig { } @Bean - public LocalAuthentication localAuthentication( - UserService userService, - PasswordService passwordService) - { + public LocalAuthentication localAuthentication(UserService userService, PasswordService passwordService) { return new LocalAuthentication(userService, passwordService); } @Bean public BasicForumServiceImpl basicForumService( - ForumPostRepository forumPostRepository, - ForumPostReadStateRepository readStateRepository, - AbstractThreadRepository threadRepository, - FileService fileService, - EventBus eventBus) - { - return new BasicForumServiceImpl(forumPostRepository, readStateRepository, threadRepository, fileService, - eventBus); + ForumPostRepository forumPostRepository, + ForumPostReadStateRepository readStateRepository, + AbstractThreadRepository threadRepository, + FileService fileService, + EventBus eventBus + ) { + return new BasicForumServiceImpl( + forumPostRepository, + readStateRepository, + threadRepository, + fileService, + eventBus + ); } @Bean @@ -372,9 +390,9 @@ public class CoreConfig { @Bean public DeliveryConfigurationServiceImpl deliveryConfigurationService( - Provider em, - UserProfileService userProfileService) - { + Provider em, + UserProfileService userProfileService + ) { return new DeliveryConfigurationServiceImpl(em, userProfileService); } @@ -395,16 +413,18 @@ public class CoreConfig { @Bean public FileServiceImpl fileService( - Provider em, - FileStore fileStore, - FileReferenceRepository fileReferenceRepository, - FileDescriptionRepo fileDescriptionRepository) - { + Provider em, + FileStore fileStore, + FileReferenceRepository fileReferenceRepository, + FileDescriptionRepo fileDescriptionRepository + ) { return new FileServiceImpl(em, fileReferenceRepository, fileDescriptionRepository, fileStore); } @Bean - public FinalSeminarActiveParticipationServiceImpl finalSeminarActiveParticipationService(Provider em) { + public FinalSeminarActiveParticipationServiceImpl finalSeminarActiveParticipationService( + Provider em + ) { return new FinalSeminarActiveParticipationServiceImpl(em); } @@ -420,26 +440,27 @@ public class CoreConfig { @Bean public FinalSeminarServiceImpl finalSeminarService( - Provider em, - EventBus eventBus, - FileService fileService, - AuthorRepository authorRepository, - FinalSeminarOppositionRepo finalSeminarOppositionRepository, - FinalSeminarActiveParticipationRepository finalSeminarActiveParticipationRepository, - FinalSeminarRepository finalSeminarRepository, - Clock clock, - RoughDraftApprovalService roughDraftApprovalService) - { + Provider em, + EventBus eventBus, + FileService fileService, + AuthorRepository authorRepository, + FinalSeminarOppositionRepo finalSeminarOppositionRepository, + FinalSeminarActiveParticipationRepository finalSeminarActiveParticipationRepository, + FinalSeminarRepository finalSeminarRepository, + Clock clock, + RoughDraftApprovalService roughDraftApprovalService + ) { return new FinalSeminarServiceImpl( - em, - eventBus, - authorRepository, - fileService, - finalSeminarOppositionRepository, - finalSeminarActiveParticipationRepository, - finalSeminarRepository, - clock, - roughDraftApprovalService); + em, + eventBus, + authorRepository, + fileService, + finalSeminarOppositionRepository, + finalSeminarActiveParticipationRepository, + finalSeminarRepository, + clock, + roughDraftApprovalService + ); } @Bean @@ -449,37 +470,51 @@ public class CoreConfig { @Bean public FinalSeminarUploadControllerImpl finalSeminarUploadController( - EventBus eventBus, - FileService fileService, - FinalSeminarService finalSeminarService, - ProjectFileService projectFileService, - ProjectService projectService, - FinalSeminarSettingsService finalSeminarSettingsService, - PlagiarismControl plagiarismControl) - { - return new FinalSeminarUploadControllerImpl(projectService, fileService, finalSeminarSettingsService, - finalSeminarService, eventBus, projectFileService, plagiarismControl); + EventBus eventBus, + FileService fileService, + FinalSeminarService finalSeminarService, + ProjectFileService projectFileService, + ProjectService projectService, + FinalSeminarSettingsService finalSeminarSettingsService, + PlagiarismControl plagiarismControl + ) { + return new FinalSeminarUploadControllerImpl( + projectService, + fileService, + finalSeminarSettingsService, + finalSeminarService, + eventBus, + projectFileService, + plagiarismControl + ); } @Bean public FinalThesisServiceImpl finalThesisService( - Provider em, - NotificationController notification, - ProjectFileService projectFile, - FileService fileService, - EventBus eventBus, - PlagiarismControl plagiarismControl, - GradingReportService gradingReportService) - { - return new FinalThesisServiceImpl(em, notification, projectFile, - fileService, eventBus, plagiarismControl, gradingReportService); + Provider em, + NotificationController notification, + ProjectFileService projectFile, + FileService fileService, + EventBus eventBus, + PlagiarismControl plagiarismControl, + GradingReportService gradingReportService + ) { + return new FinalThesisServiceImpl( + em, + notification, + projectFile, + fileService, + eventBus, + plagiarismControl, + gradingReportService + ); } @Bean public FirstMeetingServiceImpl firstMeetingService( - Provider em, - ActivityPlanFacade activityPlanFacade) - { + Provider em, + ActivityPlanFacade activityPlanFacade + ) { return new FirstMeetingServiceImpl(em, activityPlanFacade); } @@ -500,28 +535,29 @@ public class CoreConfig { @Bean public GradingReportServiceImpl gradingReportService( - EventBus eventBus, - ThesisSubmissionHistoryService thesisSubmissionHistoryService, - Clock clock, - SupervisorGradingReportRepository supervisorGradingReportRepository, - GradingReportTemplateRepoImpl gradingReportTemplateRepo, - ProjectTypeService projectTypeService) - { + EventBus eventBus, + ThesisSubmissionHistoryService thesisSubmissionHistoryService, + Clock clock, + SupervisorGradingReportRepository supervisorGradingReportRepository, + GradingReportTemplateRepoImpl gradingReportTemplateRepo, + ProjectTypeService projectTypeService + ) { return new GradingReportServiceImpl( - eventBus, - thesisSubmissionHistoryService, - clock, - supervisorGradingReportRepository, - gradingReportTemplateRepo, - projectTypeService); + eventBus, + thesisSubmissionHistoryService, + clock, + supervisorGradingReportRepository, + gradingReportTemplateRepo, + projectTypeService + ); } @Bean public GroupForumServiceImpl groupForumService( - EventBus eventBus, - GroupThreadRepository groupThreadRepository, - BasicForumService basicForumService) - { + EventBus eventBus, + GroupThreadRepository groupThreadRepository, + BasicForumService basicForumService + ) { return new GroupForumServiceImpl(groupThreadRepository, basicForumService, eventBus); } @@ -532,18 +568,27 @@ public class CoreConfig { @Bean public IdeaServiceImpl ideaService( - Provider em, - ApplicationPeriodService applicationPeriodService, - FirstMeetingRepository firstMeetingRepository, - NotificationController notificationController, - ProjectService projectService, - GeneralSystemSettingsService generalSystemSettingsService, - TargetRepository targetRepository, - IdeaRepository ideaRepository, - Clock clock) - { - return new IdeaServiceImpl(em, applicationPeriodService, firstMeetingRepository, notificationController, - projectService, generalSystemSettingsService, targetRepository, ideaRepository, clock); + Provider em, + ApplicationPeriodService applicationPeriodService, + FirstMeetingRepository firstMeetingRepository, + NotificationController notificationController, + ProjectService projectService, + GeneralSystemSettingsService generalSystemSettingsService, + TargetRepository targetRepository, + IdeaRepository ideaRepository, + Clock clock + ) { + return new IdeaServiceImpl( + em, + applicationPeriodService, + firstMeetingRepository, + notificationController, + projectService, + generalSystemSettingsService, + targetRepository, + ideaRepository, + clock + ); } @Bean @@ -573,8 +618,8 @@ public class CoreConfig { @Bean public MilestoneActivityTemplateServiceImpl milestoneActivityTemplateService( - MilestoneActivityTemplateRepository milestoneActivityTemplateRepository) - { + MilestoneActivityTemplateRepository milestoneActivityTemplateRepository + ) { return new MilestoneActivityTemplateServiceImpl(milestoneActivityTemplateRepository); } @@ -585,9 +630,9 @@ public class CoreConfig { @Bean public MilestoneServiceImpl milestoneService( - Provider em, - NotificationController notificationController) - { + Provider em, + NotificationController notificationController + ) { return new MilestoneServiceImpl(notificationController, em); } @@ -598,8 +643,8 @@ public class CoreConfig { @Bean public NationalSubjectCategoryServiceImpl nationalSubjectCategoryService( - NationalSubjectCategoryRepository nationalSubjectCategoryRepository) - { + NationalSubjectCategoryRepository nationalSubjectCategoryRepository + ) { return new NationalSubjectCategoryServiceImpl(nationalSubjectCategoryRepository); } @@ -620,13 +665,17 @@ public class CoreConfig { @Bean public OppositionReportServiceImpl oppositionReportService( - OppositionReportRepo oppositionReportRepository, - GradingReportTemplateRepo gradingReportTemplateRepository, - FileService fileService, - FinalSeminarOppositionRepo finalSeminarOppositionRepository) - { - return new OppositionReportServiceImpl(oppositionReportRepository, gradingReportTemplateRepository, - fileService, finalSeminarOppositionRepository); + OppositionReportRepo oppositionReportRepository, + GradingReportTemplateRepo gradingReportTemplateRepository, + FileService fileService, + FinalSeminarOppositionRepo finalSeminarOppositionRepository + ) { + return new OppositionReportServiceImpl( + oppositionReportRepository, + gradingReportTemplateRepository, + fileService, + finalSeminarOppositionRepository + ); } @Bean @@ -636,41 +685,48 @@ public class CoreConfig { @Bean public PeerPortalImpl peerPortal( - FileService fileService, - PeerReviewRepository peerReviewRepository, - PeerRequestRepository peerRequestRepository, - EventBus eventBus, - ProjectFileService projectFileService, - DaysService daisyService, - Clock clock) - { - return new PeerPortalImpl(fileService, peerReviewRepository, peerRequestRepository, - eventBus, projectFileService, daisyService, clock); + FileService fileService, + PeerReviewRepository peerReviewRepository, + PeerRequestRepository peerRequestRepository, + EventBus eventBus, + ProjectFileService projectFileService, + DaysService daisyService, + Clock clock + ) { + return new PeerPortalImpl( + fileService, + peerReviewRepository, + peerRequestRepository, + eventBus, + projectFileService, + daisyService, + clock + ); } @Bean public PeerRequestServiceImpl peerRequestService( - Provider em, - EventBus eventBus, - FileService fileService) - { + Provider em, + EventBus eventBus, + FileService fileService + ) { return new PeerRequestServiceImpl(em, eventBus, fileService); } @Bean public PeerReviewServiceImpl peerReviewService( - Provider em, - PeerReviewRepository peerReviewRepository) - { + Provider em, + PeerReviewRepository peerReviewRepository + ) { return new PeerReviewServiceImpl(em, peerReviewRepository); } @Bean public PlagiarismControlImpl plagiarismControl( - FileService fileService, - PlagiarismRequestRepository plagiarismRequestRepository, - UrkundSubmissionRepository urkundSubmissionRepository) - { + FileService fileService, + PlagiarismRequestRepository plagiarismRequestRepository, + UrkundSubmissionRepository urkundSubmissionRepository + ) { return new PlagiarismControlImpl(plagiarismRequestRepository, urkundSubmissionRepository, fileService); } @@ -686,9 +742,9 @@ public class CoreConfig { @Bean public ProjectFileServiceImpl projectFileService( - FileService fileService, - ProjectFileRepository projectFileRepository) - { + FileService fileService, + ProjectFileRepository projectFileRepository + ) { return new ProjectFileServiceImpl(fileService, projectFileRepository); } @@ -699,14 +755,19 @@ public class CoreConfig { @Bean public ProjectForumServiceImpl projectForumService( - EventBus eventBus, - BasicForumService basicForumService, - ProjectThreadRepository projectThreadRepository, - ForumPostRepository postRepository, - ProjectFileService projectFileService) - { - return new ProjectForumServiceImpl(projectThreadRepository, - postRepository, projectFileService, basicForumService, eventBus); + EventBus eventBus, + BasicForumService basicForumService, + ProjectThreadRepository projectThreadRepository, + ForumPostRepository postRepository, + ProjectFileService projectFileService + ) { + return new ProjectForumServiceImpl( + projectThreadRepository, + postRepository, + projectFileService, + basicForumService, + eventBus + ); } @Bean @@ -721,11 +782,11 @@ public class CoreConfig { @Bean public ProjectServiceImpl projectService( - Provider em, - EventBus eventBus, - ProjectRepo projectRepo, - Clock clock) - { + Provider em, + EventBus eventBus, + ProjectRepo projectRepo, + Clock clock + ) { return new ProjectServiceImpl(projectRepo, clock, eventBus, em); } @@ -736,17 +797,17 @@ public class CoreConfig { @Bean public PublicationMetadataServiceImpl publicationMetadataService( - PublicationMetadataRepository publicationMetadataRepository) - { + PublicationMetadataRepository publicationMetadataRepository + ) { return new PublicationMetadataServiceImpl(publicationMetadataRepository); } @Bean public ReflectionServiceImpl reflectionService( - AuthorRepository authorRepository, - FinalSeminarServiceImpl finalSeminarService, - EventBus eventBus) - { + AuthorRepository authorRepository, + FinalSeminarServiceImpl finalSeminarService, + EventBus eventBus + ) { return new ReflectionServiceImpl(authorRepository, finalSeminarService, eventBus); } @@ -762,23 +823,35 @@ public class CoreConfig { @Bean public ZipReporter reporter( - FileService fileService, - ProjectService projectService, - FinalSeminarService finalSeminarService, - ProjectForumService projectForumService, - PeerReviewService peerReviewService, - PeerRequestService peerRequestService, - GroupService groupService, - GroupForumService groupForumService, - IdeaService ideaService, - GradingReportService gradingReportService, - ReviewerInteractionService reviewerInteractionService, - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService) - { - return new ZipReporter(fileService, projectService, finalSeminarService, projectForumService, peerReviewService, - peerRequestService, groupService, groupForumService, ideaService, gradingReportService, - reviewerInteractionService, roughDraftApprovalService, finalSeminarApprovalService); + FileService fileService, + ProjectService projectService, + FinalSeminarService finalSeminarService, + ProjectForumService projectForumService, + PeerReviewService peerReviewService, + PeerRequestService peerRequestService, + GroupService groupService, + GroupForumService groupForumService, + IdeaService ideaService, + GradingReportService gradingReportService, + ReviewerInteractionService reviewerInteractionService, + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService + ) { + return new ZipReporter( + fileService, + projectService, + finalSeminarService, + projectForumService, + peerReviewService, + peerRequestService, + groupService, + groupForumService, + ideaService, + gradingReportService, + reviewerInteractionService, + roughDraftApprovalService, + finalSeminarApprovalService + ); } @Bean @@ -793,38 +866,43 @@ public class CoreConfig { @Bean public ReviewerInteractionServiceImpl reviewerInteractionService( - ReviewerThreadRepository reviewerThreadRepository, - BasicForumService forumService, - EventBus eventBus) - { + ReviewerThreadRepository reviewerThreadRepository, + BasicForumService forumService, + EventBus eventBus + ) { return new ReviewerInteractionServiceImpl(reviewerThreadRepository, forumService, eventBus); } @Bean public ReviewingServiceImpl reviewingService( - Provider em, - EventBus eventBus, - FileService fileService) - { + Provider em, + EventBus eventBus, + FileService fileService + ) { return new ReviewingServiceImpl(em, fileService, eventBus); } @Bean public ReviewerCapacityServiceImpl reviewerCapacityService( - ReviewerTargetRepository reviewerTargetRepository, - DecisionRepository decisionRepository, - UserService userService, - ProjectService projectService, - EventBus eventBus) - { - return new ReviewerCapacityServiceImpl(reviewerTargetRepository, decisionRepository, userService, - projectService, eventBus); + ReviewerTargetRepository reviewerTargetRepository, + DecisionRepository decisionRepository, + UserService userService, + ProjectService projectService, + EventBus eventBus + ) { + return new ReviewerCapacityServiceImpl( + reviewerTargetRepository, + decisionRepository, + userService, + projectService, + eventBus + ); } @Bean public ReviewerDeadlineSettingsServiceImpl reviewerDeadlineSettingsService( - ReviewerDeadlineSettingsRepository reviewerDeadlineSettingsRepository) - { + ReviewerDeadlineSettingsRepository reviewerDeadlineSettingsRepository + ) { return new ReviewerDeadlineSettingsServiceImpl(reviewerDeadlineSettingsRepository); } @@ -835,14 +913,19 @@ public class CoreConfig { @Bean public SurveyServiceImpl surveyService( - SurveyRepository surveyRepository, - QuestionRepository questionRepository, - FinalThesisService finalThesisService, - GeneralSystemSettingsService generalSystemSettingsService, - ReflectionService reflectionService) - { - return new SurveyServiceImpl(surveyRepository, questionRepository, finalThesisService, - generalSystemSettingsService, reflectionService); + SurveyRepository surveyRepository, + QuestionRepository questionRepository, + FinalThesisService finalThesisService, + GeneralSystemSettingsService generalSystemSettingsService, + ReflectionService reflectionService + ) { + return new SurveyServiceImpl( + surveyRepository, + questionRepository, + finalThesisService, + generalSystemSettingsService, + reflectionService + ); } @Bean @@ -856,20 +939,17 @@ public class CoreConfig { } @Bean - public UrkundApiImpl urkundApi( - UrkundSettingsRepository urkundSettingsRepository, - FileService fileService) - { + public UrkundApiImpl urkundApi(UrkundSettingsRepository urkundSettingsRepository, FileService fileService) { return new UrkundApiImpl(urkundSettingsRepository, fileService); } @Bean public UrkundServiceImpl urkundService( - UrkundApi urkundApi, - UrkundSubmissionRepository urkundSubmissionRepository, - Sukat sukat, - FileService fileService) - { + UrkundApi urkundApi, + UrkundSubmissionRepository urkundSubmissionRepository, + Sukat sukat, + FileService fileService + ) { return new UrkundServiceImpl(urkundApi, urkundSubmissionRepository, sukat, fileService); } @@ -895,16 +975,21 @@ public class CoreConfig { @Bean public NotificationControllerImpl notificationController( - NotificationServiceImpl notificationService, - NotificationMailFormatter notificationMailFormatter, - MailEventService mailEventService, - ReceiverConfigurationService receiverConfigurationService, - DeliveryConfigurationService deliveryConfigurationService, - Provider currentUserProvider) - { - return new NotificationControllerImpl(notificationService, - notificationMailFormatter, - mailEventService, receiverConfigurationService, deliveryConfigurationService, currentUserProvider); + NotificationServiceImpl notificationService, + NotificationMailFormatter notificationMailFormatter, + MailEventService mailEventService, + ReceiverConfigurationService receiverConfigurationService, + DeliveryConfigurationService deliveryConfigurationService, + Provider currentUserProvider + ) { + return new NotificationControllerImpl( + notificationService, + notificationMailFormatter, + mailEventService, + receiverConfigurationService, + deliveryConfigurationService, + currentUserProvider + ); } @Bean @@ -914,15 +999,21 @@ public class CoreConfig { @Bean public ReviewerAssignedDeadline reviewerAssignedDeadline( - EventBus eventBus, - ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService, - DaysService daysService, - Clock clock) - { - return new ReviewerAssignedDeadline(roughDraftApprovalService, finalSeminarApprovalService, - reviewerDeadlineSettingsService, daysService, eventBus, clock); + EventBus eventBus, + ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService, + DaysService daysService, + Clock clock + ) { + return new ReviewerAssignedDeadline( + roughDraftApprovalService, + finalSeminarApprovalService, + reviewerDeadlineSettingsService, + daysService, + eventBus, + clock + ); } @Bean @@ -932,53 +1023,67 @@ public class CoreConfig { @Bean public FinalSeminarActivityHandler finalSeminarActivityHandler( - ActivityPlanFacade activityPlanFacade, - ActivityFinalSeminarRepository activityFinalSeminarRepository, - EventBus eventBus) - { + ActivityPlanFacade activityPlanFacade, + ActivityFinalSeminarRepository activityFinalSeminarRepository, + EventBus eventBus + ) { return new FinalSeminarActivityHandler(activityPlanFacade, activityFinalSeminarRepository, eventBus); } @Bean public PostActivityUploadToForum postActivityUploadToForum( - EventBus eventBus, - ProjectForumService projectForumService, - ActivityThreadRepository activityThreadRepository) - { + EventBus eventBus, + ProjectForumService projectForumService, + ActivityThreadRepository activityThreadRepository + ) { return new PostActivityUploadToForum(projectForumService, activityThreadRepository, eventBus); } @Bean public ForumNotifications forumNotifications( - EventBus eventBus, - NotificationController notificationController, - ForumNotificationRepository forumNotificationRepository, - NotificationService notificationService) - { - return new ForumNotifications(eventBus, notificationController, forumNotificationRepository, - notificationService); + EventBus eventBus, + NotificationController notificationController, + ForumNotificationRepository forumNotificationRepository, + NotificationService notificationService + ) { + return new ForumNotifications( + eventBus, + notificationController, + forumNotificationRepository, + notificationService + ); } @Bean public ActivateCompletedMilestonesOnNewProjects activateCompletedMilestonesOnNewProjects( - EventBus eventBus, - MilestoneServiceImpl milestoneService, - PeerReviewService peerReviewService, - MilestoneActivityTemplateService milestoneActivityTemplateService, - FinalSeminarService finalSeminarService) - { - return new ActivateCompletedMilestonesOnNewProjects(peerReviewService, milestoneActivityTemplateService, - milestoneService, eventBus, finalSeminarService); + EventBus eventBus, + MilestoneServiceImpl milestoneService, + PeerReviewService peerReviewService, + MilestoneActivityTemplateService milestoneActivityTemplateService, + FinalSeminarService finalSeminarService + ) { + return new ActivateCompletedMilestonesOnNewProjects( + peerReviewService, + milestoneActivityTemplateService, + milestoneService, + eventBus, + finalSeminarService + ); } @Bean public FinalSeminarCreationSubscribers finalSeminarCreationSubscribers( - EventBus eventBus, - FinalSeminarServiceImpl finalSeminarService, - NotificationController notificationController, - AuthorRepository authorRepository) - { - return new FinalSeminarCreationSubscribers(authorRepository, finalSeminarService, notificationController, eventBus); + EventBus eventBus, + FinalSeminarServiceImpl finalSeminarService, + NotificationController notificationController, + AuthorRepository authorRepository + ) { + return new FinalSeminarCreationSubscribers( + authorRepository, + finalSeminarService, + notificationController, + eventBus + ); } @Bean @@ -988,18 +1093,18 @@ public class CoreConfig { @Bean public AddActivityPlanOnProjectStart addActivityPlanOnProjectStart( - ActivityPlanFacade activityPlanFacade, - EventBus eventBus) - { + ActivityPlanFacade activityPlanFacade, + EventBus eventBus + ) { return new AddActivityPlanOnProjectStart(activityPlanFacade, eventBus); } @Bean public Notifications notifications( - EventBus eventBus, - NotificationController notificationController, - NotificationService notificationService) - { + EventBus eventBus, + NotificationController notificationController, + NotificationService notificationService + ) { return new Notifications(notificationController, notificationService, eventBus); } @@ -1009,7 +1114,9 @@ public class CoreConfig { } @Bean - public NotificationEventServiceImpl notificationEventService(NotificationEventRepository notificationEventRepository) { + public NotificationEventServiceImpl notificationEventService( + NotificationEventRepository notificationEventRepository + ) { return new NotificationEventServiceImpl(notificationEventRepository); } diff --git a/core/src/main/java/se/su/dsv/scipro/DataInitializer.java b/core/src/main/java/se/su/dsv/scipro/DataInitializer.java index 5e38d4f9bc..aee6d0b488 100644 --- a/core/src/main/java/se/su/dsv/scipro/DataInitializer.java +++ b/core/src/main/java/se/su/dsv/scipro/DataInitializer.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; +import java.util.*; import se.su.dsv.scipro.checklist.ChecklistCategory; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.match.Keyword; @@ -16,15 +23,8 @@ import se.su.dsv.scipro.report.GradingReportTemplate; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.Month; -import java.util.*; - public class DataInitializer implements Lifecycle { + public static final int APPLICATION_PERIOD_START_MINUS_DAYS = 1; public static final int APPLICATION_PERIOD_END_PLUS_DAYS = 3; public static final int APPLICATION_PERIOD_COURSE_START_PLUS_DAYS = 5; @@ -32,12 +32,16 @@ public class DataInitializer implements Lifecycle { @Inject private UserService userService; + @Inject private PasswordService passwordService; + @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Inject private CurrentProfile profile; + @Inject private Provider em; @@ -92,14 +96,12 @@ public class DataInitializer implements Lifecycle { } @Override - public void stop() { - } + public void stop() {} private boolean noAdminUser() { return userService.findByUsername(ADMIN + MAIL) == null; } - private void createApplicationPeriodIfNotDone() { ApplicationPeriod applicationPeriod = new ApplicationPeriod("HT 2014"); applicationPeriod.setStartDate(LocalDate.now().minusDays(APPLICATION_PERIOD_START_MINUS_DAYS)); @@ -148,7 +150,11 @@ public class DataInitializer implements Lifecycle { } private void createProject(String title, User headSupervisor, User student1, User student2, User reviewer) { - Project project = Project.builder().title(title).projectType(bachelorClass).startDate(LocalDate.now().plusDays(2)).build(); + Project project = Project.builder() + .title(title) + .projectType(bachelorClass) + .startDate(LocalDate.now().plusDays(2)) + .build(); project.setHeadSupervisor(headSupervisor); project.addProjectParticipant(student2); project.addProjectParticipant(student1); @@ -240,645 +246,1457 @@ public class DataInitializer implements Lifecycle { } private GradingReportTemplate getBachelorTemplate() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(bachelorClass, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + bachelorClass, + LocalDate.of(2024, Month.JANUARY, 1) + ); List gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen.") - .descriptionEn("Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis.") - .build()); - gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U1 Sammanfattning", + "U1 Abstract", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("För 1 poäng krävs: att uppsatsen ger en introduktion till uppsatsens ämne och problem.") - .descriptionEn("Requirement for 1 point: that the thesis introduces the subject and problem of the thesis.") - .build()); - gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, gradingCriterionPointTemplates); + .descriptionEn( + "Requirement for 1 point: that the thesis introduces the subject and problem of the thesis." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U2 Introduktion", + "U2 Introduction", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras.") - .descriptionEn("Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question.") - .build()); + .description( + "För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question." + ) + .build() + ); gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, gradingCriterionPointTemplates); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet.") - .descriptionEn("Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet." + ) + .descriptionEn( + "Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag.") - .descriptionEn("For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution.") - .build()); - gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag." + ) + .descriptionEn( + "For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U4 Frågeställning", + "U4 Research question", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till.") - .descriptionEn("Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten.") - .descriptionEn("For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research.") - .build()); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten." + ) + .descriptionEn( + "For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras.") - .descriptionEn("Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår.") - .descriptionEn("For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident.") - .build()); - gradingReportTemplate.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår." + ) + .descriptionEn( + "For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras.") - .descriptionEn("Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta.") - .descriptionEn("For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this.") - .build()); - gradingReportTemplate.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta." + ) + .descriptionEn( + "For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras.") - .descriptionEn("Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras.") - .descriptionEn("For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered.") - .build()); + .description( + "För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras." + ) + .descriptionEn( + "For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered." + ) + .build() + ); gradingReportTemplate.addProjectCriterion("U8 Resultat", "U8 Result", 1, gradingCriterionPointTemplates); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras.") - .descriptionEn("Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs.") - .descriptionEn("For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made.") - .build()); - gradingReportTemplate.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs." + ) + .descriptionEn( + "For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk.") - .descriptionEn("Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language.") - .build()); - gradingReportTemplate.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig.") - .descriptionEn("Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood.") - .build()); - gradingReportTemplate.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig." + ) + .descriptionEn( + "Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U11 Argumentation", + "U11 Argumentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas.") - .descriptionEn("Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included.") - .build()); - gradingReportTemplate.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas." + ) + .descriptionEn( + "Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included." + ) + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster.") - .descriptionEn("Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet.") - .descriptionEn("For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet." + ) + .descriptionEn( + "For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter.") - .descriptionEn("For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products.") - .build()); - gradingReportTemplate.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter." + ) + .descriptionEn( + "For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products." + ) + .build() + ); + gradingReportTemplate + .addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 0, + gradingCriterionPointTemplates + ) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen.") - .descriptionEn("Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar.") - .descriptionEn("For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, gradingCriterionPointTemplates, AbstractGradingCriterion.Flag.OPPOSITION); + .description( + "För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar." + ) + .descriptionEn( + "For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements." + ) + .build() + ); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats.") - .descriptionEn("Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats." + ) + .descriptionEn( + "Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown." + ) + .build() + ); + gradingReportTemplate.addIndividualCriterion( + "Ö2 Presentationer", + "Ö2 Presentations", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten.") - .descriptionEn("Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings." + ) + .build() + ); + gradingReportTemplate.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs.") - .descriptionEn("Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions." + ) + .build() + ); + gradingReportTemplate + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet.") - .descriptionEn("Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet." + ) + .descriptionEn( + "Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar." + ) + .build() + ); + gradingReportTemplate + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + gradingCriterionPointTemplates + ) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument.") - .descriptionEn("Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document.") - .build()); - gradingReportTemplate.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 0, gradingCriterionPointTemplates, AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document." + ) + .build() + ); + gradingReportTemplate + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 0, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplate; } private GradingReportTemplate getMasterTemplate() { - GradingReportTemplate gradingReportTemplateMaster = new GradingReportTemplate(masterClass, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplateMaster = new GradingReportTemplate( + masterClass, + LocalDate.of(2024, Month.JANUARY, 1) + ); List gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen.") - .descriptionEn("Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U1 Sammanfattning", + "U1 Abstract", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("För 1 poäng krävs: att uppsatsen ger en introduktion till uppsatsens ämne och problem.") - .descriptionEn("Requirement for 1 point: that the thesis introduces the subject and problem of the thesis.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, gradingCriterionPointTemplates); + .descriptionEn( + "Requirement for 1 point: that the thesis introduces the subject and problem of the thesis." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U2 Introduktion", + "U2 Introduction", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras.") - .descriptionEn("Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question.") - .build()); + .description( + "För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question." + ) + .build() + ); gradingReportTemplateMaster.addProjectCriterion("U3 Problem", "U3 Problem", 1, gradingCriterionPointTemplates); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet.") - .descriptionEn("Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet." + ) + .descriptionEn( + "Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag.") - .descriptionEn("For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag." + ) + .descriptionEn( + "For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U4 Frågeställning", + "U4 Research question", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till.") - .descriptionEn("Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten.") - .descriptionEn("For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten." + ) + .descriptionEn( + "For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att en omfattande litteraturstudie redovisas som ligger till grund för en positionering och värdering av uppsatsens kunskapsbidrag i ett vetenskapligt sammanhang.") - .descriptionEn("For 3 points the following is also required: that a comprehensive literature study is presented that is the basis for placing and evaluating the research contribution of the thesis in a scientific context.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 2, gradingCriterionPointTemplates); + .description( + "För 3 poäng krävs dessutom: att en omfattande litteraturstudie redovisas som ligger till grund för en positionering och värdering av uppsatsens kunskapsbidrag i ett vetenskapligt sammanhang." + ) + .descriptionEn( + "For 3 points the following is also required: that a comprehensive literature study is presented that is the basis for placing and evaluating the research contribution of the thesis in a scientific context." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras.") - .descriptionEn("Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår.") - .descriptionEn("For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår." + ) + .descriptionEn( + "For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att metodvalet diskuteras i förhållande till forskningsstrategier och forskningsmetoder som tillämpats i relaterade aktuella vetenskapliga studier och som kan betraktas som state-of-the-art.") - .descriptionEn("For 3 points the following is also required: that the choice of method is discussed in relation to the research strategies and methods that are used in current, related research studies that can be regarded as state-of-the-art.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 2, gradingCriterionPointTemplates); + .description( + "För 3 poäng krävs dessutom: att metodvalet diskuteras i förhållande till forskningsstrategier och forskningsmetoder som tillämpats i relaterade aktuella vetenskapliga studier och som kan betraktas som state-of-the-art." + ) + .descriptionEn( + "For 3 points the following is also required: that the choice of method is discussed in relation to the research strategies and methods that are used in current, related research studies that can be regarded as state-of-the-art." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras.") - .descriptionEn("Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta.") - .descriptionEn("For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta." + ) + .descriptionEn( + "For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) .description("För 3 poäng krävs dessutom: att det finns ett betydande djup i dataanalysen.") - .descriptionEn("For 3 points the following is also required: that there is a meaningful depth to the data analysis.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 2, gradingCriterionPointTemplates); + .descriptionEn( + "For 3 points the following is also required: that there is a meaningful depth to the data analysis." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras.") - .descriptionEn("Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras.") - .descriptionEn("For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras." + ) + .descriptionEn( + "For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att resultaten är väl beskrivna, av betydande omfattning och av hög kvalitet, så att väl underbyggda slutsatser av relevans för frågeställningen kan dras.") - .descriptionEn("For 3 points the following is also required: that the results are well written and of considerable magnitude and high quality so that well-grounded conclusions of the relevance for the research question can be made.") - .build()); + .description( + "För 3 poäng krävs dessutom: att resultaten är väl beskrivna, av betydande omfattning och av hög kvalitet, så att väl underbyggda slutsatser av relevans för frågeställningen kan dras." + ) + .descriptionEn( + "For 3 points the following is also required: that the results are well written and of considerable magnitude and high quality so that well-grounded conclusions of the relevance for the research question can be made." + ) + .build() + ); gradingReportTemplateMaster.addProjectCriterion("U8 Resultat", "U8 Result", 2, gradingCriterionPointTemplates); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras.") - .descriptionEn("Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs.") - .descriptionEn("For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 2, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs." + ) + .descriptionEn( + "For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk.") - .descriptionEn("Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig.") - .descriptionEn("Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig." + ) + .descriptionEn( + "Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U11 Argumentation", + "U11 Argumentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas.") - .descriptionEn("Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas." + ) + .descriptionEn( + "Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster.") - .descriptionEn("Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet.") - .descriptionEn("For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet." + ) + .descriptionEn( + "For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter.") - .descriptionEn("For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter." + ) + .descriptionEn( + "For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(4) - .description("För 4 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras i en vetenskaplig tidskrift av god kvalitet.") - .descriptionEn("For 4 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific journal of good quality.") - .build()); - gradingReportTemplateMaster.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 2, gradingCriterionPointTemplates); + .description( + "För 4 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras i en vetenskaplig tidskrift av god kvalitet." + ) + .descriptionEn( + "For 4 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific journal of good quality." + ) + .build() + ); + gradingReportTemplateMaster.addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen.") - .descriptionEn("Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar.") - .descriptionEn("For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, gradingCriterionPointTemplates, - AbstractGradingCriterion.Flag.OPPOSITION); + .description( + "För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar." + ) + .descriptionEn( + "For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements." + ) + .build() + ); + gradingReportTemplateMaster.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats.") - .descriptionEn("Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats." + ) + .descriptionEn( + "Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown." + ) + .build() + ); + gradingReportTemplateMaster.addIndividualCriterion( + "Ö2 Presentationer", + "Ö2 Presentations", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten.") - .descriptionEn("Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings." + ) + .build() + ); + gradingReportTemplateMaster.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs.") - .descriptionEn("Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions." + ) + .build() + ); + gradingReportTemplateMaster + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet.") - .descriptionEn("Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet." + ) + .descriptionEn( + "Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar." + ) + .build() + ); + gradingReportTemplateMaster + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + gradingCriterionPointTemplates + ) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument.") - .descriptionEn("Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document.") - .build()); - gradingReportTemplateMaster.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 1, gradingCriterionPointTemplates, AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document." + ) + .build() + ); + gradingReportTemplateMaster + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 1, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplateMaster; } private GradingReportTemplate getMagisterTemplate() { - GradingReportTemplate gradingReportTemplateMagister = new GradingReportTemplate(magisterClass, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplateMagister = new GradingReportTemplate( + magisterClass, + LocalDate.of(2024, Month.JANUARY, 1) + ); List gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen.") - .descriptionEn("Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsens sammanfattning korrekt återspeglar uppsatsens innehåll genom att beskriva problem, frågeställning, metodval, metodtillämpning, resultat och slutsatser samt att den kan läsas och förstås fristående från uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the abstract of the thesis accurately portrays the contents of the thesis by describing the problem, the research question, the choice and application of the research methods, the result, and conclusions and that it can be read and understood separately from the thesis." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U1 Sammanfattning", + "U1 Abstract", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("För 1 poäng krävs: att uppsatsen ger en introduktion till uppsatsens ämne och problem.") - .descriptionEn("Requirement for 1 point: that the thesis introduces the subject and problem of the thesis.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, gradingCriterionPointTemplates); + .descriptionEn( + "Requirement for 1 point: that the thesis introduces the subject and problem of the thesis." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U2 Introduktion", + "U2 Introduction", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras.") - .descriptionEn("Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U3 Problem", "U3 Problem", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att det finns ett problem av generellt intresse som helt eller delvis kan lösas genom att frågeställningen besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that a problem of general interest exists that entirely or partially can be solved by answering the research question." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U3 Problem", + "U3 Problem", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet.") - .descriptionEn("Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: en tydligt formulerad och väl avgränsad frågeställning som är av generellt intresse. Studenten skall självständigt identifiera och formulera frågeställningen. Frågeställningen skall motiveras utifrån problemet så att det är tydligt hur svaret på frågan löser en del av eller hela problemet." + ) + .descriptionEn( + "Requirement for 1 point: a clearly formulated and delimited research question that is of general interest. The student is responsible for identifying and formulating the research question. The research question should derive from the presented problem so that it is clear how the answer to the research question solves a portion or the entire problem." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag.") - .descriptionEn("For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: en innovativ frågeställning som ger förutsättningar för att arbetet skall kunna ge ett signifikant bidrag." + ) + .descriptionEn( + "For 2 points the following is also required: an innovative research question that provides necessary conditions so that the thesis could provide a significant scientific contribution." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U4 Frågeställning", + "U4 Research question", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till.") - .descriptionEn("Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att uppsatsen ger en ämnesmässig förankring utifrån tidigare vetenskapliga arbeten. Det skall också framgå till vilket område inom data- och systemvetenskap som arbetet bidrar genom en redovisning av de vetenskapliga arbeten som uppsatsen relaterar till." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis provides a base for the topic of the thesis based on previous scientific research. The area within computer and systems sciences to which the thesis contributes should also be named by presenting the scientific research to which the thesis refers." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten.") - .descriptionEn("For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att en djupgående och kritisk diskussion förs om hur arbetet bygger vidare på tidigare vetenskapliga arbeten." + ) + .descriptionEn( + "For 2 points the following is also required: that a deep and critical discussion is made about how the thesis builds upon previous scientific research." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras.") - .descriptionEn("Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att valet av forskningsstrategier och forskningsmetoder tydligt beskrivs och motiveras utifrån forskningsfrågan, att minst en alternativ forskningsstrategi och forskningsmetod som kan användas för att angripa frågeställningen diskuteras, samt att relevanta etiska överväganden diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the choice of a research strategy and research methods is clearly described and motivated based on the research question, that at least one alternative research strategy and method that could be used to solve the research question is discussed, as well as that relevant ethical considerations are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår.") - .descriptionEn("For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att alternativa tillämpliga forskningsstrategier och forskningsmetoder diskuteras utförligt och att ett djupgående resonemang kring strategi- och metodval förs, där motiven för gjorda val tydligt framgår." + ) + .descriptionEn( + "For 2 points the following is also required: that alternative, applicable research strategies and methods are comprehensively discussed and that a profound reasoning about the chosen strategies and methods is made, where the motives for choices made are clearly evident." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras.") - .descriptionEn("Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att tillämpningen av valda forskningsstrategier och forskningsmetoder är tydligt beskriven, att användning av programvaruverktyg beskrivs, samt att relevanta etiska aspekter diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the application of the chosen scientific strategies and methods are clearly described, that the use of software tools is described, and that relevant ethical aspects are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta.") - .descriptionEn("For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 1, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att tillämpningen av forskningsstrategier och forskningsmetoder är genomförd i enlighet med de krav som dessa ställer och att det finns en tydlig argumentation för detta." + ) + .descriptionEn( + "For 2 points the following is also required: that the application of research strategies and methods are done in accordance to the demands of said methods and strategies and that a clear argumentation exists for this." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras.") - .descriptionEn("Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att resultaten är av sådan omfattning och kvalitet och presenteras på ett sådant sätt att frågeställningen till viss del kan besvaras." + ) + .descriptionEn( + "Requirement for 1 point: that the results are of such a magnitude and quality and are presented in such a way that the research question can to some extent be answered." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras.") - .descriptionEn("For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att resultaten är av tillräcklig omfattning och av hög kvalitet, så att frågeställningen till stor del kan besvaras." + ) + .descriptionEn( + "For 2 points the following is also required: that the results are of sufficient magnitude and high quality so that the research question can to a great extent be answered." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att resultaten är väl beskrivna, av betydande omfattning och av hög kvalitet, så att väl underbyggda slutsatser av relevans för frågeställningen kan dras.") - .descriptionEn("For 3 points the following is also required: that the results are well written and of considerable magnitude and high quality so that well-grounded conclusions of the relevance for the research question can be made.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U8 Resultat", "U8 Result", 2, gradingCriterionPointTemplates); + .description( + "För 3 poäng krävs dessutom: att resultaten är väl beskrivna, av betydande omfattning och av hög kvalitet, så att väl underbyggda slutsatser av relevans för frågeställningen kan dras." + ) + .descriptionEn( + "For 3 points the following is also required: that the results are well written and of considerable magnitude and high quality so that well-grounded conclusions of the relevance for the research question can be made." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U8 Resultat", + "U8 Result", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras.") - .descriptionEn("Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att frågeställningen ges ett tydligt svar, att begränsningar i studiens upplägg och deras påverkan på slutsatserna diskuteras liksom hur resultaten relaterar till tidigare studier, att möjliga framtida studier med utgångspunkt från den aktuella studien diskuteras, samt att etiska och samhälleliga konsekvenser av studiens slutsatser diskuteras." + ) + .descriptionEn( + "Requirement for 1 point: that the research question has a clear answer, that the limitations in the design of the study and their impact on the conclusions are discussed as well as how the results relate to previous research; that possible future research based on the study in the thesis is discussed; and that ethical and societal consequences of the conclusions in the thesis are discussed." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs.") - .descriptionEn("For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 2, gradingCriterionPointTemplates); + .description( + "För 2 poäng krävs dessutom: att studiens begränsningar diskuteras utförligt och att ett djupgående resonemang om möjliga och relevanta framtida studier förs." + ) + .descriptionEn( + "For 2 points the following is also required: that the limitations of the study are thoroughly discussed and that a profound reasoning about possible and relevant future studies is made." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 2, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk.") - .descriptionEn("Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att uppsatsen är indelad i tydliga och väl sammanhållna avsnitt och uppfyller grundläggande krav på layout samt att texten är skriven med ett adekvat och professionellt språkbruk." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis is divided into distinct, logical, and coherent sections; that it fulfils the fundamental layout requirements; and that the text is written with an adequate and professional language." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig.") - .descriptionEn("Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att argumentationen är välgrundad, logiskt sammanhållen, koncis, tydlig och lättbegriplig." + ) + .descriptionEn( + "Requirement for 1 point: that the argumentation is well grounded, logically coherent, concise, clear, and easily understood." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U11 Argumentation", + "U11 Argumentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas.") - .descriptionEn("Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att tidigare arbeten refereras till på ett korrekt sätt enligt ett vedertaget referenssystem, att en tydlig förteckning över använda källor anges enligt samma system, att samtliga citat från tidigare arbeten anges tydligt, samt att relevanta bilagor inkluderas." + ) + .descriptionEn( + "Requirement for 1 point: that references in the thesis to previous research are made in a correct way according to a recognized reference system, that a clear listing of used references is made in the same system, that all quotes from previous work are clearly specified, and that relevant supplemental attachments are included." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster.") - .descriptionEn("Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att arbetet ger originella och signifikanta kunskapsbidrag, till exempel i form av idéer, artefakter, produkter eller tjänster." + ) + .descriptionEn( + "Requirement for 1 point: that the thesis contributes with significant or original research contributions, in the form of new ideas, artifacts, products, or services." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet.") - .descriptionEn("For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 2 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig workshop av god kvalitet." + ) + .descriptionEn( + "For 2 points the following is also required: that the research contributions are of such quality that the thesis could be presented in a scientific workshop of good quality." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(3) - .description("För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter.") - .descriptionEn("For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products.") - .build()); - gradingReportTemplateMagister.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 1, gradingCriterionPointTemplates); + .description( + "För 3 poäng krävs dessutom: att kunskapsbidragen är av sådan kvalitet att arbetet skulle kunna presenteras på en vetenskaplig konferens av god kvalitet eller kunna ligga till grund för användbara lösningar, till exempel i form av kommersialiserbara produkter." + ) + .descriptionEn( + "For 3 points the following is also required: that the research contributions are of such quality that the thesis could be presented at an academic conference of good quality or that they could be a basis for useful solutions, for example commercializable products." + ) + .build() + ); + gradingReportTemplateMagister.addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen.") - .descriptionEn("Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis.") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .description( + "För 1 poäng krävs: att oppositionsrapporten ger en kort sammanfattning av det utvärderade arbetet, resonerar kring uppsatsens vetenskapliga förankring, originalitet, signifikans, formulering av problem och frågeställning, metodval och metodtillämpning, samt innehåller tydliga förslag till förbättringar; och att oppositionsrapporten inkluderar både redigering och korrekturläsning av uppsatsen." + ) + .descriptionEn( + "Requirement for 1 point: that the opposition report provides a short summary of the evaluated thesis, that it deliberates about the scientific basis, originality, significance, and formulation of the problem and research question, as well as that it contains clear suggestions for improvements; and that the opposition report includes proofreading as well as editing of the thesis." + ) + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) - .description("För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar.") - .descriptionEn("For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, gradingCriterionPointTemplates, - AbstractGradingCriterion.Flag.OPPOSITION); + .description( + "För 2 poäng krävs dessutom: att oppositionsrapporten ingående och välbalanserat beskriver styrkor och svagheter hos det utvärderade arbetet ur flera aspekter samt att den innehåller tydliga och välmotiverade förslag till förbättringar." + ) + .descriptionEn( + "For 2 points the following is also required: that the opposition report thoroughly and in a well-balanced way describes from numerous aspects the strengths and weaknesses of the evaluated thesis and that it offers clear and well-motivated suggestions for improvements." + ) + .build() + ); + gradingReportTemplateMagister.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats.") - .descriptionEn("Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att muntliga presentationer av tillräcklig kvalitet har hållits vid anvisade tillfällen samt att förmåga att muntligt försvara det egna arbetet har uppvisats." + ) + .descriptionEn( + "Requirement for 1 point: that oral presentations are of sufficient quality, that they have been given on the assigned dates, and that the ability to orally defend one’s own thesis has been shown." + ) + .build() + ); + gradingReportTemplateMagister.addIndividualCriterion( + "Ö2 Presentationer", + "Ö2 Presentations", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten.") - .descriptionEn("Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, gradingCriterionPointTemplates); + .description( + "För 1 poäng krävs: att förmåga att muntligt diskutera och ge konstruktiv kritik när det gäller andras arbete har uppvisats vid seminarier och möten." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to orally discuss and provide constructive criticism regarding others’ work has been shown in seminars and meetings." + ) + .build() + ); + gradingReportTemplateMagister.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + gradingCriterionPointTemplates + ); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs.") - .descriptionEn("Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att i tid förbereda och leverera material och presentationer vid alla tillfällen som detta krävs." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to prepare and deliver material and presentations on time has been demonstrated at all the necessary occasions." + ) + .build() + ); + gradingReportTemplateMagister + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, gradingCriterionPointTemplates) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet.") - .descriptionEn("Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, gradingCriterionPointTemplates).setFx(false); + .description( + "För 1 poäng krävs: att endast en mindre revision av uppsatsen krävs efter slutseminariet." + ) + .descriptionEn( + "Requirement for 1 point: that only one smaller revision of the thesis is needed after the final seminar." + ) + .build() + ); + gradingReportTemplateMagister + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + gradingCriterionPointTemplates + ) + .setFx(false); gradingCriterionPointTemplates = initPointTemplates(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) - .description("För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument.") - .descriptionEn("Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document.") - .build()); - gradingReportTemplateMagister.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 1, gradingCriterionPointTemplates, AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + .description( + "För 1 poäng krävs: att förmåga har uppvisats att reflektera över det genomförda examensarbetet genom individuellt författande av ett reflektionsdokument." + ) + .descriptionEn( + "Requirement for 1 point: that the ability to reflect about the thesis work has been demonstrated through the individual writing of a reflection document." + ) + .build() + ); + gradingReportTemplateMagister + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 1, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplateMagister; } @@ -909,36 +1727,159 @@ public class DataInitializer implements Lifecycle { } private void createMilestonesIfNotDone() { - MilestonePhaseTemplate milestonePhaseTemplate1 = createMileStonePhase("Phase 1 - Preparations", "This is phase 1."); - MilestonePhaseTemplate milestonePhaseTemplate2 = createMileStonePhase("Phase 2 - Research question and method", "This is phase 2."); - MilestonePhaseTemplate milestonePhaseTemplate3 = createMileStonePhase("Phase 3 - Result and discussion", "This is phase 3."); - MilestonePhaseTemplate milestonePhaseTemplate4 = createMileStonePhase("Phase 4 - Final seminar", "This is phase 4."); - MilestonePhaseTemplate milestonePhaseTemplate5 = createMileStonePhase("Phase 5 - Examination", "This is phase 5."); + MilestonePhaseTemplate milestonePhaseTemplate1 = createMileStonePhase( + "Phase 1 - Preparations", + "This is phase 1." + ); + MilestonePhaseTemplate milestonePhaseTemplate2 = createMileStonePhase( + "Phase 2 - Research question and method", + "This is phase 2." + ); + MilestonePhaseTemplate milestonePhaseTemplate3 = createMileStonePhase( + "Phase 3 - Result and discussion", + "This is phase 3." + ); + MilestonePhaseTemplate milestonePhaseTemplate4 = createMileStonePhase( + "Phase 4 - Final seminar", + "This is phase 4." + ); + MilestonePhaseTemplate milestonePhaseTemplate5 = createMileStonePhase( + "Phase 5 - Examination", + "This is phase 5." + ); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "First meeting held", "First meeting with supervisor.", milestonePhaseTemplate1, null); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Project plan approved", "Project plan approved by supervisor.", milestonePhaseTemplate1, null); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "First meeting held", + "First meeting with supervisor.", + milestonePhaseTemplate1, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Project plan approved", + "Project plan approved by supervisor.", + milestonePhaseTemplate1, + null + ); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Rough draft sent to reviewer for approval", "Rough draft approved by reviewer.", milestonePhaseTemplate2, null); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Rough draft approved by reviewer", "Rough draft approved.", milestonePhaseTemplate2, null); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Peer review 1", "This is a recommendation of when to perform peer review 1.", milestonePhaseTemplate2, MilestoneActivityTemplate.PEER_REVIEW_ONE); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Rough draft sent to reviewer for approval", + "Rough draft approved by reviewer.", + milestonePhaseTemplate2, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Rough draft approved by reviewer", + "Rough draft approved.", + milestonePhaseTemplate2, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Peer review 1", + "This is a recommendation of when to perform peer review 1.", + milestonePhaseTemplate2, + MilestoneActivityTemplate.PEER_REVIEW_ONE + ); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Result and discussion completed and approved", "Result and discussion.", milestonePhaseTemplate3, null); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Peer review 2", "This is a recommendation of when to perform peer review 2.", milestonePhaseTemplate3, MilestoneActivityTemplate.PEER_REVIEW_TWO); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Result and discussion completed and approved", + "Result and discussion.", + milestonePhaseTemplate3, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Peer review 2", + "This is a recommendation of when to perform peer review 2.", + milestonePhaseTemplate3, + MilestoneActivityTemplate.PEER_REVIEW_TWO + ); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Thesis approved for final seminar presentation", "Thesis approved for final seminar.", milestonePhaseTemplate4, null); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Final seminar created", "Creation of final seminar.", milestonePhaseTemplate4, MilestoneActivityTemplate.CREATE_SEMINAR); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Final seminar thesis uploaded", "Final seminar thesis uploaded.", milestonePhaseTemplate4, MilestoneActivityTemplate.THESIS_UPLOADED); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Perform an oral and written opposition", "Opposition.", milestonePhaseTemplate4, null); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Active participation in a final seminar", "Active participation.", milestonePhaseTemplate4, null); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Defend the thesis in a final seminar", "Defence of final thesis.", milestonePhaseTemplate4, null); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Thesis approved for final seminar presentation", + "Thesis approved for final seminar.", + milestonePhaseTemplate4, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Final seminar created", + "Creation of final seminar.", + milestonePhaseTemplate4, + MilestoneActivityTemplate.CREATE_SEMINAR + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Final seminar thesis uploaded", + "Final seminar thesis uploaded.", + milestonePhaseTemplate4, + MilestoneActivityTemplate.THESIS_UPLOADED + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Perform an oral and written opposition", + "Opposition.", + milestonePhaseTemplate4, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Active participation in a final seminar", + "Active participation.", + milestonePhaseTemplate4, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Defend the thesis in a final seminar", + "Defence of final thesis.", + milestonePhaseTemplate4, + null + ); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Revised final thesis of the submitted thesis", "Revised final thesis.", milestonePhaseTemplate5, null); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Originality report approved", "Originality report.", milestonePhaseTemplate5, null); - createMileStone(MilestoneActivityTemplate.Type.PROJECT, "Supervisor and reviewer final grading report submitted", "Final grading report.", milestonePhaseTemplate5, null); - createMileStone(MilestoneActivityTemplate.Type.STUDENT, "Grading completed", "Grading completed by examiner.", milestonePhaseTemplate5, null); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Revised final thesis of the submitted thesis", + "Revised final thesis.", + milestonePhaseTemplate5, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Originality report approved", + "Originality report.", + milestonePhaseTemplate5, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.PROJECT, + "Supervisor and reviewer final grading report submitted", + "Final grading report.", + milestonePhaseTemplate5, + null + ); + createMileStone( + MilestoneActivityTemplate.Type.STUDENT, + "Grading completed", + "Grading completed by examiner.", + milestonePhaseTemplate5, + null + ); } - private void createMileStone(MilestoneActivityTemplate.Type type, String title, String description, MilestonePhaseTemplate milestonePhaseTemplate, String code) { + private void createMileStone( + MilestoneActivityTemplate.Type type, + String title, + String description, + MilestonePhaseTemplate milestonePhaseTemplate, + String code + ) { MilestoneActivityTemplate milestoneActivityTemplate = new MilestoneActivityTemplate(type, title, description); milestoneActivityTemplate.addProjectType(bachelorClass); milestoneActivityTemplate.addProjectType(masterClass); diff --git a/core/src/main/java/se/su/dsv/scipro/RepositoryConfiguration.java b/core/src/main/java/se/su/dsv/scipro/RepositoryConfiguration.java index 6a2167bc1f..d759376ea1 100644 --- a/core/src/main/java/se/su/dsv/scipro/RepositoryConfiguration.java +++ b/core/src/main/java/se/su/dsv/scipro/RepositoryConfiguration.java @@ -53,6 +53,7 @@ import se.su.dsv.scipro.system.UserRepoImpl; @Configuration(proxyBeanMethods = false) public class RepositoryConfiguration { + @Bean public GradingHistoryEventRepositoryImpl gradingHistoryEventRepository(Provider em) { return new GradingHistoryEventRepositoryImpl(em); @@ -104,7 +105,9 @@ public class RepositoryConfiguration { } @Bean - public FinalSeminarActiveParticipationRepositoryImpl finalSeminarActiveParticipationRepository(Provider em) { + public FinalSeminarActiveParticipationRepositoryImpl finalSeminarActiveParticipationRepository( + Provider em + ) { return new FinalSeminarActiveParticipationRepositoryImpl(em); } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/Action.java b/core/src/main/java/se/su/dsv/scipro/activityplan/Action.java index 5e7884420a..8b0e0dad2f 100644 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/Action.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/Action.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.activityplan; public enum Action { - NONE, HAND_IN, PEER, FINAL_THESIS, FINAL_SEMINAR + NONE, + HAND_IN, + PEER, + FINAL_THESIS, + FINAL_SEMINAR, } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/Activity.java b/core/src/main/java/se/su/dsv/scipro/activityplan/Activity.java index 28e834f5ef..fe3e3392a1 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/Activity.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/Activity.java @@ -1,51 +1,48 @@ package se.su.dsv.scipro.activityplan; import com.querydsl.core.annotations.QueryInit; - import jakarta.persistence.Basic; -import jakarta.persistence.Table; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; -import jakarta.persistence.GenerationType; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; - -import se.su.dsv.scipro.checklist.Checklist; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; - +import jakarta.persistence.Table; import java.io.Serializable; import java.util.Comparator; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.checklist.Checklist; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; @Entity @Table(name = "activity") @Cacheable(true) public class Activity extends LazyDeletableDomainObject { - public static IActivityPlan builder(){ + public static IActivityPlan builder() { return new Builder(); } // @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; @Basic - @Column(name = "title", nullable=false) + @Column(name = "title", nullable = false) private String title; @Basic - @Column(name = "date", nullable=false) + @Column(name = "date", nullable = false) private Date date; @Basic @@ -59,28 +56,31 @@ public class Activity extends LazyDeletableDomainObject { @Enumerated(EnumType.STRING) @Column(name = "action") private Action action = Action.NONE; + // // @ManyToOne(optional = false) - @JoinColumn(name = "activity_plan_id", referencedColumnName = "id") + @JoinColumn(name = "activity_plan_id", referencedColumnName = "id") @QueryInit("project") - private ActivityPlan activityPlan; + private ActivityPlan activityPlan; @ManyToOne @JoinColumn(name = "checklist_id", referencedColumnName = "id") private Checklist checklist; - @OneToOne(optional = true, cascade = CascadeType.ALL) + @OneToOne(optional = true, cascade = CascadeType.ALL) @JoinColumn(name = "upload_file_reference_id", referencedColumnName = "id") - private FileReference fileUpload; + private FileReference fileUpload; + // // - public Activity() { - this.title = ""; - this.description = ""; - } + public Activity() { + this.title = ""; + this.description = ""; + } + // // @@ -156,6 +156,7 @@ public class Activity extends LazyDeletableDomainObject { public void setFileUpload(FileReference fileUpload) { this.fileUpload = fileUpload; } + // // @@ -164,8 +165,7 @@ public class Activity extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof Activity)) return false; final Activity other = (Activity) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -174,19 +174,22 @@ public class Activity extends LazyDeletableDomainObject { } @Override - public String toString(){ - return "Event: "+ getTitle()+"@"+getDate(); - } + public String toString() { + return "Event: " + getTitle() + "@" + getDate(); + } + // // protected boolean canEqual(final Object other) { return other instanceof Activity; } + // // public static class ByDateComparator implements Comparator, Serializable { + @Override public int compare(Activity o1, Activity o2) { return o1.getDate().compareTo(o2.getDate()); @@ -194,6 +197,7 @@ public class Activity extends LazyDeletableDomainObject { } public static class Builder implements IActivityPlan, IDate, IName, IDescription, IBuild { + private ActivityPlan activityPlan; private Date date; private String name; @@ -247,7 +251,7 @@ public class Activity extends LazyDeletableDomainObject { } public interface IDate { - IName date (Date date); + IName date(Date date); } public interface IName { diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityFileUploadedEvent.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityFileUploadedEvent.java index 4493a0cea2..ac77b7496a 100644 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityFileUploadedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityFileUploadedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.activityplan; import se.su.dsv.scipro.file.FileDescription; public class ActivityFileUploadedEvent { + private final Activity activity; private final FileDescription fileDescription; diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlan.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlan.java index 8af7cd3374..d5ce02780a 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlan.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlan.java @@ -11,18 +11,16 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; - import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import java.util.Date; import java.util.Objects; import java.util.Set; import java.util.TreeSet; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity -@Table(name ="activity_plan") +@Table(name = "activity_plan") @Cacheable(true) public class ActivityPlan extends DomainObject { @@ -31,28 +29,31 @@ public class ActivityPlan extends DomainObject { } // - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; @Basic @Column(name = "start_date") private Date startDate; + // // - @OneToOne(optional=false) + @OneToOne(optional = false) @JoinColumn(name = "project_id", referencedColumnName = "id") private Project project; + // // - @OneToMany(mappedBy= "activityPlan",cascade=CascadeType.PERSIST, orphanRemoval = true) - private Set activities = new TreeSet<>(new Activity.ByDateComparator()); + @OneToMany(mappedBy = "activityPlan", cascade = CascadeType.PERSIST, orphanRemoval = true) + private Set activities = new TreeSet<>(new Activity.ByDateComparator()); + // // - @Override + @Override public Long getId() { return this.id; } @@ -84,6 +85,7 @@ public class ActivityPlan extends DomainObject { public void setActivities(Set activities) { this.activities = activities; } + // // @@ -92,11 +94,13 @@ public class ActivityPlan extends DomainObject { if (o == this) return true; if (!(o instanceof ActivityPlan)) return false; final ActivityPlan other = (ActivityPlan) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getActivities(), other.getActivities()) - && Objects.equals(this.getProject(), other.getProject()) - && Objects.equals(this.getStartDate(), other.getStartDate()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getActivities(), other.getActivities()) && + Objects.equals(this.getProject(), other.getProject()) && + Objects.equals(this.getStartDate(), other.getStartDate()) + ); } @Override @@ -106,19 +110,31 @@ public class ActivityPlan extends DomainObject { @Override public String toString() { - return "ActivityPlan(id=" + this.getId() + ", activities=" + this.getActivities() + ", project=" + - this.getProject() + ", startDate=" + this.getStartDate() + ")"; + return ( + "ActivityPlan(id=" + + this.getId() + + ", activities=" + + this.getActivities() + + ", project=" + + this.getProject() + + ", startDate=" + + this.getStartDate() + + ")" + ); } + // // protected boolean canEqual(final Object other) { return other instanceof ActivityPlan; } + // // categories = new ArrayList<>(template.getCategories()); - Checklist checklist = Checklist.builder().name(template.getName()).project(project).description(template.getDescription()).build(); + Checklist checklist = Checklist.builder() + .name(template.getName()) + .project(project) + .description(template.getDescription()) + .build(); checklist.setCategories(categories); for (String question : template.getQuestions()) { ChecklistQuestion clQuestion = new ChecklistQuestion(question, checklist.getNumberOfQuestions()); @@ -350,5 +377,4 @@ public class ActivityPlanFacadeImpl implements ActivityPlanFacade { } return true; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanService.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanService.java index a5b64a39b4..2fa451c837 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanService.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanService.java @@ -2,6 +2,4 @@ package se.su.dsv.scipro.activityplan; import se.su.dsv.scipro.system.GenericService; -public interface ActivityPlanService extends GenericService { -} - +public interface ActivityPlanService extends GenericService {} diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanServiceImpl.java index 904ed006dc..3438d45b72 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanServiceImpl.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.activityplan; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; -public class ActivityPlanServiceImpl extends AbstractServiceImpl implements ActivityPlanService { - @Inject - public ActivityPlanServiceImpl(Provider em) { +public class ActivityPlanServiceImpl extends AbstractServiceImpl implements ActivityPlanService { + + @Inject + public ActivityPlanServiceImpl(Provider em) { super(em, ActivityPlan.class, QActivityPlan.activityPlan); - } + } } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplate.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplate.java index b91217a705..7ee63d0358 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplate.java @@ -1,11 +1,5 @@ package se.su.dsv.scipro.activityplan; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; @@ -19,8 +13,12 @@ import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.OrderColumn; - import jakarta.persistence.Table; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; @@ -29,134 +27,158 @@ import se.su.dsv.scipro.system.User; @Cacheable(true) public class ActivityPlanTemplate extends DomainObject { - // + // @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Basic - @Column(name = "is_sys_admin_template", nullable=false) - private boolean isSysAdminTemplate = false; + @Basic + @Column(name = "is_sys_admin_template", nullable = false) + private boolean isSysAdminTemplate = false; - @Basic - @Column(name = "title", nullable = false) - private String title; + @Basic + @Column(name = "title", nullable = false) + private String title; - @Basic - @Column(name = "description") - @Lob - private String description; - // + @Basic + @Column(name = "description") + @Lob + private String description; - // - @ManyToOne(optional = false) - @JoinColumn(name = "creator_user_id", referencedColumnName = "id") - private User creator; - // + // - // - @OneToMany(mappedBy="activityPlanTemplate", orphanRemoval=true, cascade=CascadeType.ALL) - @OrderColumn(name = "number_in_order") - private List activityTemplates = new ArrayList<>(); - // + // + @ManyToOne(optional = false) + @JoinColumn(name = "creator_user_id", referencedColumnName = "id") + private User creator; - // - @Override - public Long getId() { - return this.id; - } + // - public void setId(Long id) { - this.id = id; - } + // + @OneToMany(mappedBy = "activityPlanTemplate", orphanRemoval = true, cascade = CascadeType.ALL) + @OrderColumn(name = "number_in_order") + private List activityTemplates = new ArrayList<>(); - public boolean isSysAdminTemplate() { - return this.isSysAdminTemplate; - } + // - public void setSysAdminTemplate(boolean isSysAdminTemplate) { - this.isSysAdminTemplate = isSysAdminTemplate; - } + // + @Override + public Long getId() { + return this.id; + } - public String getTitle() { - return this.title; - } + public void setId(Long id) { + this.id = id; + } - public void setTitle(String title) { - this.title = title; - } + public boolean isSysAdminTemplate() { + return this.isSysAdminTemplate; + } - public String getDescription() { - return this.description; - } + public void setSysAdminTemplate(boolean isSysAdminTemplate) { + this.isSysAdminTemplate = isSysAdminTemplate; + } - public void setDescription(String description) { - this.description = description; - } + public String getTitle() { + return this.title; + } - public User getCreator() { - return this.creator; - } + public void setTitle(String title) { + this.title = title; + } - public void setCreator(User creator) { - this.creator = creator; - } + public String getDescription() { + return this.description; + } - public List getActivityTemplates(){ - return Collections.unmodifiableList(activityTemplates); - } + public void setDescription(String description) { + this.description = description; + } - public void setActivityTemplates(List activityTemplates){ - this.activityTemplates = new ArrayList<>(activityTemplates); - } - // + public User getCreator() { + return this.creator; + } - // - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof ActivityPlanTemplate)) return false; - final ActivityPlanTemplate other = (ActivityPlanTemplate) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getActivityTemplates(), other.getActivityTemplates()) - && Objects.equals(this.getCreator(), other.getCreator()) - && Objects.equals(this.getTitle(), other.getTitle()) - && Objects.equals(this.getDescription(), other.getDescription()) - && this.isSysAdminTemplate() == other.isSysAdminTemplate(); - } + public void setCreator(User creator) { + this.creator = creator; + } - protected boolean canEqual(final Object other) { - return other instanceof ActivityPlanTemplate; - } + public List getActivityTemplates() { + return Collections.unmodifiableList(activityTemplates); + } - @Override - public int hashCode() { - return Objects.hash(this.getId(), this.getActivityTemplates(), this.getCreator(), this.getTitle(), this.getDescription(), this.isSysAdminTemplate()); - } + public void setActivityTemplates(List activityTemplates) { + this.activityTemplates = new ArrayList<>(activityTemplates); + } - @Override - public String toString() { - return "ActivityPlanTemplate(id=" + this.getId() + ", creator=" + this.getCreator() + - ", title=" + this.getTitle() + ", description=" + this.getDescription() + - ", isSysAdminTemplate=" + this.isSysAdminTemplate() + ")"; - } - // + // - // - public void addActivity(ActivityTemplate activity){ - activity.setActivityPlanTemplate(this); - activity.setNumberInOrder(activityTemplates.size()); - activityTemplates.add(activity); - } + // + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof ActivityPlanTemplate)) return false; + final ActivityPlanTemplate other = (ActivityPlanTemplate) o; + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getActivityTemplates(), other.getActivityTemplates()) && + Objects.equals(this.getCreator(), other.getCreator()) && + Objects.equals(this.getTitle(), other.getTitle()) && + Objects.equals(this.getDescription(), other.getDescription()) && + this.isSysAdminTemplate() == other.isSysAdminTemplate() + ); + } - public void clearActivities(){ - activityTemplates.clear(); - } + protected boolean canEqual(final Object other) { + return other instanceof ActivityPlanTemplate; + } - public void addActivities(final Collection activities){ - activityTemplates.addAll(activities); - } - // + @Override + public int hashCode() { + return Objects.hash( + this.getId(), + this.getActivityTemplates(), + this.getCreator(), + this.getTitle(), + this.getDescription(), + this.isSysAdminTemplate() + ); + } + + @Override + public String toString() { + return ( + "ActivityPlanTemplate(id=" + + this.getId() + + ", creator=" + + this.getCreator() + + ", title=" + + this.getTitle() + + ", description=" + + this.getDescription() + + ", isSysAdminTemplate=" + + this.isSysAdminTemplate() + + ")" + ); + } + + // + + // + public void addActivity(ActivityTemplate activity) { + activity.setActivityPlanTemplate(this); + activity.setNumberInOrder(activityTemplates.size()); + activityTemplates.add(activity); + } + + public void clearActivities() { + activityTemplates.clear(); + } + + public void addActivities(final Collection activities) { + activityTemplates.addAll(activities); + } + // } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateService.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateService.java index c82572a6b4..ce8f975f87 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateService.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateService.java @@ -1,18 +1,20 @@ package se.su.dsv.scipro.activityplan; -import se.su.dsv.scipro.system.FilteredService; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.system.FilteredService; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.User; -public interface ActivityPlanTemplateService extends GenericService, FilteredService { - +public interface ActivityPlanTemplateService + extends + GenericService, + FilteredService { List findAll(Filter filter); class Filter implements Serializable { + private String filterString; private User creator; @@ -37,9 +39,11 @@ public interface ActivityPlanTemplateService extends GenericService + implements ActivityPlanTemplateService { -public class ActivityPlanTemplateServiceImpl extends AbstractServiceImpl implements ActivityPlanTemplateService { @Inject public ActivityPlanTemplateServiceImpl(Provider em) { super(em, ActivityPlanTemplate.class, QActivityPlanTemplate.activityPlanTemplate); @@ -31,23 +32,26 @@ public class ActivityPlanTemplateServiceImpl extends AbstractServiceImpl { -} - +public interface ActivityService extends GenericService {} diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityServiceImpl.java index 16ff0d5a94..3225fa5c61 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityServiceImpl.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.activityplan; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; public class ActivityServiceImpl extends AbstractServiceImpl implements ActivityService { @@ -12,5 +11,4 @@ public class ActivityServiceImpl extends AbstractServiceImpl imp public ActivityServiceImpl(Provider em) { super(em, Activity.class, QActivity.activity); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityTemplate.java b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityTemplate.java index 6671bea897..52a3519167 100755 --- a/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/activityplan/ActivityTemplate.java @@ -1,7 +1,5 @@ package se.su.dsv.scipro.activityplan; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -14,7 +12,7 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.checklist.ChecklistTemplate; import se.su.dsv.scipro.system.DomainObject; @@ -48,6 +46,7 @@ public class ActivityTemplate extends DomainObject { @Basic @Column(name = "number_in_order", nullable = false) private int numberInOrder = Integer.MAX_VALUE; + // // @@ -58,15 +57,16 @@ public class ActivityTemplate extends DomainObject { @ManyToOne(optional = true) @JoinColumn(name = "checklist_template_id", referencedColumnName = "id") private ChecklistTemplate checklistTemplate; + // // - public ActivityTemplate() { - } + public ActivityTemplate() {} public ActivityTemplate(int daysOffset) { this.daysOffset = daysOffset; } + // // @@ -134,6 +134,7 @@ public class ActivityTemplate extends DomainObject { public void setChecklistTemplate(ChecklistTemplate checklistTemplate) { this.checklistTemplate = checklistTemplate; } + // // @@ -142,8 +143,7 @@ public class ActivityTemplate extends DomainObject { if (o == this) return true; if (!(o instanceof ActivityTemplate)) return false; final ActivityTemplate other = (ActivityTemplate) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -153,12 +153,27 @@ public class ActivityTemplate extends DomainObject { @Override public String toString() { - return "ActivityTemplate(id=" + this.getId() + ", title=" + this.getTitle() + - ", description=" + this.getDescription() + ", activityPlanTemplate=" + - this.getActivityPlanTemplate() + ", daysOffset=" + this.getDaysOffset() + ", action=" + - this.getAction() + ", numberInOrder=" + this.getNumberInOrder() + ", checklistTemplate=" + - this.getChecklistTemplate() + ")"; + return ( + "ActivityTemplate(id=" + + this.getId() + + ", title=" + + this.getTitle() + + ", description=" + + this.getDescription() + + ", activityPlanTemplate=" + + this.getActivityPlanTemplate() + + ", daysOffset=" + + this.getDaysOffset() + + ", action=" + + this.getAction() + + ", numberInOrder=" + + this.getNumberInOrder() + + ", checklistTemplate=" + + this.getChecklistTemplate() + + ")" + ); } + // // diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/Checklist.java b/core/src/main/java/se/su/dsv/scipro/checklist/Checklist.java index d4c7044f52..5d9ad34c13 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/Checklist.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/Checklist.java @@ -18,16 +18,15 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "checklist") @@ -54,26 +53,29 @@ public class Checklist extends DomainObject { private Project project; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) - @JoinTable(name = "checklist_checklist_question", - joinColumns = @JoinColumn(name = "checklist_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "checklist_question_id", referencedColumnName = "id")) + @JoinTable( + name = "checklist_checklist_question", + joinColumns = @JoinColumn(name = "checklist_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "checklist_question_id", referencedColumnName = "id") + ) private List questions = new ArrayList<>(); @ManyToMany - @JoinTable(name = "checklist_checklist_category", - joinColumns = @JoinColumn(name = "checklist_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "checklist_category_id", referencedColumnName = "id")) + @JoinTable( + name = "checklist_checklist_category", + joinColumns = @JoinColumn(name = "checklist_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "checklist_category_id", referencedColumnName = "id") + ) private List categories = new ArrayList<>(); @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "checklist_user_last_open_date", joinColumns = @JoinColumn(name = "checklist_id")) @Column(name = "last_open_date") - @SuppressWarnings("JpaDataSourceORMInspection") // false warning from IntelliJ for the @MapKeyJoinColumn + @SuppressWarnings("JpaDataSourceORMInspection") // false warning from IntelliJ for the @MapKeyJoinColumn @MapKeyJoinColumn(name = "user_id") private Map userLastOpenDate = new HashMap<>(); - protected Checklist() { - } + protected Checklist() {} public int getNumberOfQuestions() { return questions.size(); @@ -148,7 +150,23 @@ public class Checklist extends DomainObject { @Override public String toString() { - return "Checklist(id=" + this.getId() + ", name=" + this.getName() + ", description=" + this.getDescription() + ", project=" + this.getProject() + ", questions=" + this.getQuestions() + ", categories=" + this.getCategories() + ", userLastOpenDate=" + this.getUserLastOpenDate() + ")"; + return ( + "Checklist(id=" + + this.getId() + + ", name=" + + this.getName() + + ", description=" + + this.getDescription() + + ", project=" + + this.getProject() + + ", questions=" + + this.getQuestions() + + ", categories=" + + this.getCategories() + + ", userLastOpenDate=" + + this.getUserLastOpenDate() + + ")" + ); } @Override @@ -156,8 +174,7 @@ public class Checklist extends DomainObject { if (o == this) return true; if (!(o instanceof Checklist)) return false; final Checklist other = (Checklist) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -170,6 +187,7 @@ public class Checklist extends DomainObject { } private static class Builder implements IName, IProject, IBuild { + private final Checklist instance = new Checklist(); @Override @@ -204,12 +222,9 @@ public class Checklist extends DomainObject { IBuild project(Project project); } - public interface IBuild { - IBuild description(String description); Checklist build(); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswer.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswer.java index 704f907f40..f369e5611d 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswer.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswer.java @@ -1,7 +1,5 @@ package se.su.dsv.scipro.checklist; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -14,13 +12,14 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; @Entity @Table(name = "checklist_answer") public class ChecklistAnswer extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -49,8 +48,7 @@ public class ChecklistAnswer extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected ChecklistAnswer() { - } + protected ChecklistAnswer() {} public ChecklistAnswer(User user) { this(user, null); @@ -105,8 +103,7 @@ public class ChecklistAnswer extends DomainObject { if (o == this) return true; if (!(o instanceof ChecklistAnswer)) return false; final ChecklistAnswer other = (ChecklistAnswer) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -116,8 +113,17 @@ public class ChecklistAnswer extends DomainObject { @Override public String toString() { - return "ChecklistAnswer(id=" + this.getId() + ", answer=" + this.getAnswer() + ", user=" + this.getUser() + - ", comment=" + this.getComment() + ")"; + return ( + "ChecklistAnswer(id=" + + this.getId() + + ", answer=" + + this.getAnswer() + + ", user=" + + this.getUser() + + ", comment=" + + this.getComment() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -126,4 +132,4 @@ public class ChecklistAnswer extends DomainObject { protected boolean canEqual(final Object other) { return other instanceof ChecklistAnswer; } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerEnum.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerEnum.java index e806794440..928c591135 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerEnum.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerEnum.java @@ -1,9 +1,9 @@ package se.su.dsv.scipro.checklist; public enum ChecklistAnswerEnum { - RED, - GREEN, - YELLOW, - NOT_APPLICABLE, - NO_ANSWER + RED, + GREEN, + YELLOW, + NOT_APPLICABLE, + NO_ANSWER, } diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerService.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerService.java index 62f9be7db2..5e328d8d5f 100644 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerService.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerService.java @@ -2,6 +2,4 @@ package se.su.dsv.scipro.checklist; import se.su.dsv.scipro.system.GenericService; -public interface ChecklistAnswerService extends GenericService { - -} +public interface ChecklistAnswerService extends GenericService {} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerServiceImpl.java index 20a612c25f..7f750c229d 100644 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistAnswerServiceImpl.java @@ -1,12 +1,13 @@ package se.su.dsv.scipro.checklist; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; -public class ChecklistAnswerServiceImpl extends AbstractServiceImpl implements ChecklistAnswerService { +public class ChecklistAnswerServiceImpl + extends AbstractServiceImpl + implements ChecklistAnswerService { @Inject public ChecklistAnswerServiceImpl(Provider em) { diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategory.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategory.java index c3589be745..a17037190d 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategory.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategory.java @@ -1,7 +1,5 @@ package se.su.dsv.scipro.checklist; -import java.util.Objects; - import jakarta.persistence.Cacheable; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -9,64 +7,63 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; @Entity -@Table(name="checklist_category") +@Table(name = "checklist_category") @Cacheable(true) public class ChecklistCategory extends DomainObject { + @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(name = "category_name", unique = true) - private String categoryName; + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - protected ChecklistCategory() { - } - - public ChecklistCategory(final String name){ - categoryName = name; - } + @Column(name = "category_name", unique = true) + private String categoryName; - @Override - public Long getId() { - return this.id; - } + protected ChecklistCategory() {} - public String getCategoryName() { - return this.categoryName; - } + public ChecklistCategory(final String name) { + categoryName = name; + } - public void setId(Long id) { - this.id = id; - } + @Override + public Long getId() { + return this.id; + } - public void setCategoryName(String categoryName) { - this.categoryName = categoryName; - } + public String getCategoryName() { + return this.categoryName; + } - @Override - public String toString() { - return "ChecklistCategory(id=" + this.getId() + ", categoryName=" + this.getCategoryName() + ")"; - } + public void setId(Long id) { + this.id = id; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof ChecklistCategory)) return false; - final ChecklistCategory other = (ChecklistCategory) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); - } + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } - protected boolean canEqual(final Object other) { - return other instanceof ChecklistCategory; - } + @Override + public String toString() { + return ("ChecklistCategory(id=" + this.getId() + ", categoryName=" + this.getCategoryName() + ")"); + } - @Override - public int hashCode() { - return Objects.hashCode(this.getId()); - } + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof ChecklistCategory)) return false; + final ChecklistCategory other = (ChecklistCategory) o; + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); + } + + protected boolean canEqual(final Object other) { + return other instanceof ChecklistCategory; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.getId()); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepo.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepo.java index 64b595d29e..80ff184bf6 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepo.java @@ -4,8 +4,6 @@ import jakarta.transaction.Transactional; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; - @Transactional -public interface ChecklistCategoryRepo extends JpaRepository, QueryDslPredicateExecutor { - -} +public interface ChecklistCategoryRepo + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepoImpl.java index 27caa5ac53..fad2584ec7 100644 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistCategoryRepoImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.checklist; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class ChecklistCategoryRepoImpl extends GenericRepo implements ChecklistCategoryRepo { + @Inject public ChecklistCategoryRepoImpl(Provider em) { super(em, ChecklistCategory.class, QChecklistCategory.checklistCategory); diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestion.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestion.java index 3678024780..da580c7d70 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestion.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestion.java @@ -1,9 +1,5 @@ package se.su.dsv.scipro.checklist; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; @@ -17,7 +13,9 @@ import jakarta.persistence.JoinTable; import jakarta.persistence.Lob; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; @@ -25,6 +23,7 @@ import se.su.dsv.scipro.system.User; @Table(name = "checklist_question") @Cacheable(true) public class ChecklistQuestion extends DomainObject { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -39,13 +38,13 @@ public class ChecklistQuestion extends DomainObject { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinTable( - name = "checklist_question_checklist_answer", - joinColumns = @JoinColumn(name = "checklist_question_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "checklist_answer_id", referencedColumnName = "id")) + name = "checklist_question_checklist_answer", + joinColumns = @JoinColumn(name = "checklist_question_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "checklist_answer_id", referencedColumnName = "id") + ) private List answers = new ArrayList<>(); - protected ChecklistQuestion() { - } + protected ChecklistQuestion() {} public ChecklistQuestion(String question, int questionNumber) { this.question = question; @@ -104,7 +103,17 @@ public class ChecklistQuestion extends DomainObject { @Override public String toString() { - return "ChecklistQuestion(id=" + this.getId() + ", question=" + this.getQuestion() + ", questionNumber=" + this.getQuestionNumber() + ", answers=" + this.getAnswers() + ")"; + return ( + "ChecklistQuestion(id=" + + this.getId() + + ", question=" + + this.getQuestion() + + ", questionNumber=" + + this.getQuestionNumber() + + ", answers=" + + this.getAnswers() + + ")" + ); } @Override @@ -112,8 +121,7 @@ public class ChecklistQuestion extends DomainObject { if (o == this) return true; if (!(o instanceof ChecklistQuestion)) return false; final ChecklistQuestion other = (ChecklistQuestion) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -124,4 +132,4 @@ public class ChecklistQuestion extends DomainObject { public int hashCode() { return Objects.hashCode(this.getId()); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepo.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepo.java index 3fb6407ebc..66c078c6aa 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepo.java @@ -4,7 +4,6 @@ import jakarta.transaction.Transactional; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; - @Transactional -public interface ChecklistQuestionRepo extends JpaRepository, QueryDslPredicateExecutor { -} +public interface ChecklistQuestionRepo + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepoImpl.java index 0846d001aa..9fe0fd26f3 100644 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistQuestionRepoImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.checklist; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class ChecklistQuestionRepoImpl extends GenericRepo implements ChecklistQuestionRepo { + @Inject public ChecklistQuestionRepoImpl(Provider em) { super(em, ChecklistQuestion.class, QChecklistQuestion.checklistQuestion); diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistService.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistService.java index 30cc7e1806..1a96e689ea 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistService.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistService.java @@ -5,7 +5,6 @@ import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; public interface ChecklistService extends GenericService { - Long countAnswers(Project project, ChecklistAnswerEnum answer); Long countUnanswered(Project project); diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistServiceImpl.java index 9a9a9c234e..85e55133a4 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistServiceImpl.java @@ -1,19 +1,18 @@ package se.su.dsv.scipro.checklist; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.activityplan.QActivity; -import se.su.dsv.scipro.activityplan.QActivityPlan; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.Date; +import se.su.dsv.scipro.activityplan.QActivity; +import se.su.dsv.scipro.activityplan.QActivityPlan; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; import se.su.dsv.scipro.system.User; -import java.util.Date; - public class ChecklistServiceImpl extends AbstractServiceImpl implements ChecklistService { + @Inject public ChecklistServiceImpl(Provider em) { super(em, Checklist.class, QChecklist.checklist); @@ -22,33 +21,31 @@ public class ChecklistServiceImpl extends AbstractServiceImpl i @Override public Long countAnswers(Project project, ChecklistAnswerEnum answer) { return from(QActivityPlan.activityPlan) - .select(QChecklistAnswer.checklistAnswer.count()) - .join(QActivityPlan.activityPlan.activities, QActivity.activity) - .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) - .join(QChecklistQuestion.checklistQuestion.answers, QChecklistAnswer.checklistAnswer) - .where( - QActivityPlan.activityPlan.project.eq(project), - QChecklistAnswer.checklistAnswer.answer.eq(answer)) - .fetchFirst(); + .select(QChecklistAnswer.checklistAnswer.count()) + .join(QActivityPlan.activityPlan.activities, QActivity.activity) + .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) + .join(QChecklistQuestion.checklistQuestion.answers, QChecklistAnswer.checklistAnswer) + .where(QActivityPlan.activityPlan.project.eq(project), QChecklistAnswer.checklistAnswer.answer.eq(answer)) + .fetchFirst(); } @Override public Long countUnanswered(Project project) { long questions = from(QActivityPlan.activityPlan) - .select(QChecklistQuestion.checklistQuestion.count()) - .join(QActivityPlan.activityPlan.activities, QActivity.activity) - .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) - .where(QActivityPlan.activityPlan.project.eq(project)) - .fetchFirst(); + .select(QChecklistQuestion.checklistQuestion.count()) + .join(QActivityPlan.activityPlan.activities, QActivity.activity) + .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) + .where(QActivityPlan.activityPlan.project.eq(project)) + .fetchFirst(); questions = questions * project.getProjectParticipants().size(); long answers = from(QActivityPlan.activityPlan) - .select(QChecklistAnswer.checklistAnswer.count()) - .join(QActivityPlan.activityPlan.activities, QActivity.activity) - .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) - .join(QChecklistQuestion.checklistQuestion.answers, QChecklistAnswer.checklistAnswer) - .where(QActivityPlan.activityPlan.project.eq(project)) - .fetchFirst(); + .select(QChecklistAnswer.checklistAnswer.count()) + .join(QActivityPlan.activityPlan.activities, QActivity.activity) + .join(QActivity.activity.checklist.questions, QChecklistQuestion.checklistQuestion) + .join(QChecklistQuestion.checklistQuestion.answers, QChecklistAnswer.checklistAnswer) + .where(QActivityPlan.activityPlan.project.eq(project)) + .fetchFirst(); return questions - answers; } @@ -64,4 +61,4 @@ public class ChecklistServiceImpl extends AbstractServiceImpl i checklist.getUserLastOpenDate().put(user, new Date()); return save(checklist); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplate.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplate.java index 12ad047041..3673bb5d02 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplate.java @@ -13,19 +13,19 @@ import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "checklist_template") public class ChecklistTemplate extends DomainObject { + public static final int MIN_TITLE_LENGTH = 3; public static final int DEFAULT_TEMPLATE_NUMBER = 999; @@ -46,8 +46,7 @@ public class ChecklistTemplate extends DomainObject { private int templateNumber = DEFAULT_TEMPLATE_NUMBER; @ElementCollection - @CollectionTable(name = "checklist_template_question", - joinColumns = @JoinColumn(name = "checklist_template_id")) + @CollectionTable(name = "checklist_template_question", joinColumns = @JoinColumn(name = "checklist_template_id")) @Column(name = "question") private List questions = new ArrayList<>(1); @@ -56,20 +55,22 @@ public class ChecklistTemplate extends DomainObject { private User creator; @ManyToMany - @JoinTable(name = "checklist_template_checklist_category", - joinColumns = @JoinColumn(name = "checklist_template_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "checklist_category_id", referencedColumnName = "id")) + @JoinTable( + name = "checklist_template_checklist_category", + joinColumns = @JoinColumn(name = "checklist_template_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "checklist_category_id", referencedColumnName = "id") + ) private List categories = new ArrayList<>(); @ManyToMany - @JoinTable(name = "checklist_template_project_type", - joinColumns = {@JoinColumn(name = "checklist_template_id")}, - inverseJoinColumns = {@JoinColumn(name = "project_type_id")}) + @JoinTable( + name = "checklist_template_project_type", + joinColumns = { @JoinColumn(name = "checklist_template_id") }, + inverseJoinColumns = { @JoinColumn(name = "project_type_id") } + ) private Collection projectTypes = new HashSet<>(); - public ChecklistTemplate() { - - } + public ChecklistTemplate() {} public ChecklistTemplate(String name, User creator) { this.name = name; @@ -84,7 +85,7 @@ public class ChecklistTemplate extends DomainObject { questions.add(question); } - public void clearQuestions(){ + public void clearQuestions() { questions.clear(); } @@ -151,7 +152,25 @@ public class ChecklistTemplate extends DomainObject { @Override public String toString() { - return "ChecklistTemplate(id=" + this.getId() + ", name=" + this.getName() + ", description=" + this.getDescription() + ", templateNumber=" + this.getTemplateNumber() + ", questions=" + this.getQuestions() + ", creator=" + this.getCreator() + ", categories=" + this.getCategories() + ", projectTypes=" + this.getProjectTypes() + ")"; + return ( + "ChecklistTemplate(id=" + + this.getId() + + ", name=" + + this.getName() + + ", description=" + + this.getDescription() + + ", templateNumber=" + + this.getTemplateNumber() + + ", questions=" + + this.getQuestions() + + ", creator=" + + this.getCreator() + + ", categories=" + + this.getCategories() + + ", projectTypes=" + + this.getProjectTypes() + + ")" + ); } @Override @@ -159,8 +178,7 @@ public class ChecklistTemplate extends DomainObject { if (o == this) return true; if (!(o instanceof ChecklistTemplate)) return false; final ChecklistTemplate other = (ChecklistTemplate) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -171,4 +189,4 @@ public class ChecklistTemplate extends DomainObject { public int hashCode() { return Objects.hashCode(this.getId()); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateService.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateService.java index 35e2d9eb0f..230939f28d 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateService.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateService.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.checklist; +import java.util.List; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.FilteredService; import se.su.dsv.scipro.system.GenericService; -import java.util.List; - -public interface ChecklistTemplateService extends GenericService, FilteredService { +public interface ChecklistTemplateService + extends GenericService, FilteredService { void upChecklistTemplate(ChecklistTemplate checklistTemplate); void downChecklistTemplate(ChecklistTemplate checklistTemplate); void safeDeleteChecklistTemplate(ChecklistTemplate checklistTemplate); diff --git a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImpl.java index 336d0e8b58..9c0618e9a6 100755 --- a/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImpl.java @@ -1,19 +1,20 @@ package se.su.dsv.scipro.checklist; -import jakarta.transaction.Transactional; -import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.List; - import static com.querydsl.core.types.dsl.Expressions.allOf; -public class ChecklistTemplateServiceImpl extends AbstractServiceImpl implements ChecklistTemplateService { +import com.querydsl.core.types.dsl.BooleanExpression; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; + +public class ChecklistTemplateServiceImpl + extends AbstractServiceImpl + implements ChecklistTemplateService { public static final String PEER = "Peer"; @@ -65,7 +66,9 @@ public class ChecklistTemplateServiceImpl extends AbstractServiceImpl findPeerRequestChecklists(final Project project) { - return findAll(allOf( + return findAll( + allOf( QChecklistTemplate.checklistTemplate.projectTypes.any().eq(project.getProjectType()), QChecklistTemplate.checklistTemplate.categories.any().categoryName.eq(PEER) - )); + ) + ); } @Override @@ -90,7 +95,9 @@ public class ChecklistTemplateServiceImpl extends AbstractServiceImpl getContributors(Integer projectId); diff --git a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImpl.java b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImpl.java index 393e5e66ed..aa41073c08 100755 --- a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImpl.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.daisyExternal.http; +import static jakarta.ws.rs.client.Entity.xml; + +import jakarta.inject.Inject; +import jakarta.inject.Named; import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.client.Client; @@ -10,16 +14,11 @@ import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.GenericType; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import se.su.dsv.scipro.io.dto.*; - -import jakarta.inject.Inject; -import jakarta.inject.Named; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.*; - -import static jakarta.ws.rs.client.Entity.xml; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import se.su.dsv.scipro.io.dto.*; public class DaisyAPIImpl implements DaisyAPI { @@ -44,207 +43,176 @@ public class DaisyAPIImpl implements DaisyAPI { @Inject public DaisyAPIImpl( - @Named("daisy.api.url") final String baseUrl, - @Named("daisy.api.username") final String user, - @Named("daisy.api.password") final String password) { + @Named("daisy.api.url") final String baseUrl, + @Named("daisy.api.username") final String user, + @Named("daisy.api.password") final String password + ) { this.baseUrl = baseUrl; - this.client = ClientBuilder.newClient() - .register(HttpAuthenticationFeature.basic(user, password)); + this.client = ClientBuilder.newClient().register(HttpAuthenticationFeature.basic(user, password)); this.objectFactory = new ObjectFactory(); } @Override public Set getContributors(Integer projectId) { return thesis() - .path(String.valueOf(projectId)) - .path(CONTRIBUTOR) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(projectId)) + .path(CONTRIBUTOR) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public Set getAuthors(Integer projectId) { return thesis() - .path(String.valueOf(projectId)) - .path(AUTHOR) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(projectId)) + .path(AUTHOR) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public Set getProjects(Integer personId) { return person() - .path(String.valueOf(personId)) - .path(THESES) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(personId)) + .path(THESES) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public Set getSubUnits(Integer unitId) { return units() - .path(String.valueOf(unitId)) - .path(SUBUNITS) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(unitId)) + .path(SUBUNITS) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } - @Override public Set getUsernames(Integer personId) { return person() - .path(String.valueOf(personId)) - .path(USERNAMES) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(personId)) + .path(USERNAMES) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public List getResearchAreas(Integer personId) { return person() - .path(String.valueOf(personId)) - .path(RESEARCH_AREAS) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(personId)) + .path(RESEARCH_AREAS) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public List getSupervisors(Integer unitId) { return units() - .path(String.valueOf(unitId)) - .path(SUPERVISORS) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(unitId)) + .path(SUPERVISORS) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public Optional findPersonById(Integer id) { Response response = person() - .path(String.valueOf(id)) - .request(MediaType.APPLICATION_XML_TYPE) - .get(Response.class); - return response.getStatus() == 200 - ? Optional.of(response.readEntity(Person.class)) - : Optional.empty(); + .path(String.valueOf(id)) + .request(MediaType.APPLICATION_XML_TYPE) + .get(Response.class); + return response.getStatus() == 200 ? Optional.of(response.readEntity(Person.class)) : Optional.empty(); } @Override public Optional findByUsername(String userName) { Response response = person() - .path(USERNAME) - .path(userName) - .request(MediaType.APPLICATION_XML_TYPE) - .get(Response.class); - return response.getStatus() == 200 - ? Optional.of(response.readEntity(Person.class)) - : Optional.empty(); + .path(USERNAME) + .path(userName) + .request(MediaType.APPLICATION_XML_TYPE) + .get(Response.class); + return response.getStatus() == 200 ? Optional.of(response.readEntity(Person.class)) : Optional.empty(); } @Override public Response addContributor(Integer projectIdentifier, ProjectParticipant contributor) { return thesis() - .path(String.valueOf(projectIdentifier)) - .path(CONTRIBUTOR) - .request(MediaType.APPLICATION_XML_TYPE) - .post(xml(objectFactory.createProjectParticipant(contributor))); + .path(String.valueOf(projectIdentifier)) + .path(CONTRIBUTOR) + .request(MediaType.APPLICATION_XML_TYPE) + .post(xml(objectFactory.createProjectParticipant(contributor))); } @Override public Response deleteThesisPerson(Integer projectId, Integer personId) { return thesis() - .path(String.valueOf(projectId)) - .path(PERSON) - .path(String.valueOf(personId)) - .request(MediaType.APPLICATION_XML_TYPE) - .delete(); + .path(String.valueOf(projectId)) + .path(PERSON) + .path(String.valueOf(personId)) + .request(MediaType.APPLICATION_XML_TYPE) + .delete(); } @Override public Response createProject(ThesisToBeCreated project) { - return thesis() - .request(MediaType.APPLICATION_XML_TYPE) - .post(xml(project)); + return thesis().request(MediaType.APPLICATION_XML_TYPE).post(xml(project)); } @Override public Response addAuthor(Integer projectId, AddThesisAuthor addThesisAuthor) { return thesis() - .path(String.valueOf(projectId)) - .path("author") - .request(MediaType.APPLICATION_XML_TYPE) - .post(xml(addThesisAuthor)); + .path(String.valueOf(projectId)) + .path("author") + .request(MediaType.APPLICATION_XML_TYPE) + .post(xml(addThesisAuthor)); } @Override public Response deleteProject(Integer projectId) { - return thesis() - .path(String.valueOf(projectId)) - .request(MediaType.APPLICATION_XML_TYPE) - .delete(); + return thesis().path(String.valueOf(projectId)).request(MediaType.APPLICATION_XML_TYPE).delete(); } @Override public Response getStudent(Integer id) { - return student() - .path(String.valueOf(id)) - .request(MediaType.APPLICATION_XML_TYPE) - .get(); + return student().path(String.valueOf(id)).request(MediaType.APPLICATION_XML_TYPE).get(); } @Override public Program getProgram(Integer id) { - return program() - .path(String.valueOf(id)) - .request(MediaType.APPLICATION_XML_TYPE) - .get(Program.class); + return program().path(String.valueOf(id)).request(MediaType.APPLICATION_XML_TYPE).get(Program.class); } @Override public Optional getThesis(Integer projectIdentifier) { Response response = thesis() - .path(String.valueOf(projectIdentifier)) - .request(MediaType.APPLICATION_XML_TYPE) - .get(Response.class); - return response.getStatus() == 200 - ? Optional.of(response.readEntity(Thesis.class)) - : Optional.empty(); + .path(String.valueOf(projectIdentifier)) + .request(MediaType.APPLICATION_XML_TYPE) + .get(Response.class); + return response.getStatus() == 200 ? Optional.of(response.readEntity(Thesis.class)) : Optional.empty(); } @Override public void updateThesis(final Integer id, ThesisToBeUpdated thesis) { - thesis() - .path(String.valueOf(id)) - .request() - .put(xml(thesis)); + thesis().path(String.valueOf(id)).request().put(xml(thesis)); } @Override public Optional getGradeForStudentInCourse(Long authorId, Integer courseId) { Response response = course() - .path(String.valueOf(courseId)) - .path(STUDENT) - .path(String.valueOf(authorId)) - .request(MediaType.APPLICATION_XML_TYPE) - .get(); - return response.getStatus() == 200 - ? Optional.ofNullable(response.readEntity(String.class)) - : Optional.empty(); + .path(String.valueOf(courseId)) + .path(STUDENT) + .path(String.valueOf(authorId)) + .request(MediaType.APPLICATION_XML_TYPE) + .get(); + return response.getStatus() == 200 ? Optional.ofNullable(response.readEntity(String.class)) : Optional.empty(); } @Override public List findByPersonnummer(final String personnummer) { return person() - .queryParam("personnummer", personnummer) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .queryParam("personnummer", personnummer) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override @@ -252,12 +220,12 @@ public class DaisyAPIImpl implements DaisyAPI { final Response response; try { response = person() - .path(String.valueOf(personId)) - .path("photo") - .queryParam("show", alwaysShow) - .request() - .header("X-User-Id", requesterId) - .get(); + .path(String.valueOf(personId)) + .path("photo") + .queryParam("show", alwaysShow) + .request() + .header("X-User-Id", requesterId) + .get(); } catch (ProcessingException e) { return new PhotoResult.Missing(); } @@ -279,10 +247,10 @@ public class DaisyAPIImpl implements DaisyAPI { @Override public Optional getPublication(final long projectId) { final Response response = thesis() - .path(Long.toString(projectId)) - .path("publication") - .request(MediaType.APPLICATION_XML_TYPE) - .get(); + .path(Long.toString(projectId)) + .path("publication") + .request(MediaType.APPLICATION_XML_TYPE) + .get(); switch (response.getStatus()) { case 200: return Optional.of(response.readEntity(ThesisPublication.class)); @@ -297,10 +265,10 @@ public class DaisyAPIImpl implements DaisyAPI { @Override public boolean sendPublication(final long projectId, final ThesisPublication publication) { final Response response = thesis() - .path(Long.toString(projectId)) - .path("publication") - .request(MediaType.APPLICATION_XML_TYPE) - .put(Entity.xml(publication)); + .path(Long.toString(projectId)) + .path("publication") + .request(MediaType.APPLICATION_XML_TYPE) + .put(Entity.xml(publication)); return response.getStatus() == 200; } @@ -308,44 +276,42 @@ public class DaisyAPIImpl implements DaisyAPI { public boolean sendPublicationFile(final long projectId, final String filename, final InputStream data) { final String asciiOnlyFilename = asciify(filename); final Response response = thesis() - .path(Long.toString(projectId)) - .path("publication") - .path("file") - .request(MediaType.APPLICATION_XML_TYPE) - .header("X-Filename", asciiOnlyFilename) - .put(Entity.entity(data, "application/pdf")); + .path(Long.toString(projectId)) + .path("publication") + .path("file") + .request(MediaType.APPLICATION_XML_TYPE) + .header("X-Filename", asciiOnlyFilename) + .put(Entity.entity(data, "application/pdf")); return response.getStatus() == 200; } private static String asciify(String str) { return str - .replace('Å', 'A') - .replace('Ä', 'A') - .replace('Ö', 'O') - .replace('å', 'a') - .replace('ä', 'a') - .replace('ö', 'o') - .replaceAll("\\P{ASCII}", ""); // Removes all remaining non-ASCII characters + .replace('Å', 'A') + .replace('Ä', 'A') + .replace('Ö', 'O') + .replace('å', 'a') + .replace('ä', 'a') + .replace('ö', 'o') + .replaceAll("\\P{ASCII}", ""); // Removes all remaining non-ASCII characters } @Override public List getPrograms(final Integer responsibleDepartmentId) { return program() - .queryParam("responsibleDepartment", responsibleDepartmentId) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .queryParam("responsibleDepartment", responsibleDepartmentId) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public List getProgramAdmissions(final Program program, final Semester admissionSemester) { return program() - .path(String.valueOf(program.getId())) - .path("admissions") - .queryParam("admissionSemester", admissionSemester.getId()) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(String.valueOf(program.getId())) + .path("admissions") + .queryParam("admissionSemester", admissionSemester.getId()) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override @@ -353,23 +319,21 @@ public class DaisyAPIImpl implements DaisyAPI { // have to pre-format the date parameter due to weird api handling of dates final String sinceParameter = new SimpleDateFormat("yyyy-MM-dd").format(since); return thesis() - .path("rejections") - .queryParam("since", sinceParameter) - // must be XML due to api date-formatting in json - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path("rejections") + .queryParam("since", sinceParameter) + // must be XML due to api date-formatting in json + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public List getProgramAdmissionsForStudent(final int studentId) { try { return student() - .path(Integer.toString(studentId)) - .path("programAdmissions") - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(Integer.toString(studentId)) + .path("programAdmissions") + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } catch (NotFoundException ignored) { return Collections.emptyList(); } @@ -379,11 +343,10 @@ public class DaisyAPIImpl implements DaisyAPI { public List getCourseRegistrationsForStudent(final int studentId) { try { return student() - .path(Integer.toString(studentId)) - .path("courseRegistrations") - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() { - }); + .path(Integer.toString(studentId)) + .path("courseRegistrations") + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } catch (NotFoundException ignored) { return Collections.emptyList(); } @@ -392,15 +355,16 @@ public class DaisyAPIImpl implements DaisyAPI { @Override public List listEmployees(int departmentId) { return target() - .path("employee") - .queryParam("department", departmentId) - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() {}); + .path("employee") + .queryParam("department", departmentId) + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } @Override public OrganisationalUnit orgunit(final int unitId) { - return () -> target() + return () -> + target() .path("orgunit") .path(Integer.toString(unitId)) .path("researchAreas") @@ -411,22 +375,22 @@ public class DaisyAPIImpl implements DaisyAPI { @Override public PublishingConsent getPublishingConsent(int projectId, int personId) { return thesis() - .path(Integer.toString(projectId)) - .path("author") - .path(Integer.toString(personId)) - .path("publishingConsent") - .request(MediaType.APPLICATION_XML_TYPE) - .get(PublishingConsent.class); + .path(Integer.toString(projectId)) + .path("author") + .path(Integer.toString(personId)) + .path("publishingConsent") + .request(MediaType.APPLICATION_XML_TYPE) + .get(PublishingConsent.class); } @Override public boolean setPublishingConsent(int projectId, int personId, PublishingConsentLevel publishingConsentLevel) { final Invocation.Builder request = thesis() - .path(Integer.toString(projectId)) - .path("author") - .path(Integer.toString(personId)) - .path("publishingConsent") - .request(MediaType.APPLICATION_XML_TYPE); + .path(Integer.toString(projectId)) + .path("author") + .path(Integer.toString(personId)) + .path("publishingConsent") + .request(MediaType.APPLICATION_XML_TYPE); // For some reason XML does not work try (Response response = request.post(Entity.json(publishingConsentLevel))) { @@ -437,44 +401,37 @@ public class DaisyAPIImpl implements DaisyAPI { @Override public List getNationalResearchSubjects(int organisationId) { return units() - .path(Integer.toString(organisationId)) - .path("nationalSubjectCategories") - .request(MediaType.APPLICATION_XML_TYPE) - .get(new GenericType<>() {}); + .path(Integer.toString(organisationId)) + .path("nationalSubjectCategories") + .request(MediaType.APPLICATION_XML_TYPE) + .get(new GenericType<>() {}); } private WebTarget program() { - return target() - .path(PROGRAM); + return target().path(PROGRAM); } private WebTarget student() { - return target() - .path(STUDENT); + return target().path(STUDENT); } private WebTarget thesis() { - return target() - .path(THESIS); + return target().path(THESIS); } private WebTarget units() { - return target() - .path(ORGUNIT); + return target().path(ORGUNIT); } private WebTarget person() { - return target() - .path(PERSON); + return target().path(PERSON); } private WebTarget course() { - return target() - .path(COURSE); + return target().path(COURSE); } private WebTarget target() { - return client - .target(baseUrl); + return client.target(baseUrl); } } diff --git a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/OrganisationalUnit.java b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/OrganisationalUnit.java index d1d52b8bd5..65f6699a53 100644 --- a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/OrganisationalUnit.java +++ b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/OrganisationalUnit.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.daisyExternal.http; -import se.su.dsv.scipro.io.dto.ResearchArea; - import java.util.List; +import se.su.dsv.scipro.io.dto.ResearchArea; public interface OrganisationalUnit { List getResearchAreas(); diff --git a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/PhotoResult.java b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/PhotoResult.java index 1321836ebd..063c5cf9c1 100644 --- a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/PhotoResult.java +++ b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/PhotoResult.java @@ -6,23 +6,38 @@ import java.util.function.Supplier; public abstract class PhotoResult { - public abstract X fold(final Supplier missing, final Supplier forbidden, final Function found); + public abstract X fold( + final Supplier missing, + final Supplier forbidden, + final Function found + ); public static class Missing extends PhotoResult { + @Override - public X fold(final Supplier missing, final Supplier forbidden, final Function found) { + public X fold( + final Supplier missing, + final Supplier forbidden, + final Function found + ) { return missing.get(); } } static class Forbidden extends PhotoResult { + @Override - public X fold(final Supplier missing, final Supplier forbidden, final Function found) { + public X fold( + final Supplier missing, + final Supplier forbidden, + final Function found + ) { return forbidden.get(); } } static class Found extends PhotoResult { + private final InputStream photo; Found(final InputStream photo) { @@ -30,9 +45,12 @@ public abstract class PhotoResult { } @Override - public X fold(final Supplier missing, final Supplier forbidden, final Function found) { + public X fold( + final Supplier missing, + final Supplier forbidden, + final Function found + ) { return found.apply(photo); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/Semester.java b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/Semester.java index 7f7f679373..9930163d84 100644 --- a/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/Semester.java +++ b/core/src/main/java/se/su/dsv/scipro/daisyExternal/http/Semester.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.daisyExternal.http; public abstract class Semester { + public static Semester spring(int year) { return new Spring(year); } @@ -17,6 +18,7 @@ public abstract class Semester { public abstract String toString(); private static final class Spring extends Semester { + private final int year; public Spring(final int year) { @@ -35,6 +37,7 @@ public abstract class Semester { } private static final class Autumn extends Semester { + private final int year; public Autumn(final int year) { diff --git a/core/src/main/java/se/su/dsv/scipro/data/dataobjects/Member.java b/core/src/main/java/se/su/dsv/scipro/data/dataobjects/Member.java index 0d338a272f..602b7b4bc2 100755 --- a/core/src/main/java/se/su/dsv/scipro/data/dataobjects/Member.java +++ b/core/src/main/java/se/su/dsv/scipro/data/dataobjects/Member.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.data.dataobjects; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.system.User; public class Member implements Serializable { + private final User user; private final Type type; - public enum Type { + public enum Type { AUTHOR { @Override public String toString() { @@ -75,7 +75,7 @@ public class Member implements Serializable { public String toString() { return "Individual milestone"; } - } + }, } public Member(User user, Type type) { @@ -96,9 +96,11 @@ public class Member implements Serializable { if (o == this) return true; if (!(o instanceof Member)) return false; final Member other = (Member) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getType(), other.getType()); + return ( + other.canEqual(this) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getType(), other.getType()) + ); } protected boolean canEqual(final Object other) { @@ -112,6 +114,6 @@ public class Member implements Serializable { @Override public String toString() { - return "Member(user=" + this.getUser() + ", type=" + this.getType() + ")"; + return ("Member(user=" + this.getUser() + ", type=" + this.getType() + ")"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/data/enums/DateStyle.java b/core/src/main/java/se/su/dsv/scipro/data/enums/DateStyle.java index 6b83f6b620..c5ef56d301 100644 --- a/core/src/main/java/se/su/dsv/scipro/data/enums/DateStyle.java +++ b/core/src/main/java/se/su/dsv/scipro/data/enums/DateStyle.java @@ -1,8 +1,9 @@ package se.su.dsv.scipro.data.enums; public enum DateStyle { - - DATETIME("yyyy-MM-dd HH:mm"), DATE("yyyy-MM-dd"), TIME("HH:mm"); + DATETIME("yyyy-MM-dd HH:mm"), + DATE("yyyy-MM-dd"), + TIME("HH:mm"); private final String format; diff --git a/core/src/main/java/se/su/dsv/scipro/data/enums/MailChoice.java b/core/src/main/java/se/su/dsv/scipro/data/enums/MailChoice.java index 73cba86ee2..e3cbe3f8bd 100644 --- a/core/src/main/java/se/su/dsv/scipro/data/enums/MailChoice.java +++ b/core/src/main/java/se/su/dsv/scipro/data/enums/MailChoice.java @@ -1,27 +1,25 @@ package se.su.dsv.scipro.data.enums; public enum MailChoice { - THESIS_SUPPORT("Thesis support"), - AUTHORS_ACTIVE_PROJECT("Authors with active projects"), - ACTIVE_SUPERVISORS("Head supervisors with active projects"), - ACTIVE_CO_SUPERVISORS("Co-supervisors with active projects"), - ACTIVE_REVIEWERS("Reviewers of active projects"), - ALL_FOLLOWERS("All supervisors and reviewers of active projects"), - AUTHORS_SUBMITTED_IDEA("Authors with submitted ideas"), - AUTHORS_MATCHED_IDEA("Authors with matched ideas"), - SUPERVISORS_MATCHED_IDEA("Supervisors with matched ideas"), - SUPERVISORS_SUBMITTED_IDEA("Supervisors with submitted ideas"); - - private String asString; + THESIS_SUPPORT("Thesis support"), + AUTHORS_ACTIVE_PROJECT("Authors with active projects"), + ACTIVE_SUPERVISORS("Head supervisors with active projects"), + ACTIVE_CO_SUPERVISORS("Co-supervisors with active projects"), + ACTIVE_REVIEWERS("Reviewers of active projects"), + ALL_FOLLOWERS("All supervisors and reviewers of active projects"), + AUTHORS_SUBMITTED_IDEA("Authors with submitted ideas"), + AUTHORS_MATCHED_IDEA("Authors with matched ideas"), + SUPERVISORS_MATCHED_IDEA("Supervisors with matched ideas"), + SUPERVISORS_SUBMITTED_IDEA("Supervisors with submitted ideas"); + + private String asString; MailChoice(String asString) { this.asString = asString; } - @Override - public String toString() { - return asString; - } - - + @Override + public String toString() { + return asString; + } } diff --git a/core/src/main/java/se/su/dsv/scipro/data/facade/MailFacade.java b/core/src/main/java/se/su/dsv/scipro/data/facade/MailFacade.java index e258cf450e..54a2d04783 100755 --- a/core/src/main/java/se/su/dsv/scipro/data/facade/MailFacade.java +++ b/core/src/main/java/se/su/dsv/scipro/data/facade/MailFacade.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.data.facade; +import jakarta.inject.Inject; +import java.io.Serializable; +import java.util.*; import se.su.dsv.scipro.data.enums.MailChoice; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.mail.EmailRecipient; @@ -15,16 +18,14 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.io.Serializable; -import java.util.*; - public class MailFacade implements Serializable { @Inject private ProjectService projectService; + @Inject private IdeaService ideaService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; @@ -38,7 +39,12 @@ public class MailFacade implements Serializable { return supervisorsFromProjects(filter); } - private Set addProjectCoSupervisors(ProjectStatus ps, Set pc, Date startDate, Date endDate) { + private Set addProjectCoSupervisors( + ProjectStatus ps, + Set pc, + Date startDate, + Date endDate + ) { final ProjectService.Filter filter = setProjectParams(ps, pc, startDate, endDate); return coSupervisorsFromProjects(filter); } @@ -48,7 +54,12 @@ public class MailFacade implements Serializable { return reviewersFromProjects(filter); } - private ProjectService.Filter setProjectParams(ProjectStatus status, Set pc, Date startDate, Date endDate) { + private ProjectService.Filter setProjectParams( + ProjectStatus status, + Set pc, + Date startDate, + Date endDate + ) { final ProjectService.Filter projectParams = new ProjectService.Filter(); if (status != null) { projectParams.setStatuses(new HashSet<>(Collections.singletonList(status))); @@ -91,7 +102,7 @@ public class MailFacade implements Serializable { List listOfProjects = projectService.findAll(filter); Set recipients = new HashSet<>(); for (Project p : listOfProjects) { - for (User user : p.getCoSupervisors()){ + for (User user : p.getCoSupervisors()) { recipients.add(new UserRecipient(user)); } } @@ -103,7 +114,7 @@ public class MailFacade implements Serializable { List listOProjects = projectService.findAll(filter); Set recipients = new HashSet<>(); for (Project p : listOProjects) { - for (User user : p.getReviewers()){ + for (User user : p.getReviewers()) { recipients.add(new UserRecipient(user)); } } @@ -112,11 +123,12 @@ public class MailFacade implements Serializable { } private Set addThesisSupport() { - String thesisSupportMail = generalSystemSettingsService.getGeneralSystemSettingsInstance().getThesisSupportMail(); + String thesisSupportMail = generalSystemSettingsService + .getGeneralSystemSettingsInstance() + .getThesisSupportMail(); if (thesisSupportMail != null) { return Collections.singleton(new EmailRecipient(thesisSupportMail)); - } - else { + } else { return Collections.emptySet(); } } @@ -140,23 +152,53 @@ public class MailFacade implements Serializable { allFollowers.addAll(addProjectCoSupervisors(ProjectStatus.ACTIVE, pc, startDate, endDate)); return allFollowers; case AUTHORS_MATCHED_IDEA: - IdeaService.Filter matchedFilter = setIdeaParams(Arrays.asList(Idea.Status.COMPLETED, Idea.Status.MATCHED), pc, startDate, endDate, null); + IdeaService.Filter matchedFilter = setIdeaParams( + Arrays.asList(Idea.Status.COMPLETED, Idea.Status.MATCHED), + pc, + startDate, + endDate, + null + ); return authorsFromIdeas(matchedFilter); case AUTHORS_SUBMITTED_IDEA: - IdeaService.Filter submittedFilter = setIdeaParams(null, pc, startDate, endDate, Collections.singletonList(Type.STUDENT)); + IdeaService.Filter submittedFilter = setIdeaParams( + null, + pc, + startDate, + endDate, + Collections.singletonList(Type.STUDENT) + ); return authorsFromIdeas(submittedFilter); case SUPERVISORS_MATCHED_IDEA: - IdeaService.Filter supervisorMatchedFilter = setIdeaParams(Arrays.asList(Idea.Status.COMPLETED, Idea.Status.MATCHED), pc, startDate, endDate, null); + IdeaService.Filter supervisorMatchedFilter = setIdeaParams( + Arrays.asList(Idea.Status.COMPLETED, Idea.Status.MATCHED), + pc, + startDate, + endDate, + null + ); return supervisorsFromIdeas(supervisorMatchedFilter); case SUPERVISORS_SUBMITTED_IDEA: - IdeaService.Filter supervisorSubmittedFilter = setIdeaParams(null, pc, startDate, endDate, Collections.singletonList(Type.SUPERVISOR)); + IdeaService.Filter supervisorSubmittedFilter = setIdeaParams( + null, + pc, + startDate, + endDate, + Collections.singletonList(Type.SUPERVISOR) + ); return supervisorsFromIdeas(supervisorSubmittedFilter); default: return new HashSet<>(); } } - private IdeaService.Filter setIdeaParams(Collection statuses, Set pc, Date startDate, Date endDate, Collection types) { + private IdeaService.Filter setIdeaParams( + Collection statuses, + Set pc, + Date startDate, + Date endDate, + Collection types + ) { final IdeaService.Filter ideaParams = new IdeaService.Filter(); if (statuses != null && !statuses.isEmpty()) { ideaParams.setStatuses(statuses); diff --git a/core/src/main/java/se/su/dsv/scipro/date/DateService.java b/core/src/main/java/se/su/dsv/scipro/date/DateService.java index d6198fae3b..727e94b600 100644 --- a/core/src/main/java/se/su/dsv/scipro/date/DateService.java +++ b/core/src/main/java/se/su/dsv/scipro/date/DateService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.date; +import java.util.Date; import se.su.dsv.scipro.data.enums.DateStyle; -import java.util.Date; - -public interface DateService { +public interface DateService { String format(Date date); String format(Date date, DateStyle style); String getFormat(DateStyle style); diff --git a/core/src/main/java/se/su/dsv/scipro/date/DateServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/date/DateServiceImpl.java index 835aa5a07b..353c247e5a 100644 --- a/core/src/main/java/se/su/dsv/scipro/date/DateServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/date/DateServiceImpl.java @@ -1,15 +1,12 @@ package se.su.dsv.scipro.date; - -import se.su.dsv.scipro.data.enums.DateStyle; - import java.text.SimpleDateFormat; import java.util.Date; +import se.su.dsv.scipro.data.enums.DateStyle; public class DateServiceImpl implements DateService { - - private String findStyle(DateStyle style){ + private String findStyle(DateStyle style) { return style.getFormat(); } diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileDescription.java b/core/src/main/java/se/su/dsv/scipro/file/FileDescription.java index ac42cab487..d5d8c54bcb 100755 --- a/core/src/main/java/se/su/dsv/scipro/file/FileDescription.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileDescription.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.file; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.*; import java.io.IOException; import java.io.InputStream; @@ -13,6 +8,10 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Objects; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; /** * Metadata about a specific file. To get access to the underlying data you need a @@ -138,8 +137,7 @@ public class FileDescription extends DomainObject { if (o == this) return true; if (!(o instanceof FileDescription)) return false; final FileDescription other = (FileDescription) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepo.java b/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepo.java index c649d10bfe..2737c44750 100755 --- a/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepo.java @@ -4,7 +4,6 @@ import jakarta.transaction.Transactional; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; - @Transactional -public interface FileDescriptionRepo extends JpaRepository, QueryDslPredicateExecutor { -} +public interface FileDescriptionRepo + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepoImpl.java index cd6584cadb..6d46ae3126 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileDescriptionRepoImpl.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.file; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class FileDescriptionRepoImpl extends GenericRepo implements FileDescriptionRepo { + @Inject public FileDescriptionRepoImpl(Provider em) { super(em, FileDescription.class, QFileDescription.fileDescription); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileReference.java b/core/src/main/java/se/su/dsv/scipro/file/FileReference.java index 4858d090db..0c8cea730b 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/FileReference.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileReference.java @@ -24,6 +24,7 @@ import java.util.Objects; @Entity @Table(name = "file_reference") public class FileReference implements Serializable { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -57,7 +58,7 @@ public class FileReference implements Serializable { return false; } final FileReference that = (FileReference) o; - return Objects.equals(id, that.id) && fileDescription.equals(that.fileDescription); + return (Objects.equals(id, that.id) && fileDescription.equals(that.fileDescription)); } @Override @@ -67,10 +68,7 @@ public class FileReference implements Serializable { @Override public String toString() { - return "FileReference{" + - "id=" + id + - ", fileDescription=" + fileDescription + - '}'; + return ("FileReference{" + "id=" + id + ", fileDescription=" + fileDescription + '}'); } public String getName() { diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileReferenceRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/file/FileReferenceRepositoryImpl.java index 25e00cf450..674e1f59e7 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/FileReferenceRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileReferenceRepositoryImpl.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.file; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.system.AbstractRepository; public class FileReferenceRepositoryImpl extends AbstractRepository implements FileReferenceRepository { @@ -30,8 +29,8 @@ public class FileReferenceRepositoryImpl extends AbstractRepository implements F @Override public long countReferencesTo(final FileDescription fileDescription) { return from(QFileReference.fileReference) - .select(QFileReference.fileReference.count()) - .where(QFileReference.fileReference.fileDescription.eq(fileDescription)) - .fetchOne(); + .select(QFileReference.fileReference.count()) + .where(QFileReference.fileReference.fileDescription.eq(fileDescription)) + .fetchOne(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileService.java b/core/src/main/java/se/su/dsv/scipro/file/FileService.java index fde4167598..7a08dd8684 100755 --- a/core/src/main/java/se/su/dsv/scipro/file/FileService.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.file; -import se.su.dsv.scipro.system.GenericService; - import java.io.InputStream; +import se.su.dsv.scipro.system.GenericService; public interface FileService extends GenericService { FileReference storeFile(FileUpload fileUpload); diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/file/FileServiceImpl.java index c6643f50ad..70346fb9c8 100755 --- a/core/src/main/java/se/su/dsv/scipro/file/FileServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileServiceImpl.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.file; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.io.InputStream; +import se.su.dsv.scipro.system.AbstractServiceImpl; public class FileServiceImpl extends AbstractServiceImpl implements FileService { @@ -16,11 +15,11 @@ public class FileServiceImpl extends AbstractServiceImpl @Inject public FileServiceImpl( - Provider em, - final FileReferenceRepository fileReferenceRepository, - final FileDescriptionRepo fileDescriptionRepository, - final FileStore fileStore) - { + Provider em, + final FileReferenceRepository fileReferenceRepository, + final FileDescriptionRepo fileDescriptionRepository, + final FileStore fileStore + ) { super(em, FileDescription.class, QFileDescription.fileDescription); this.fileReferenceRepository = fileReferenceRepository; this.fileDescriptionRepository = fileDescriptionRepository; @@ -80,5 +79,4 @@ public class FileServiceImpl extends AbstractServiceImpl fileStore.deleteData(fileDescription); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileSource.java b/core/src/main/java/se/su/dsv/scipro/file/FileSource.java index c4ec6f5185..c051a02d2e 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/FileSource.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileSource.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.file; -public enum FileSource { +public enum FileSource { FILES, FORUM, FINAL_THESIS, PEER_REVIEW, PEER_REQUEST, FINAL_SEMINAR, - ACTIVITY_PLAN + ACTIVITY_PLAN, } diff --git a/core/src/main/java/se/su/dsv/scipro/file/FileUpload.java b/core/src/main/java/se/su/dsv/scipro/file/FileUpload.java index d10e894c24..bf63b3b51e 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/FileUpload.java +++ b/core/src/main/java/se/su/dsv/scipro/file/FileUpload.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.file; -import se.su.dsv.scipro.system.User; - import java.io.InputStream; import java.util.function.Function; +import se.su.dsv.scipro.system.User; public interface FileUpload { String getFileName(); diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFile.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFile.java index ba57470626..878bc12362 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFile.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFile.java @@ -12,11 +12,10 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; +import java.util.Objects; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DomainObject; -import java.util.Objects; - @Entity @Table(name = "project_file") public class ProjectFile extends DomainObject { @@ -88,12 +87,14 @@ public class ProjectFile extends DomainObject { if (o == this) return true; if (!(o instanceof ProjectFile)) return false; final ProjectFile other = (ProjectFile) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getProject(), other.getProject()) - && Objects.equals(this.getFileSource(), other.getFileSource()) - && Objects.equals(this.getFileDescription(), other.getFileDescription()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getProject(), other.getProject()) && + Objects.equals(this.getFileSource(), other.getFileSource()) && + Objects.equals(this.getFileDescription(), other.getFileDescription()) + ); } @Override @@ -103,7 +104,17 @@ public class ProjectFile extends DomainObject { @Override public String toString() { - return "ProjectFile(id=" + this.getId() + ", project=" + this.getProject() + ", fileSource=" + this.getFileSource() + ", fileDescription=" + this.getFileDescription() + ")"; + return ( + "ProjectFile(id=" + + this.getId() + + ", project=" + + this.getProject() + + ", fileSource=" + + this.getFileSource() + + ", fileDescription=" + + this.getFileDescription() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepository.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepository.java index e33001f8c5..274b3e3e67 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepository.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.file; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -import se.su.dsv.scipro.project.Project; - import java.util.*; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -public interface ProjectFileRepository extends JpaRepository, QueryDslPredicateExecutor { +public interface ProjectFileRepository + extends JpaRepository, QueryDslPredicateExecutor { List latestUpload(Project project, int amount); Collection getProjectFiles(Project project, Pageable pageable); diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepositoryImpl.java index a480a8763a..9358749539 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileRepositoryImpl.java @@ -2,16 +2,16 @@ package se.su.dsv.scipro.file; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.jpa.impl.JPAQuery; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; public class ProjectFileRepositoryImpl extends AbstractServiceImpl implements ProjectFileRepository { + @Inject public ProjectFileRepositoryImpl(final Provider em) { super(em, ProjectFile.class, QProjectFile.projectFile); @@ -20,10 +20,10 @@ public class ProjectFileRepositoryImpl extends AbstractServiceImpl latestUpload(final Project project, final int amount) { return new JPAQuery(em()) - .from(QProjectFile.projectFile) - .where(QProjectFile.projectFile.project.eq(project)) - .limit(amount) - .fetch(); + .from(QProjectFile.projectFile) + .where(QProjectFile.projectFile.project.eq(project)) + .limit(amount) + .fetch(); } @Override @@ -38,8 +38,13 @@ public class ProjectFileRepositoryImpl extends AbstractServiceImpl findProjectFile(final FileDescription fileDescription, final Project project) { - return Optional.ofNullable(findOne(Expressions.allOf( - QProjectFile.projectFile.fileReference.fileDescription.eq(fileDescription), - QProjectFile.projectFile.project.eq(project)))); + return Optional.ofNullable( + findOne( + Expressions.allOf( + QProjectFile.projectFile.fileReference.fileDescription.eq(fileDescription), + QProjectFile.projectFile.project.eq(project) + ) + ) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileService.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileService.java index b9dc4a2fb6..4f5401641c 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileService.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileService.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.file; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; - import java.util.*; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Pageable; public interface ProjectFileService { ProjectFile store(ProjectFileUpload projectFileUpload, final FileSource fileSource); diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileServiceImpl.java index db099d6323..8d44fef071 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileServiceImpl.java @@ -1,26 +1,22 @@ package se.su.dsv.scipro.file; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import java.util.*; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Pageable; public class ProjectFileServiceImpl implements ProjectFileService { + private final FileService fileService; private final ProjectFileRepository projectFileRepository; @Inject - public ProjectFileServiceImpl( - final FileService fileService, - final ProjectFileRepository projectFileRepository) - { + public ProjectFileServiceImpl(final FileService fileService, final ProjectFileRepository projectFileRepository) { this.fileService = fileService; this.projectFileRepository = projectFileRepository; } - @Override @Transactional public ProjectFile store(final ProjectFileUpload projectFileUpload, final FileSource fileSource) { @@ -30,7 +26,11 @@ public class ProjectFileServiceImpl implements ProjectFileService { @Override @Transactional - public ProjectFile promote(final FileDescription fileDescription, final Project project, final FileSource fileSource) { + public ProjectFile promote( + final FileDescription fileDescription, + final Project project, + final FileSource fileSource + ) { Optional existing = projectFileRepository.findProjectFile(fileDescription, project); if (existing.isPresent()) { return existing.get(); diff --git a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileUpload.java b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileUpload.java index 227cc029e4..12f0b9bd58 100644 --- a/core/src/main/java/se/su/dsv/scipro/file/ProjectFileUpload.java +++ b/core/src/main/java/se/su/dsv/scipro/file/ProjectFileUpload.java @@ -1,6 +1,5 @@ package se.su.dsv.scipro.file; - import se.su.dsv.scipro.project.Project; public interface ProjectFileUpload extends FileUpload { diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractOppositionEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractOppositionEvent.java index 8e3963505c..e60a7b2bc7 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractOppositionEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractOppositionEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; class AbstractOppositionEvent { + private final FinalSeminarOpposition opposition; protected AbstractOppositionEvent(FinalSeminarOpposition opposition) { diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractParticipationEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractParticipationEvent.java index 808d67eea8..24d230dec7 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractParticipationEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractParticipationEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; class AbstractParticipationEvent { + private final FinalSeminarActiveParticipation participation; protected AbstractParticipationEvent(FinalSeminarActiveParticipation participation) { diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractRespondentEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractRespondentEvent.java index e496ded53a..74446a49d0 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractRespondentEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/AbstractRespondentEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; class AbstractRespondentEvent { + private final FinalSeminarRespondent respondent; protected AbstractRespondentEvent(FinalSeminarRespondent respondent) { diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/ActiveParticipationRegistrationErrorStatus.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/ActiveParticipationRegistrationErrorStatus.java index b67abeab8f..11f0f6a100 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/ActiveParticipationRegistrationErrorStatus.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/ActiveParticipationRegistrationErrorStatus.java @@ -3,74 +3,84 @@ package se.su.dsv.scipro.finalseminar; import java.util.function.Function; public abstract class ActiveParticipationRegistrationErrorStatus { - ActiveParticipationRegistrationErrorStatus() { - } + + ActiveParticipationRegistrationErrorStatus() {} public abstract A fold( - Function a, - Function b, - Function e, - Function f, - Function g); + Function a, + Function b, + Function e, + Function f, + Function g + ); } final class TooManyParticipants extends ActiveParticipationRegistrationErrorStatus { + @Override public A fold( - Function a, - Function b, - Function e, - Function f, - Function g) { + Function a, + Function b, + Function e, + Function f, + Function g + ) { return a.apply(this); } } final class ManualParticipants extends ActiveParticipationRegistrationErrorStatus { + @Override public A fold( - Function a, - Function b, - Function e, - Function f, - Function g) { + Function a, + Function b, + Function e, + Function f, + Function g + ) { return b.apply(this); } } final class ParticipationAlreadyParticipating extends ActiveParticipationRegistrationErrorStatus { + @Override public A fold( - Function a, - Function b, - Function e, - Function f, - Function g) { + Function a, + Function b, + Function e, + Function f, + Function g + ) { return e.apply(this); } } final class ParticipationAlreadyHappened extends ActiveParticipationRegistrationErrorStatus { + @Override public A fold( - Function a, - Function b, - Function e, - Function f, - Function g) { + Function a, + Function b, + Function e, + Function f, + Function g + ) { return f.apply(this); } } final class ParticipationFinalSeminarCancelled extends ActiveParticipationRegistrationErrorStatus { + @Override public A fold( - Function a, - Function b, - Function e, - Function f, - Function g) { + Function a, + Function b, + Function e, + Function f, + Function g + ) { return g.apply(this); } } - diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepository.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepository.java index f6774c864a..5c3de18fdc 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepository.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.finalseminar; +import java.util.List; +import java.util.Optional; import se.su.dsv.scipro.project.Author; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.List; -import java.util.Optional; - public interface AuthorRepository { Optional findByProjectAndUser(Project project, User user); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepositoryImpl.java index 1acb79b98a..db7e8ccd9c 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/AuthorRepositoryImpl.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.util.List; +import java.util.Optional; import se.su.dsv.scipro.project.Author; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectStatus; @@ -8,13 +13,8 @@ import se.su.dsv.scipro.system.AbstractRepository; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.List; -import java.util.Optional; - public class AuthorRepositoryImpl extends AbstractRepository implements AuthorRepository { + @Inject public AuthorRepositoryImpl(Provider em) { super(em); @@ -23,11 +23,7 @@ public class AuthorRepositoryImpl extends AbstractRepository implements AuthorRe @Override public Optional findByProjectAndUser(Project project, User user) { final QAuthor author = QAuthor.author; - final Author author1 = from(author) - .where( - author.project.eq(project), - author.user.eq(user)) - .fetchOne(); + final Author author1 = from(author).where(author.project.eq(project), author.user.eq(user)).fetchOne(); return Optional.ofNullable(author1); } @@ -35,9 +31,11 @@ public class AuthorRepositoryImpl extends AbstractRepository implements AuthorRe public List getSubscribersWithActiveProjectOnType(ProjectType projectType) { final QAuthor author = QAuthor.author; return from(author) - .where(author.subscribedToFinalSeminarNotifications.isTrue(), - author.project.projectType.eq(projectType), - author.project.projectStatus.eq(ProjectStatus.ACTIVE)) - .fetch(); + .where( + author.subscribedToFinalSeminarNotifications.isTrue(), + author.project.projectType.eq(projectType), + author.project.projectStatus.eq(ProjectStatus.ACTIVE) + ) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminar.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminar.java index 1679e993a0..6a9861175d 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminar.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminar.java @@ -1,15 +1,6 @@ package se.su.dsv.scipro.finalseminar; import com.querydsl.core.annotations.QueryInit; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; @@ -18,12 +9,12 @@ import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -32,11 +23,19 @@ import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "final_seminar") @Cacheable(true) public class FinalSeminar extends LazyDeletableDomainObject { + public static final String U_SINGULAR = "Final seminar"; public static final int DEFAULT_MAX_OPPONENTS = 2; @@ -100,7 +99,7 @@ public class FinalSeminar extends LazyDeletableDomainObject { @OneToOne(optional = false) @JoinColumn(name = "project_id", referencedColumnName = "id") - @QueryInit({"projectType", "headSupervisor"}) + @QueryInit({ "projectType", "headSupervisor" }) private Project project; // ---------------------------------------------------------------------------------- @@ -118,8 +117,7 @@ public class FinalSeminar extends LazyDeletableDomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public FinalSeminar() { - } + public FinalSeminar() {} public FinalSeminar(int maxOpponents, int maxParticipants) { this.maxOpponents = maxOpponents; @@ -273,9 +271,7 @@ public class FinalSeminar extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof FinalSeminar)) return false; final FinalSeminar other = (FinalSeminar) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.getId(), other.getId())); } @Override @@ -285,14 +281,35 @@ public class FinalSeminar extends LazyDeletableDomainObject { @Override public String toString() { - return "FinalSeminar(id=" + this.getId() + ", project=" + this.getProject() + ", startDate=" + - this.getStartDate() + ", room=" + this.getRoom() + ", activeParticipations=" + - this.getActiveParticipations() + ", oppositions=" + this.getOppositions() + - ", respondents=" + this.getRespondents() + ", document=" + this.getDocument() + - ", documentUploadDate=" + this.getDocumentUploadDate() + ", presentationLanguage=" + - this.getPresentationLanguage() + ", maxOpponents=" + this.getMaxOpponents() + - ", maxParticipants=" + this.getMaxParticipants() + ", creationReason=" + - this.getCreationReason() + ")"; + return ( + "FinalSeminar(id=" + + this.getId() + + ", project=" + + this.getProject() + + ", startDate=" + + this.getStartDate() + + ", room=" + + this.getRoom() + + ", activeParticipations=" + + this.getActiveParticipations() + + ", oppositions=" + + this.getOppositions() + + ", respondents=" + + this.getRespondents() + + ", document=" + + this.getDocument() + + ", documentUploadDate=" + + this.getDocumentUploadDate() + + ", presentationLanguage=" + + this.getPresentationLanguage() + + ", maxOpponents=" + + this.getMaxOpponents() + + ", maxParticipants=" + + this.getMaxParticipants() + + ", creationReason=" + + this.getCreationReason() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -314,9 +331,9 @@ public class FinalSeminar extends LazyDeletableDomainObject { activeParticipations.removeIf(next -> next.getUser().equals(user)); } - public Set getActiveParticipants(){ + public Set getActiveParticipants() { Set activeParticipants = new HashSet<>(); - for (FinalSeminarActiveParticipation fsap : activeParticipations){ + for (FinalSeminarActiveParticipation fsap : activeParticipations) { activeParticipants.add(fsap.getUser()); } return activeParticipants; @@ -334,9 +351,9 @@ public class FinalSeminar extends LazyDeletableDomainObject { this.oppositions.remove(opposition); } - public Set getOpponents(){ + public Set getOpponents() { Set opponents = new HashSet<>(); - for (FinalSeminarOpposition fso : oppositions){ + for (FinalSeminarOpposition fso : oppositions) { opponents.add(fso.getUser()); } return opponents; @@ -353,7 +370,7 @@ public class FinalSeminar extends LazyDeletableDomainObject { private Collection getNotGradedParticipations(Set participations) { List result = new ArrayList<>(); for (FinalSeminarParticipation participation : participations) { - if(participation.getGrade() == null) { + if (participation.getGrade() == null) { result.add(participation.getUser()); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipation.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipation.java index fdc7bf1429..f0565b5a28 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipation.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipation.java @@ -1,18 +1,18 @@ package se.su.dsv.scipro.finalseminar; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.project.Project; - import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import java.util.Objects; +import se.su.dsv.scipro.project.Project; @Entity @Table(name = "final_seminar_active_participation") @Cacheable(true) public class FinalSeminarActiveParticipation extends FinalSeminarParticipation { + // ---------------------------------------------------------------------------------- // JPA-mappings of foreign keys in this table (final_seminar_active_participation) // referencing other tables. @@ -40,9 +40,7 @@ public class FinalSeminarActiveParticipation extends FinalSeminarParticipation { if (o == this) return true; if (!(o instanceof FinalSeminarActiveParticipation)) return false; final FinalSeminarActiveParticipation other = (FinalSeminarActiveParticipation) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.project, other.project); + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.project, other.project)); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepository.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepository.java index 9335918377..98bf95c743 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import java.util.*; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.*; - public interface FinalSeminarActiveParticipationRepository { List findByParticipatingUserAndLevel(User user, ProjectType projectType); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepositoryImpl.java index 7c20d3f851..f85dc68c0a 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationRepositoryImpl.java @@ -1,15 +1,17 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.AbstractRepository; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.system.AbstractRepository; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; + +public class FinalSeminarActiveParticipationRepositoryImpl + extends AbstractRepository + implements FinalSeminarActiveParticipationRepository { -public class FinalSeminarActiveParticipationRepositoryImpl extends AbstractRepository implements FinalSeminarActiveParticipationRepository { @Inject public FinalSeminarActiveParticipationRepositoryImpl(Provider em) { super(em); @@ -18,8 +20,8 @@ public class FinalSeminarActiveParticipationRepositoryImpl extends AbstractRepos @Override public List findByParticipatingUserAndLevel(User user, ProjectType projectType) { return from(QFinalSeminarActiveParticipation.finalSeminarActiveParticipation) - .where(QFinalSeminarActiveParticipation.finalSeminarActiveParticipation.user.eq(user)) - .where(QFinalSeminarActiveParticipation.finalSeminarActiveParticipation.project.projectType.eq(projectType)) - .fetch(); + .where(QFinalSeminarActiveParticipation.finalSeminarActiveParticipation.user.eq(user)) + .where(QFinalSeminarActiveParticipation.finalSeminarActiveParticipation.project.projectType.eq(projectType)) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationService.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationService.java index 90b7e0f2c2..7540ccad98 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationService.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationService.java @@ -3,7 +3,6 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; -public interface FinalSeminarActiveParticipationService extends GenericService{ - - FinalSeminarActiveParticipation findByFinalSeminarUser(FinalSeminar finalSeminar,User user); +public interface FinalSeminarActiveParticipationService extends GenericService { + FinalSeminarActiveParticipation findByFinalSeminarUser(FinalSeminar finalSeminar, User user); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationServiceImpl.java index a51f10f6bc..c1c6f367a4 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarActiveParticipationServiceImpl.java @@ -1,28 +1,31 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.User; -public class FinalSeminarActiveParticipationServiceImpl extends AbstractServiceImpl implements FinalSeminarActiveParticipationService { +public class FinalSeminarActiveParticipationServiceImpl + extends AbstractServiceImpl + implements FinalSeminarActiveParticipationService { @Inject public FinalSeminarActiveParticipationServiceImpl(Provider em) { - super(em, FinalSeminarActiveParticipation.class, QFinalSeminarActiveParticipation.finalSeminarActiveParticipation); + super( + em, + FinalSeminarActiveParticipation.class, + QFinalSeminarActiveParticipation.finalSeminarActiveParticipation + ); } @Override - public FinalSeminarActiveParticipation findByFinalSeminarUser(FinalSeminar finalSeminar,User user){ - + public FinalSeminarActiveParticipation findByFinalSeminarUser(FinalSeminar finalSeminar, User user) { for (FinalSeminarActiveParticipation fsap : finalSeminar.getActiveParticipations()) { - if(fsap.getUser().equals(user)){ + if (fsap.getUser().equals(user)) { return fsap; } } - return null; + return null; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreatedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreatedEvent.java index 56f688e50d..86a442000a 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreatedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreatedEvent.java @@ -3,17 +3,18 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.project.Project; public final class FinalSeminarCreatedEvent { - private final FinalSeminar finalSeminar; - public FinalSeminar getFinalSeminar(){ + private final FinalSeminar finalSeminar; + + public FinalSeminar getFinalSeminar() { return finalSeminar; } - public FinalSeminarCreatedEvent(FinalSeminar finalSeminar) { - this.finalSeminar = finalSeminar; - } + public FinalSeminarCreatedEvent(FinalSeminar finalSeminar) { + this.finalSeminar = finalSeminar; + } - public Project getProject() { - return finalSeminar.getProject(); - } + public Project getProject() { + return finalSeminar.getProject(); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreationSubscribers.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreationSubscribers.java index f0597564bb..2774ea82a5 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreationSubscribers.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarCreationSubscribers.java @@ -2,6 +2,10 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.NotificationController; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; @@ -9,21 +13,17 @@ import se.su.dsv.scipro.notifications.dataobject.SeminarEvent; import se.su.dsv.scipro.project.Author; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - public class FinalSeminarCreationSubscribers { + private final AuthorRepository authorRepository; private final FinalSeminarService finalSeminarService; private final NotificationController notificationController; FinalSeminarCreationSubscribers( - AuthorRepository authorRepository, - FinalSeminarService finalSeminarService, - NotificationController notificationController) - { + AuthorRepository authorRepository, + FinalSeminarService finalSeminarService, + NotificationController notificationController + ) { this.authorRepository = authorRepository; this.finalSeminarService = finalSeminarService; this.notificationController = notificationController; @@ -31,42 +31,54 @@ public class FinalSeminarCreationSubscribers { @Inject public FinalSeminarCreationSubscribers( - AuthorRepository authorRepository, - FinalSeminarService finalSeminarService, - NotificationController notificationController, - EventBus eventBus) - { + AuthorRepository authorRepository, + FinalSeminarService finalSeminarService, + NotificationController notificationController, + EventBus eventBus + ) { this(authorRepository, finalSeminarService, notificationController); eventBus.register(this); } @Subscribe public void finalSeminarCreated(FinalSeminarCreatedEvent event) { - List subscribers = authorRepository.getSubscribersWithActiveProjectOnType(event.getFinalSeminar().getProjectType()); + List subscribers = authorRepository.getSubscribersWithActiveProjectOnType( + event.getFinalSeminar().getProjectType() + ); Set users = getSubscribersStillNeedingOppositionOrParticipation(subscribers) - .stream() - .map(user -> new Member(user, Member.Type.OPPONENT)) - .collect(Collectors.toSet()); - notificationController.notifyCustomSeminar(event.getFinalSeminar(), SeminarEvent.Event.CREATED, new NotificationSource(), users); + .stream() + .map(user -> new Member(user, Member.Type.OPPONENT)) + .collect(Collectors.toSet()); + notificationController.notifyCustomSeminar( + event.getFinalSeminar(), + SeminarEvent.Event.CREATED, + new NotificationSource(), + users + ); } private List getSubscribersStillNeedingOppositionOrParticipation(List subscribers) { return subscribers - .stream() - .filter(subscriber -> onlyFailedOppositions(subscriber) || onlyFailedParticipations(subscriber)) - .map(Author::getUser) - .toList(); + .stream() + .filter(subscriber -> onlyFailedOppositions(subscriber) || onlyFailedParticipations(subscriber)) + .map(Author::getUser) + .toList(); } private boolean onlyFailedParticipations(Author subscriber) { - return finalSeminarService.findUserParticipating(subscriber.getProject(), subscriber.getUser()) - .stream() - .noneMatch(FinalSeminarParticipation::isApproved); + return finalSeminarService + .findUserParticipating(subscriber.getProject(), subscriber.getUser()) + .stream() + .noneMatch(FinalSeminarParticipation::isApproved); } private boolean onlyFailedOppositions(Author subscriber) { - return finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(subscriber.getProject().getProjectType(), subscriber.getUser()) - .stream() - .noneMatch(FinalSeminarParticipation::isApproved); + return finalSeminarService + .findFinalSeminarOppositionsByOpponentAndProjectType( + subscriber.getProject().getProjectType(), + subscriber.getUser() + ) + .stream() + .noneMatch(FinalSeminarParticipation::isApproved); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDeletedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDeletedEvent.java index 8f9c03be27..d983521445 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDeletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDeletedEvent.java @@ -3,17 +3,18 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.project.Project; public final class FinalSeminarDeletedEvent { - private final FinalSeminar finalSeminar; - public FinalSeminar getFinalSeminar(){ + private final FinalSeminar finalSeminar; + + public FinalSeminar getFinalSeminar() { return finalSeminar; } - public FinalSeminarDeletedEvent(FinalSeminar finalSeminar) { - this.finalSeminar = finalSeminar; - } + public FinalSeminarDeletedEvent(FinalSeminar finalSeminar) { + this.finalSeminar = finalSeminar; + } - public Project getProject() { - return finalSeminar.getProject(); - } + public Project getProject() { + return finalSeminar.getProject(); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetails.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetails.java index 31a66177f7..65b74b9f6d 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetails.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetails.java @@ -3,12 +3,11 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.system.Language; public record FinalSeminarDetails( - String location, - Boolean manualParticipants, - int maxParticipants, - int maxOpponents, - Language presentationLanguage, - Language reportLanguage, - String extraInfo) -{ -} + String location, + Boolean manualParticipants, + int maxParticipants, + int maxOpponents, + Language presentationLanguage, + Language reportLanguage, + String extraInfo +) {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarGrade.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarGrade.java index bd3aa7c55e..5471434114 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarGrade.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarGrade.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.finalseminar; public enum FinalSeminarGrade { - APPROVED { @Override public String toString() { return "approved"; } - }, NOT_APPROVED { + }, + NOT_APPROVED { @Override public String toString() { return "not approved"; } - } - + }, } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarMovedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarMovedEvent.java index 98a4ff8f6e..9ba43dc5db 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarMovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarMovedEvent.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.finalseminar; import java.time.LocalDateTime; -public record FinalSeminarMovedEvent(FinalSeminar finalSeminar, LocalDateTime from, LocalDateTime to) { -} +public record FinalSeminarMovedEvent(FinalSeminar finalSeminar, LocalDateTime from, LocalDateTime to) {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOpposition.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOpposition.java index de9c6cd3a4..9825e981a8 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOpposition.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOpposition.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.report.OppositionReport; -import se.su.dsv.scipro.system.ProjectType; - import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -13,12 +8,16 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.util.Objects; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.report.OppositionReport; +import se.su.dsv.scipro.system.ProjectType; @Entity -@Table(name="final_seminar_opposition") +@Table(name = "final_seminar_opposition") public class FinalSeminarOpposition extends FinalSeminarParticipation { + private static final int FEEDBACK_LENGTH = 2000; // ---------------------------------------------------------------------------------- @@ -47,8 +46,7 @@ public class FinalSeminarOpposition extends FinalSeminarParticipation { // ---------------------------------------------------------------------------------- // JPA-mappings of other tables referencing to this table (final_seminar_opposition) // ---------------------------------------------------------------------------------- - @OneToOne(optional = true, orphanRemoval = true, cascade = CascadeType.ALL, - mappedBy = "finalSeminarOpposition") + @OneToOne(optional = true, orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "finalSeminarOpposition") private OppositionReport oppositionReport; // ---------------------------------------------------------------------------------- @@ -102,9 +100,7 @@ public class FinalSeminarOpposition extends FinalSeminarParticipation { if (o == this) return true; if (!(o instanceof FinalSeminarOpposition)) return false; final FinalSeminarOpposition other = (FinalSeminarOpposition) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getProject(), other.getProject()); + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.getProject(), other.getProject())); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepo.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepo.java index 46957a9678..e636597075 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepo.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.finalseminar; import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; import se.su.dsv.scipro.system.User; -import java.util.*; - - @Transactional -public interface FinalSeminarOppositionRepo extends JpaRepository, QueryDslPredicateExecutor { +public interface FinalSeminarOppositionRepo + extends JpaRepository, QueryDslPredicateExecutor { List findByOpposingUserAndType(User user, ProjectType projectType); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepoImpl.java index 2fe781e2b7..00ad589634 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionRepoImpl.java @@ -1,15 +1,17 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.GenericRepo; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.system.GenericRepo; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; + +public class FinalSeminarOppositionRepoImpl + extends GenericRepo + implements FinalSeminarOppositionRepo { -public class FinalSeminarOppositionRepoImpl extends GenericRepo implements FinalSeminarOppositionRepo { @Inject public FinalSeminarOppositionRepoImpl(Provider em) { super(em, FinalSeminarOpposition.class, QFinalSeminarOpposition.finalSeminarOpposition); @@ -18,8 +20,8 @@ public class FinalSeminarOppositionRepoImpl extends GenericRepo findByOpposingUserAndType(User user, ProjectType projectType) { return createQuery() - .where(QFinalSeminarOpposition.finalSeminarOpposition.user.eq(user)) - .where(QFinalSeminarOpposition.finalSeminarOpposition.project.projectType.eq(projectType)) - .fetch(); + .where(QFinalSeminarOpposition.finalSeminarOpposition.user.eq(user)) + .where(QFinalSeminarOpposition.finalSeminarOpposition.project.projectType.eq(projectType)) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionService.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionService.java index 67caa1eb91..60eeacc1a9 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionService.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionService.java @@ -3,8 +3,6 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.system.GenericService; public interface FinalSeminarOppositionService extends GenericService { - @Override void delete(Long aLong); - } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImpl.java index b1d0a48fd8..27550bb3ac 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImpl.java @@ -1,12 +1,14 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; + +public class FinalSeminarOppositionServiceImpl + extends AbstractServiceImpl + implements FinalSeminarOppositionService { -public class FinalSeminarOppositionServiceImpl extends AbstractServiceImpl implements FinalSeminarOppositionService { @Inject public FinalSeminarOppositionServiceImpl(Provider em) { super(em, FinalSeminarOpposition.class, QFinalSeminarOpposition.finalSeminarOpposition); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarParticipation.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarParticipation.java index 8d97c21020..b7d4157f7a 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarParticipation.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarParticipation.java @@ -10,13 +10,13 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MappedSuperclass; +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Objects; - @MappedSuperclass public abstract class FinalSeminarParticipation extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -45,8 +45,7 @@ public abstract class FinalSeminarParticipation extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected FinalSeminarParticipation() { - } + protected FinalSeminarParticipation() {} protected FinalSeminarParticipation(User user, FinalSeminar finalSeminar) { this.user = user; @@ -97,9 +96,11 @@ public abstract class FinalSeminarParticipation extends DomainObject { if (o == this) return true; if (!(o instanceof FinalSeminarParticipation)) return false; final FinalSeminarParticipation other = (FinalSeminarParticipation) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getFinalSeminar(), other.getFinalSeminar()); + return ( + other.canEqual(this) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getFinalSeminar(), other.getFinalSeminar()) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRepositoryImpl.java index 40e72964a7..597496bd99 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRepositoryImpl.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.finalseminar; -import jakarta.transaction.Transactional; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.system.AbstractRepository; public class FinalSeminarRepositoryImpl extends AbstractRepository implements FinalSeminarRepository { + @Inject public FinalSeminarRepositoryImpl(Provider em) { super(em); @@ -19,8 +19,7 @@ public class FinalSeminarRepositoryImpl extends AbstractRepository implements Fi EntityManager entityManager = em(); if (entityManager.contains(finalSeminar)) { return entityManager.merge(finalSeminar); - } - else { + } else { entityManager.persist(finalSeminar); return finalSeminar; } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondent.java index 92bf8ee457..b350817c7e 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondent.java @@ -1,19 +1,17 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Table; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "final_seminar_respondent") @Cacheable(true) public class FinalSeminarRespondent extends FinalSeminarParticipation { - protected FinalSeminarRespondent() { - } + protected FinalSeminarRespondent() {} public FinalSeminarRespondent(User student, FinalSeminar finalSeminar) { super(student, finalSeminar); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentService.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentService.java index a5662f2c54..aee6ce5e72 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentService.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.GenericService; - import java.util.List; +import se.su.dsv.scipro.system.GenericService; public interface FinalSeminarRespondentService extends GenericService { List findOrCreate(FinalSeminar finalSeminar); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImpl.java index f532f0289d..cae9b20414 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImpl.java @@ -1,21 +1,22 @@ package se.su.dsv.scipro.finalseminar; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.User; +import static com.querydsl.core.types.dsl.Expressions.allOf; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; - -import static com.querydsl.core.types.dsl.Expressions.allOf; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.User; @Named -public class FinalSeminarRespondentServiceImpl extends AbstractServiceImpl implements FinalSeminarRespondentService { +public class FinalSeminarRespondentServiceImpl + extends AbstractServiceImpl + implements FinalSeminarRespondentService { @Inject public FinalSeminarRespondentServiceImpl(Provider em) { @@ -23,9 +24,12 @@ public class FinalSeminarRespondentServiceImpl extends AbstractServiceImpl findOrCreate(FinalSeminar finalSeminar) { - if(finalSeminar.getId() == null) { + if (finalSeminar.getId() == null) { return new ArrayList<>(); } List finalSeminarRespondents = new ArrayList<>(); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarScheduling.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarScheduling.java index a39d50f9de..c12560a261 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarScheduling.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarScheduling.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.util.Either; - import java.time.LocalDate; import java.time.LocalDateTime; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.util.Either; public interface FinalSeminarScheduling { Either schedule(Project project, LocalDateTime when, FinalSeminarDetails details); diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarService.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarService.java index b39387d3c1..5f56d80aaa 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarService.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarService.java @@ -1,28 +1,49 @@ - package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.*; -import se.su.dsv.scipro.util.Either; - import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.util.Either; -public interface FinalSeminarService extends GenericService, FilteredService, FinalSeminarScheduling { - Either attemptAddOpposition(User student, FinalSeminar finalSeminar, Project project); +public interface FinalSeminarService + extends + GenericService, + FilteredService, + FinalSeminarScheduling { + Either attemptAddOpposition( + User student, + FinalSeminar finalSeminar, + Project project + ); - Either attemptAddActiveParticipation(User student, FinalSeminar finalSeminar, Project project); + Either attemptAddActiveParticipation( + User student, + FinalSeminar finalSeminar, + Project project + ); - Either attemptAddOppositionAsSupervisor(User student, FinalSeminar finalSeminar, Project project); + Either attemptAddOppositionAsSupervisor( + User student, + FinalSeminar finalSeminar, + Project project + ); - Either attemptAddActiveParticipationAsSupervisor(User student, FinalSeminar finalSeminar, Project project); + Either attemptAddActiveParticipationAsSupervisor( + User student, + FinalSeminar finalSeminar, + Project project + ); Either canOppose(User Student, FinalSeminar finalSeminar, Project project); - Either canActiveParticipate(User student, FinalSeminar finalSeminar); + Either canActiveParticipate( + User student, + FinalSeminar finalSeminar + ); Iterable findAll(Filter params); @@ -51,7 +72,10 @@ public interface FinalSeminarService extends GenericService, FinalSeminar cancel(FinalSeminar finalSeminar); - List findFinalSeminarOppositionsByOpponentAndProjectType(ProjectType projectType, User user); + List findFinalSeminarOppositionsByOpponentAndProjectType( + ProjectType projectType, + User user + ); List findUserParticipating(Project project, User user); @@ -60,6 +84,7 @@ public interface FinalSeminarService extends GenericService, void toggleSubscriptionToSeminarCreationNotifications(Project project, User user); class Filter implements Serializable { + private Date fromDate; private Date toDate; private Boolean lazyDeleted; @@ -147,16 +172,18 @@ public interface FinalSeminarService extends GenericService, if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getFromDate(), other.getFromDate()) - && Objects.equals(this.getToDate(), other.getToDate()) - && Objects.equals(this.getLazyDeleted(), other.getLazyDeleted()) - && Objects.equals(this.getExempted(), other.getExempted()) - && Objects.equals(this.getOnlyActiveProjects(), other.getOnlyActiveProjects()) - && Objects.equals(this.getOnlyActiveOrCompletedProjects(), other.getOnlyActiveOrCompletedProjects()) - && Objects.equals(this.getHeadSupervisor(), other.getHeadSupervisor()) - && Objects.equals(this.getDegreeType(), other.getDegreeType()) - && Objects.equals(this.onlyNonManualParticipants, other.onlyNonManualParticipants); + return ( + other.canEqual(this) && + Objects.equals(this.getFromDate(), other.getFromDate()) && + Objects.equals(this.getToDate(), other.getToDate()) && + Objects.equals(this.getLazyDeleted(), other.getLazyDeleted()) && + Objects.equals(this.getExempted(), other.getExempted()) && + Objects.equals(this.getOnlyActiveProjects(), other.getOnlyActiveProjects()) && + Objects.equals(this.getOnlyActiveOrCompletedProjects(), other.getOnlyActiveOrCompletedProjects()) && + Objects.equals(this.getHeadSupervisor(), other.getHeadSupervisor()) && + Objects.equals(this.getDegreeType(), other.getDegreeType()) && + Objects.equals(this.onlyNonManualParticipants, other.onlyNonManualParticipants) + ); } protected boolean canEqual(final Object other) { @@ -166,29 +193,42 @@ public interface FinalSeminarService extends GenericService, @Override public int hashCode() { return Objects.hash( - this.getFromDate(), - this.getToDate(), - this.getLazyDeleted(), - this.getExempted(), - this.getOnlyActiveProjects(), - this.getOnlyActiveOrCompletedProjects(), - this.getHeadSupervisor(), - this.getDegreeType(), - this.getOnlyNonManualParticipants()); + this.getFromDate(), + this.getToDate(), + this.getLazyDeleted(), + this.getExempted(), + this.getOnlyActiveProjects(), + this.getOnlyActiveOrCompletedProjects(), + this.getHeadSupervisor(), + this.getDegreeType(), + this.getOnlyNonManualParticipants() + ); } @Override public String toString() { - return "FinalSeminarService.Filter(" + - "fromDate=" + this.getFromDate() - + ", toDate=" + this.getToDate() - + ", lazyDeleted=" + this.getLazyDeleted() - + ", exempted=" + this.getExempted() - + ", onlyActiveProjects=" + this.getOnlyActiveProjects() - + ", onlyActiveOrCompletedProjects=" + this.getOnlyActiveOrCompletedProjects() - + ", headSupervisor=" + this.getHeadSupervisor() - + ", degreeType=" + this.getDegreeType() - + ", onlyNonManualParticipants=" + this.getOnlyNonManualParticipants() + ")"; + return ( + "FinalSeminarService.Filter(" + + "fromDate=" + + this.getFromDate() + + ", toDate=" + + this.getToDate() + + ", lazyDeleted=" + + this.getLazyDeleted() + + ", exempted=" + + this.getExempted() + + ", onlyActiveProjects=" + + this.getOnlyActiveProjects() + + ", onlyActiveOrCompletedProjects=" + + this.getOnlyActiveOrCompletedProjects() + + ", headSupervisor=" + + this.getHeadSupervisor() + + ", degreeType=" + + this.getDegreeType() + + ", onlyNonManualParticipants=" + + this.getOnlyNonManualParticipants() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImpl.java index b5514bcd3e..0af91dca55 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImpl.java @@ -1,11 +1,16 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.dsl.BooleanExpression; +import jakarta.inject.Inject; +import jakarta.inject.Provider; import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.Pageable; +import jakarta.transaction.Transactional; +import java.time.*; +import java.util.Date; +import java.util.List; +import java.util.Optional; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.misc.DaysService; @@ -17,25 +22,22 @@ import se.su.dsv.scipro.report.OppositionReportService; import se.su.dsv.scipro.reviewing.RoughDraftApproval; import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.time.*; -import java.util.Date; -import java.util.List; -import java.util.Optional; - public class FinalSeminarServiceImpl extends AbstractServiceImpl implements FinalSeminarService { @Inject FinalSeminarSettingsService finalSeminarSettingsService; + @Inject DaysService daysService; + @Inject OppositionReportService oppositionReportService; + @Inject NonWorkDayPeriodService nonWorkDayPeriodService; @@ -50,15 +52,16 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl em, - EventBus eventBus, - AuthorRepository authorRepository, - final FileService fileService, - FinalSeminarOppositionRepo finalSeminarOppositionRepository, - FinalSeminarActiveParticipationRepository finalSeminarActiveParticipationRepository, - FinalSeminarRepository finalSeminarRepository, - Clock clock, - RoughDraftApprovalService roughDraftApprovalService) { + Provider em, + EventBus eventBus, + AuthorRepository authorRepository, + final FileService fileService, + FinalSeminarOppositionRepo finalSeminarOppositionRepository, + FinalSeminarActiveParticipationRepository finalSeminarActiveParticipationRepository, + FinalSeminarRepository finalSeminarRepository, + Clock clock, + RoughDraftApprovalService roughDraftApprovalService + ) { super(em, FinalSeminar.class, QFinalSeminar.finalSeminar); this.eventBus = eventBus; this.authorRepository = authorRepository; @@ -72,7 +75,11 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl schedule(Project project, LocalDateTime when, FinalSeminarDetails details) { + public Either schedule( + Project project, + LocalDateTime when, + FinalSeminarDetails details + ) { if (project.isFinalSeminarRuleExempted()) { return createSeminar(project, when, details); } @@ -80,9 +87,10 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl createSeminar( - Project project, - LocalDateTime when, - FinalSeminarDetails details) { + Project project, + LocalDateTime when, + FinalSeminarDetails details + ) { FinalSeminar finalSeminar = new FinalSeminar(project); FinalSeminar persisted = setDetails(finalSeminar, when, details); eventBus.post(new FinalSeminarCreatedEvent(persisted)); @@ -211,7 +219,11 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl canOppose(User Student, FinalSeminar finalSeminar, Project project) { + public Either canOppose( + User Student, + FinalSeminar finalSeminar, + Project project + ) { if (finalSeminar.isCancelled()) { return Either.left(new FinalSeminarCancelled()); } @@ -227,7 +239,11 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl= finalSeminar.getMaxOpponents()) { return Either.left(new TooManyOpponents()); } - for (FinalSeminarOpposition opposition : finalSeminarOppositionRepository.findByOpposingUserAndType(Student, project.getProjectType())) { + List oppositions = finalSeminarOppositionRepository.findByOpposingUserAndType( + Student, + project.getProjectType() + ); + for (FinalSeminarOpposition opposition : oppositions) { if (opposition.getGrade() == null) { return Either.left(new UngradedOpposition()); } else if (opposition.getGrade() == FinalSeminarGrade.APPROVED) { @@ -244,7 +260,10 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl canActiveParticipate(User student, FinalSeminar finalSeminar) { + public Either canActiveParticipate( + User student, + FinalSeminar finalSeminar + ) { if (finalSeminar.getManualParticipants()) { return Either.left(new ManualParticipants()); } @@ -264,20 +283,32 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl attemptAddOpposition(final User student, final FinalSeminar finalSeminar, final Project project) { - return canOppose(student, finalSeminar, project) - .map(allowed -> createAndSaveOpposition(student, finalSeminar, project)); + public Either attemptAddOpposition( + final User student, + final FinalSeminar finalSeminar, + final Project project + ) { + return canOppose(student, finalSeminar, project).map(allowed -> + createAndSaveOpposition(student, finalSeminar, project) + ); } @Override @Transactional - public Either attemptAddOppositionAsSupervisor(User student, FinalSeminar finalSeminar, Project project) { - + public Either attemptAddOppositionAsSupervisor( + User student, + FinalSeminar finalSeminar, + Project project + ) { if (alreadyActiveParticipant(student, finalSeminar)) { return Either.left(OpposeError.ALREADY_PARTICIPANT); } else if (alreadyOpponent(student, finalSeminar)) { @@ -301,14 +332,22 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl attemptAddActiveParticipation(final User student, final FinalSeminar finalSeminar, final Project project) { - return canActiveParticipate(student, finalSeminar) - .map(allowed -> createAndSaveActiveParticipation(student, finalSeminar, project)); + public Either< + ActiveParticipationRegistrationErrorStatus, + FinalSeminarActiveParticipation + > attemptAddActiveParticipation(final User student, final FinalSeminar finalSeminar, final Project project) { + return canActiveParticipate(student, finalSeminar).map(allowed -> + createAndSaveActiveParticipation(student, finalSeminar, project) + ); } @Override @Transactional - public Either attemptAddActiveParticipationAsSupervisor(User student, FinalSeminar finalSeminar, Project project) { + public Either attemptAddActiveParticipationAsSupervisor( + User student, + FinalSeminar finalSeminar, + Project project + ) { if (alreadyActiveParticipant(student, finalSeminar)) { return Either.left(ParticipateError.ALREADY_PARTICIPANT); } else if (alreadyOpponent(student, finalSeminar)) { @@ -320,7 +359,11 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl getOppositionsByProjectAuthors(Project project) { - return project.getProjectParticipants() - .stream() - .map(author -> findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), author)) - .flatMap(List::stream) - .toList(); + return project + .getProjectParticipants() + .stream() + .map(author -> findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), author)) + .flatMap(List::stream) + .toList(); } @Override public boolean hasHadFinalSeminar(Project project) { FinalSeminar finalSeminar = findByProject(project); - return finalSeminar != null && finalSeminar.getStartDate().toInstant().isBefore(clock.instant()); + return (finalSeminar != null && finalSeminar.getStartDate().toInstant().isBefore(clock.instant())); } @Override @@ -463,39 +509,52 @@ public class FinalSeminarServiceImpl extends AbstractServiceImpl findFinalSeminarOppositionsByOpponentAndProjectType(ProjectType projectType, User user) { + public List findFinalSeminarOppositionsByOpponentAndProjectType( + ProjectType projectType, + User user + ) { return finalSeminarOppositionRepository.findByOpposingUserAndType(user, projectType); } @Override public List findUserParticipating(Project project, User user) { - return finalSeminarActiveParticipationRepository.findByParticipatingUserAndLevel(user, project.getProjectType()); + return finalSeminarActiveParticipationRepository.findByParticipatingUserAndLevel( + user, + project.getProjectType() + ); } @Override public boolean isSubscribedToSeminarCreationNotifications(Project project, User user) { final Optional author = authorRepository.findByProjectAndUser(project, user); - return author.isPresent() && author.get().isSubscribedToFinalSeminarNotifications(); + return (author.isPresent() && author.get().isSubscribedToFinalSeminarNotifications()); } @Override @Transactional public void toggleSubscriptionToSeminarCreationNotifications(Project project, User user) { - authorRepository.findByProjectAndUser(project, user) - .ifPresent(author -> author.setSubscribedToFinalSeminarNotifications(!author.isSubscribedToFinalSeminarNotifications())); + authorRepository + .findByProjectAndUser(project, user) + .ifPresent(author -> + author.setSubscribedToFinalSeminarNotifications(!author.isSubscribedToFinalSeminarNotifications()) + ); } private BooleanExpression unfinishedSeminars(Date after, Date before) { QFinalSeminar seminar = QFinalSeminar.finalSeminar; if (after == null && before == null) { - return seminar.oppositions.any().grade.isNull().or( - seminar.activeParticipations.any().grade.isNull().or( - seminar.respondents.any().grade.isNull())); + return seminar.oppositions + .any() + .grade.isNull() + .or(seminar.activeParticipations.any().grade.isNull().or(seminar.respondents.any().grade.isNull())); } else { - return seminar.startDate.between(after, before) - .andAnyOf(seminar.oppositions.any().grade.isNull(), - seminar.activeParticipations.any().grade.isNull(), - seminar.respondents.any().grade.isNull()); + return seminar.startDate + .between(after, before) + .andAnyOf( + seminar.oppositions.any().grade.isNull(), + seminar.activeParticipations.any().grade.isNull(), + seminar.respondents.any().grade.isNull() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettings.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettings.java index 7a62ea83e9..6468b01d85 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettings.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.finalseminar; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.*; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Cacheable(true) @Table(name = "final_seminar_settings") public class FinalSeminarSettings extends DomainObject { + public static final int DEFAULT_DAYS_AHEAD_TO_UPLOAD_THESIS = 10; public static final int DEFAULT_DAYS_AHEAD_TO_REGISTER_OPPOSITION = 3; public static final int DEFAULT_DAYS_AHEAD_TO_REGISTER_PARTICIPATION = 1; @@ -16,8 +16,7 @@ public class FinalSeminarSettings extends DomainObject { @Id private Long id = null; - public FinalSeminarSettings() { - } + public FinalSeminarSettings() {} public FinalSeminarSettings(final Long id) { this.id = id; @@ -116,7 +115,25 @@ public class FinalSeminarSettings extends DomainObject { @Override public String toString() { - return "FinalSeminarSettings(id=" + this.getId() + ", daysAheadToCreate=" + this.getDaysAheadToCreate() + ", daysAheadToRegisterParticipation=" + this.getDaysAheadToRegisterParticipation() + ", daysAheadToRegisterOpposition=" + this.getDaysAheadToRegisterOpposition() + ", daysAheadToUploadThesis=" + this.getDaysAheadToUploadThesis() + ", thesisMustBePDF=" + this.isThesisMustBePDF() + ", evaluationURL=" + this.getEvaluationURL() + ", oppositionPriorityDays=" + this.getOppositionPriorityDays() + ")"; + return ( + "FinalSeminarSettings(id=" + + this.getId() + + ", daysAheadToCreate=" + + this.getDaysAheadToCreate() + + ", daysAheadToRegisterParticipation=" + + this.getDaysAheadToRegisterParticipation() + + ", daysAheadToRegisterOpposition=" + + this.getDaysAheadToRegisterOpposition() + + ", daysAheadToUploadThesis=" + + this.getDaysAheadToUploadThesis() + + ", thesisMustBePDF=" + + this.isThesisMustBePDF() + + ", evaluationURL=" + + this.getEvaluationURL() + + ", oppositionPriorityDays=" + + this.getOppositionPriorityDays() + + ")" + ); } @Override @@ -124,16 +141,18 @@ public class FinalSeminarSettings extends DomainObject { if (o == this) return true; if (!(o instanceof FinalSeminarSettings)) return false; final FinalSeminarSettings other = (FinalSeminarSettings) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && this.getDaysAheadToCreate() == other.getDaysAheadToCreate() - && this.getDaysAheadToRegisterParticipation() == other.getDaysAheadToRegisterParticipation() - && this.getDaysAheadToRegisterOpposition() == other.getDaysAheadToRegisterOpposition() - && this.getDaysAheadToUploadThesis() == other.getDaysAheadToUploadThesis() - && this.isThesisMustBePDF() == other.isThesisMustBePDF() - && Objects.equals(this.getEvaluationURL(), other.getEvaluationURL()) - && this.getOppositionPriorityDays() == other.getOppositionPriorityDays(); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + this.getDaysAheadToCreate() == other.getDaysAheadToCreate() && + this.getDaysAheadToRegisterParticipation() == other.getDaysAheadToRegisterParticipation() && + this.getDaysAheadToRegisterOpposition() == other.getDaysAheadToRegisterOpposition() && + this.getDaysAheadToUploadThesis() == other.getDaysAheadToUploadThesis() && + this.isThesisMustBePDF() == other.isThesisMustBePDF() && + Objects.equals(this.getEvaluationURL(), other.getEvaluationURL()) && + this.getOppositionPriorityDays() == other.getOppositionPriorityDays() + ); } protected boolean canEqual(final Object other) { @@ -143,13 +162,14 @@ public class FinalSeminarSettings extends DomainObject { @Override public int hashCode() { return Objects.hash( - this.getId(), - this.getDaysAheadToCreate(), - this.getDaysAheadToRegisterParticipation(), - this.getDaysAheadToRegisterOpposition(), - this.getDaysAheadToUploadThesis(), - this.isThesisMustBePDF(), - this.getEvaluationURL(), - this.getOppositionPriorityDays()); + this.getId(), + this.getDaysAheadToCreate(), + this.getDaysAheadToRegisterParticipation(), + this.getDaysAheadToRegisterOpposition(), + this.getDaysAheadToUploadThesis(), + this.isThesisMustBePDF(), + this.getEvaluationURL(), + this.getOppositionPriorityDays() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettingsServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettingsServiceImpl.java index c912f35abb..5495ac7f1e 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettingsServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarSettingsServiceImpl.java @@ -1,29 +1,30 @@ package se.su.dsv.scipro.finalseminar; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.system.AbstractServiceImpl; -public class FinalSeminarSettingsServiceImpl extends AbstractServiceImpl implements FinalSeminarSettingsService { +public class FinalSeminarSettingsServiceImpl + extends AbstractServiceImpl + implements FinalSeminarSettingsService { - private static final long INSTANCE_ID = 1L; + private static final long INSTANCE_ID = 1L; - @Inject - public FinalSeminarSettingsServiceImpl(Provider em) { + @Inject + public FinalSeminarSettingsServiceImpl(Provider em) { super(em, FinalSeminarSettings.class, QFinalSeminarSettings.finalSeminarSettings); - } + } - @Override - @Transactional - public FinalSeminarSettings getInstance() { - FinalSeminarSettings settings = findOne(INSTANCE_ID); - if(settings==null) { - settings = new FinalSeminarSettings(INSTANCE_ID); - save(settings); - } - return settings; - } + @Override + @Transactional + public FinalSeminarSettings getInstance() { + FinalSeminarSettings settings = findOne(INSTANCE_ID); + if (settings == null) { + settings = new FinalSeminarSettings(INSTANCE_ID); + save(settings); + } + return settings; + } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisDeletedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisDeletedEvent.java index 1f74d805d1..b1e82aac63 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisDeletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisDeletedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public final class FinalSeminarThesisDeletedEvent { + private final FinalSeminar finalSeminar; public FinalSeminarThesisDeletedEvent(final FinalSeminar finalSeminar) { diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisUploadedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisUploadedEvent.java index 264ba1c06f..bfc74f6d8e 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisUploadedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarThesisUploadedEvent.java @@ -3,11 +3,12 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.project.Project; public final class FinalSeminarThesisUploadedEvent { + private final FinalSeminar seminar; public FinalSeminarThesisUploadedEvent(FinalSeminar seminar) { this.seminar = seminar; - } + } public FinalSeminar getFinalSeminar() { return seminar; diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadController.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadController.java index 4b20e0decc..29137fa8fc 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadController.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadController.java @@ -3,15 +3,13 @@ package se.su.dsv.scipro.finalseminar; import se.su.dsv.scipro.file.FileUpload; public interface FinalSeminarUploadController { - enum SeminarDocumentUpload { SUCCESS, ERROR_MUST_BE_PDF, - ERROR_UPLOADER_MUST_BE_AUTHOR + ERROR_UPLOADER_MUST_BE_AUTHOR, } - SeminarDocumentUpload storeSeminarDocument( - FileUpload fileUpload, - FinalSeminar seminar); + + SeminarDocumentUpload storeSeminarDocument(FileUpload fileUpload, FinalSeminar seminar); SeminarDocumentUpload replaceSeminarDocument(FinalSeminar finalSeminar, FileUpload fileUpload); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImpl.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImpl.java index 2613d77c32..abd46d339a 100755 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImpl.java @@ -1,7 +1,9 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.file.*; @@ -10,9 +12,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Date; - public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadController { private static final Logger LOGGER = LoggerFactory.getLogger(FinalSeminarUploadControllerImpl.class); @@ -25,15 +24,16 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr private final PlagiarismControl plagiarismControl; private final FinalSeminarSettingsService finalSeminarSettingsService; - @Inject + @Inject public FinalSeminarUploadControllerImpl( - ProjectService projectService, - FileService fileDescriptionService, - FinalSeminarSettingsService finalSeminarSettingsService, - FinalSeminarService finalSeminarService, - EventBus eventBus, ProjectFileService projectFileService, - final PlagiarismControl plagiarismControl) - { + ProjectService projectService, + FileService fileDescriptionService, + FinalSeminarSettingsService finalSeminarSettingsService, + FinalSeminarService finalSeminarService, + EventBus eventBus, + ProjectFileService projectFileService, + final PlagiarismControl plagiarismControl + ) { this.projectService = projectService; this.fileDescriptionService = fileDescriptionService; this.finalSeminarSettingsService = finalSeminarSettingsService; @@ -47,7 +47,7 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr @Transactional public SeminarDocumentUpload storeSeminarDocument(FileUpload fileUpload, FinalSeminar seminar) { seminar = finalSeminarService.findOne(seminar.getId()); - if (seminar.getDocument() != null){ + if (seminar.getDocument() != null) { throw new IllegalStateException("A file has already been uploaded"); } return storeAndSetSeminarDocument(seminar, fileUpload); @@ -63,7 +63,10 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr return storeAndSetSeminarDocument(finalSeminar, fileUpload); } - private SeminarDocumentUpload storeAndSetSeminarDocument(final FinalSeminar finalSeminar, final FileUpload fileUpload) { + private SeminarDocumentUpload storeAndSetSeminarDocument( + final FinalSeminar finalSeminar, + final FileUpload fileUpload + ) { if (!assertParticipant(fileUpload.getUploader(), finalSeminar)) { return SeminarDocumentUpload.ERROR_UPLOADER_MUST_BE_AUTHOR; } @@ -73,7 +76,11 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr final FileReference newDocument = fileDescriptionService.storeFile(fileUpload); setSeminarDocument(newDocument, finalSeminar); - projectFileService.promote(newDocument.getFileDescription(), finalSeminar.getProject(), FileSource.FINAL_SEMINAR); + projectFileService.promote( + newDocument.getFileDescription(), + finalSeminar.getProject(), + FileSource.FINAL_SEMINAR + ); return SeminarDocumentUpload.SUCCESS; } @@ -84,7 +91,7 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr seminar = finalSeminarService.save(seminar); plagiarismControl.submit(fileReference.getFileDescription(), seminar.getProject().getHeadSupervisor()); - eventBus.post(new FinalSeminarThesisUploadedEvent(seminar)); + eventBus.post(new FinalSeminarThesisUploadedEvent(seminar)); } private boolean assertParticipant(final User uploader, final FinalSeminar seminar) { @@ -102,10 +109,15 @@ public class FinalSeminarUploadControllerImpl implements FinalSeminarUploadContr private boolean assertMimeType(final String type) { final boolean requirePdf = finalSeminarSettingsService.getInstance().getThesisMustBePDF(); if (type == null || (requirePdf && !type.equals("application/pdf"))) { - LOGGER.debug("Faulty file type uploaded. Expected " + (requirePdf ? "\"application/pdf\"" : "non null") + ", was: \"" + type + "\""); + LOGGER.debug( + "Faulty file type uploaded. Expected " + + (requirePdf ? "\"application/pdf\"" : "non null") + + ", was: \"" + + type + + "\"" + ); return false; } return true; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/MovingError.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/MovingError.java index 13d10992e3..13d12ef606 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/MovingError.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/MovingError.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.finalseminar; -public sealed interface MovingError extends SchedulingError permits NonWorkDay, NotEnoughWorkDays { -} +public sealed interface MovingError extends SchedulingError permits NonWorkDay, NotEnoughWorkDays {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/NonWorkDay.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/NonWorkDay.java index 681940c54a..0a9a26f0ec 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/NonWorkDay.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/NonWorkDay.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.finalseminar; import java.time.LocalDate; -public record NonWorkDay(LocalDate date) implements MovingError { -} +public record NonWorkDay(LocalDate date) implements MovingError {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/NotEnoughWorkDays.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/NotEnoughWorkDays.java index eecbb0dac9..f076226088 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/NotEnoughWorkDays.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/NotEnoughWorkDays.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.finalseminar; import java.time.LocalDate; -public record NotEnoughWorkDays(LocalDate scheduling, LocalDate earliest) implements MovingError { -} +public record NotEnoughWorkDays(LocalDate scheduling, LocalDate earliest) implements MovingError {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/OpposeError.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/OpposeError.java index 536a26e3ab..6e9f493dc6 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/OpposeError.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/OpposeError.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; public enum OpposeError { - ALREADY_OPPONENT, ALREADY_PARTICIPANT, IS_AUTHOR -} \ No newline at end of file + ALREADY_OPPONENT, + ALREADY_PARTICIPANT, + IS_AUTHOR, +} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionApprovedEvent.java index fccfec60f6..672290a46b 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionApprovedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class OppositionApprovedEvent extends AbstractOppositionEvent { + public OppositionApprovedEvent(FinalSeminarOpposition opposition) { super(opposition); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionFailedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionFailedEvent.java index 3c87e07f8d..0221041fff 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionFailedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionFailedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class OppositionFailedEvent extends AbstractOppositionEvent { + public OppositionFailedEvent(FinalSeminarOpposition opposition) { super(opposition); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionRegistrationErrorStatus.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionRegistrationErrorStatus.java index dccc43fa3f..d618e97152 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionRegistrationErrorStatus.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/OppositionRegistrationErrorStatus.java @@ -4,126 +4,142 @@ import java.time.Instant; import java.util.function.Function; public abstract class OppositionRegistrationErrorStatus { - OppositionRegistrationErrorStatus() { - } + + OppositionRegistrationErrorStatus() {} public abstract A fold( - Function a, - Function b, - Function c, - Function d, - Function e, - Function f, - Function g, - Function h); + Function a, + Function b, + Function c, + Function d, + Function e, + Function f, + Function g, + Function h + ); } final class UngradedOpposition extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return a.apply(this); } } final class AlreadyOpposed extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return g.apply(this); } } final class FinalSeminarCancelled extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return b.apply(this); } } final class AlreadyParticipating extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return c.apply(this); } } final class AlreadyHappened extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return d.apply(this); } } final class TooManyOpponents extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return e.apply(this); } } final class ManualOpponents extends OppositionRegistrationErrorStatus { + @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return h.apply(this); } } final class PriorityForSeminarAuthors extends OppositionRegistrationErrorStatus { + private final int priorityDays; private final Instant priorityEnd; @@ -142,14 +158,15 @@ final class PriorityForSeminarAuthors extends OppositionRegistrationErrorStatus @Override public A fold( - final Function a, - final Function b, - final Function c, - final Function d, - final Function e, - final Function f, - final Function g, - final Function h) { + final Function a, + final Function b, + final Function c, + final Function d, + final Function e, + final Function f, + final Function g, + final Function h + ) { return f.apply(this); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateError.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateError.java index 1f091ee514..fc86f3e161 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateError.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateError.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; public enum ParticipateError { - ALREADY_OPPONENT, ALREADY_PARTICIPANT, IS_AUTHOR -} \ No newline at end of file + ALREADY_OPPONENT, + ALREADY_PARTICIPANT, + IS_AUTHOR, +} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationApprovedEvent.java index a9f726f085..51f52c158c 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationApprovedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class ParticipationApprovedEvent extends AbstractParticipationEvent { + public ParticipationApprovedEvent(FinalSeminarActiveParticipation participation) { super(participation); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationFailedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationFailedEvent.java index c637befc2e..dfbe6c3835 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationFailedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/ParticipationFailedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class ParticipationFailedEvent extends AbstractParticipationEvent { + public ParticipationFailedEvent(FinalSeminarActiveParticipation participation) { super(participation); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentApprovedEvent.java index 6f8f446160..121106969f 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentApprovedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class RespondentApprovedEvent extends AbstractRespondentEvent { + public RespondentApprovedEvent(FinalSeminarRespondent respondent) { super(respondent); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentFailedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentFailedEvent.java index 23d3324a34..508a5ec704 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentFailedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/RespondentFailedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.finalseminar; public class RespondentFailedEvent extends AbstractRespondentEvent { + public RespondentFailedEvent(FinalSeminarRespondent respondent) { super(respondent); } diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/RoughDraftNotApproved.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/RoughDraftNotApproved.java index 5758fa06f6..9fe99ae944 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/RoughDraftNotApproved.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/RoughDraftNotApproved.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.finalseminar; -public record RoughDraftNotApproved() implements SchedulingError { -} +public record RoughDraftNotApproved() implements SchedulingError {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalseminar/SchedulingError.java b/core/src/main/java/se/su/dsv/scipro/finalseminar/SchedulingError.java index 78949d98ba..f15f1aa011 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalseminar/SchedulingError.java +++ b/core/src/main/java/se/su/dsv/scipro/finalseminar/SchedulingError.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.finalseminar; -public sealed interface SchedulingError permits MovingError, RoughDraftNotApproved { -} +public sealed interface SchedulingError permits MovingError, RoughDraftNotApproved {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesis.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesis.java index 818bfc2b0c..ca4ddada7a 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesis.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesis.java @@ -2,27 +2,25 @@ package se.su.dsv.scipro.finalthesis; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; import jakarta.persistence.Table; - import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity @Table(name = "final_thesis") @@ -89,8 +87,6 @@ public class FinalThesis extends DomainObject { this.swedishTitle = clean(this.swedishTitle); } - - // ---------------------------------------------------------------------------------- // Properties (Getters and Setters) // ---------------------------------------------------------------------------------- @@ -191,9 +187,11 @@ public class FinalThesis extends DomainObject { if (o == this) return true; if (!(o instanceof FinalThesis)) return false; final FinalThesis other = (FinalThesis) o; - return other.canEqual(this) - && Objects.equals(this.getDocument(), other.getDocument()) - && Objects.equals(this.getProject(), other.getProject()); + return ( + other.canEqual(this) && + Objects.equals(this.getDocument(), other.getDocument()) && + Objects.equals(this.getProject(), other.getProject()) + ); } @Override @@ -203,7 +201,27 @@ public class FinalThesis extends DomainObject { @Override public String toString() { - return "FinalThesis(id=" + this.getId() + ", fileDescription=" + this.getDocument() + ", textMatchingDocument=" + this.getTextMatchingDocument() + ", project=" + this.getProject() + ", status=" + this.getStatus() + ", dateApproved=" + this.getDateApproved() + ", dateRejected=" + this.getDateRejected() + ", englishTitle=" + this.getEnglishTitle() + ", swedishTitle=" + this.getSwedishTitle() + ")"; + return ( + "FinalThesis(id=" + + this.getId() + + ", fileDescription=" + + this.getDocument() + + ", textMatchingDocument=" + + this.getTextMatchingDocument() + + ", project=" + + this.getProject() + + ", status=" + + this.getStatus() + + ", dateApproved=" + + this.getDateApproved() + + ", dateRejected=" + + this.getDateRejected() + + ", englishTitle=" + + this.getEnglishTitle() + + ", swedishTitle=" + + this.getSwedishTitle() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -214,10 +232,10 @@ public class FinalThesis extends DomainObject { return null; } return str - .replaceAll("\\p{C}", "") - // replace multiple consecutive horizontal whitespaces with only one - .replaceAll("\\h\\h+", " ") - .trim(); + .replaceAll("\\p{C}", "") + // replace multiple consecutive horizontal whitespaces with only one + .replaceAll("\\h\\h+", " ") + .trim(); } protected boolean canEqual(final Object other) { @@ -237,6 +255,8 @@ public class FinalThesis extends DomainObject { // Nested types // ---------------------------------------------------------------------------------- public enum Status { - APPROVED, REJECTED, NO_DECISION + APPROVED, + REJECTED, + NO_DECISION, } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisApprovedEvent.java index 365aed511d..18379cde59 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisApprovedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.finalthesis; import se.su.dsv.scipro.project.Project; public final class FinalThesisApprovedEvent { + private final Project project; public FinalThesisApprovedEvent(final Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisRejectedEvent.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisRejectedEvent.java index bcc1d66141..521edd3aaa 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisRejectedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisRejectedEvent.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.finalthesis; import se.su.dsv.scipro.project.Project; -public record FinalThesisRejectedEvent(Project project) { -} +public record FinalThesisRejectedEvent(Project project) {} diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisService.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisService.java index 6407fb26c1..67d7a4da96 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisService.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisService.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.finalthesis; +import java.io.Serializable; +import java.util.*; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.ProjectFileUpload; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.FilteredService; import se.su.dsv.scipro.system.GenericService; -import java.io.Serializable; -import java.util.*; - -public interface FinalThesisService extends GenericService, - FilteredService { +public interface FinalThesisService + extends GenericService, FilteredService { FinalThesis upload(ProjectFileUpload fileUpload, String englishTitle, String swedishTitle); boolean hasFinalThesis(Project project); @@ -30,6 +29,7 @@ public interface FinalThesisService extends GenericService, void removeApproval(Project project); class Filter implements Serializable { + private FinalThesis.Status status; public FinalThesis.Status getStatus() { diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImpl.java index f505a3d189..6e97f34e2f 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImpl.java @@ -1,11 +1,14 @@ package se.su.dsv.scipro.finalthesis; import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import jakarta.inject.Provider; import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.Pageable; +import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; @@ -21,14 +24,11 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.report.GradingReportService; import se.su.dsv.scipro.report.SupervisorGradingReport; import se.su.dsv.scipro.system.AbstractServiceImpl; - -import jakarta.inject.Inject; -import jakarta.inject.Named; -import jakarta.inject.Provider; -import java.util.*; +import se.su.dsv.scipro.system.Pageable; @Named public class FinalThesisServiceImpl extends AbstractServiceImpl implements FinalThesisService { + protected final NotificationController notificationController; protected final ProjectFileService projectFileService; private final FileService fileService; @@ -38,14 +38,14 @@ public class FinalThesisServiceImpl extends AbstractServiceImpl em, - NotificationController notificationController, - ProjectFileService projectFileService, - final FileService fileService, - final EventBus eventBus, - final PlagiarismControl plagiarismControl, - GradingReportService gradingReportService) - { + Provider em, + NotificationController notificationController, + ProjectFileService projectFileService, + final FileService fileService, + final EventBus eventBus, + final PlagiarismControl plagiarismControl, + GradingReportService gradingReportService + ) { super(em, FinalThesis.class, QFinalThesis.finalThesis); this.notificationController = notificationController; this.projectFileService = projectFileService; @@ -66,7 +66,11 @@ public class FinalThesisServiceImpl extends AbstractServiceImpl available) {} + enum Level { DO_NOT_PUBLISH, PUBLISH_INTERNALLY, - PUBLISH + PUBLISH, } } diff --git a/core/src/main/java/se/su/dsv/scipro/finalthesis/PublishingConsentUnavailable.java b/core/src/main/java/se/su/dsv/scipro/finalthesis/PublishingConsentUnavailable.java index f1d428e4ec..0925772db4 100644 --- a/core/src/main/java/se/su/dsv/scipro/finalthesis/PublishingConsentUnavailable.java +++ b/core/src/main/java/se/su/dsv/scipro/finalthesis/PublishingConsentUnavailable.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.finalthesis; +import java.util.List; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.List; - public class PublishingConsentUnavailable implements PublishingConsentService { + @Override public boolean setPublishingConsent(Project project, User author, Level publishingConsent) { return false; diff --git a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorker.java b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorker.java index 0192c3af58..e6aa513ad1 100644 --- a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorker.java @@ -1,24 +1,24 @@ package se.su.dsv.scipro.firstmeeting; +import jakarta.inject.*; import java.time.Clock; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; -import jakarta.inject.*; - -import se.su.dsv.scipro.match.Idea.Status; -import se.su.dsv.scipro.match.IdeaService.Filter; -import se.su.dsv.scipro.match.Idea; -import se.su.dsv.scipro.match.IdeaService; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.mail.*; +import se.su.dsv.scipro.match.Idea; +import se.su.dsv.scipro.match.Idea.Status; +import se.su.dsv.scipro.match.IdeaService; +import se.su.dsv.scipro.match.IdeaService.Filter; import se.su.dsv.scipro.misc.DaysService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.workerthreads.AbstractWorker; import se.su.dsv.scipro.workerthreads.Scheduler; public class FirstMeetingReminderWorker extends AbstractWorker { + private static final Filter filter; static { @@ -47,12 +47,12 @@ public class FirstMeetingReminderWorker extends AbstractWorker { @Inject public FirstMeetingReminderWorker( - final IdeaService ideaService, - final DaysService daysService, - final MailEventService mailEventService, - final GeneralSystemSettingsService generalSystemSettingsService, - final Clock clock) - { + final IdeaService ideaService, + final DaysService daysService, + final MailEventService mailEventService, + final GeneralSystemSettingsService generalSystemSettingsService, + final Clock clock + ) { this.ideaService = ideaService; this.daysService = daysService; this.mailEventService = mailEventService; @@ -67,24 +67,28 @@ public class FirstMeetingReminderWorker extends AbstractWorker { final LocalDate today = LocalDate.now(clock); - final Map> needReminding = ideas.stream() - .filter(idea -> needReminding(idea, today)) - .collect(Collectors.groupingBy(idea -> idea.getMatch().getSupervisor())); - final Map> needRemindingNow = ideasToday.stream() - .filter(idea -> needRemindingToday(idea, today)) - .collect(Collectors.groupingBy(idea -> idea.getMatch().getSupervisor())); + final Map> needReminding = ideas + .stream() + .filter(idea -> needReminding(idea, today)) + .collect(Collectors.groupingBy(idea -> idea.getMatch().getSupervisor())); + final Map> needRemindingNow = ideasToday + .stream() + .filter(idea -> needRemindingToday(idea, today)) + .collect(Collectors.groupingBy(idea -> idea.getMatch().getSupervisor())); final String baseURL = generalSystemSettingsService.getGeneralSystemSettingsInstance().getSciproURL(); beginTransaction(); - needReminding.entrySet() - .stream() - .map(entry -> generateReminder(baseURL, entry.getKey(), entry.getValue())) - .forEach(mailEventService::save); - needRemindingNow.entrySet() - .stream() - .map(entry -> generateReminderToday(entry.getKey(), entry.getValue())) - .forEach(mailEventService::save); + needReminding + .entrySet() + .stream() + .map(entry -> generateReminder(baseURL, entry.getKey(), entry.getValue())) + .forEach(mailEventService::save); + needRemindingNow + .entrySet() + .stream() + .map(entry -> generateReminderToday(entry.getKey(), entry.getValue())) + .forEach(mailEventService::save); commitTransaction(); } @@ -102,8 +106,8 @@ public class FirstMeetingReminderWorker extends AbstractWorker { private Set calculateReminderDaysBasedOnWorkDays(LocalDate startDate) { return daysAheadToRemind() - .mapToObj(daysAhead -> daysService.workDaysAhead(startDate, daysAhead)) - .collect(Collectors.toSet()); + .mapToObj(daysAhead -> daysService.workDaysAhead(startDate, daysAhead)) + .collect(Collectors.toSet()); } private boolean containsSameDay(final Set datesToRemind, final LocalDate today) { @@ -118,32 +122,48 @@ public class FirstMeetingReminderWorker extends AbstractWorker { MailEvent reminder = new MailEvent(); reminder.getRecipients().add(supervisor); reminder.setSubject("A friendly reminder to book First meeting(s)"); - String lines = ideas.stream().map(idea -> - "-Course start: " + idea.getCourseStartDate() + '\n' + - "-Deadline: " + deadline(idea) + '\n' + - "-Authors: " + idea.getAuthorNames() + '\n' + - "-Supervisor: " + supervisor.getFullName() + '\n' + - "-Title: " + idea.getTitle() + '\n' + - '\n') - .collect(Collectors.joining()); + String lines = ideas + .stream() + .map( + idea -> + "-Course start: " + + idea.getCourseStartDate() + + '\n' + + "-Deadline: " + + deadline(idea) + + '\n' + + "-Authors: " + + idea.getAuthorNames() + + '\n' + + "-Supervisor: " + + supervisor.getFullName() + + '\n' + + "-Title: " + + idea.getTitle() + + '\n' + + '\n' + ) + .collect(Collectors.joining()); reminder.setMessageBody( - "According to the information in SciPro, you haven't booked a First meeting with your thesis student(s) yet.\n" + - "\n" + - "Please book a first meeting in SciPro even if you have already agreed to a meeting with the students in any other way.\n" + - "\n" + - "To book a meeting, please see the instructions below:\n" + - "\n" + - "First meeting with the student(s)\n" + - " - A meeting is to be held within 3 days after the course start.\n" + - " - The meeting is scheduled by the supervisor before the course starts.\n" + - " - The meeting is scheduled under the “Ideas” tab (an email is automatically sent to the student(s))\n" + - " - To go directly to the \"Ideas\" tab go to " + baseUrl + "supervisor/projectideas\n" + - " - If you have already met the student(s), please create a First meeting after the course start anyway.\n" + - "\n" + - "The following project(s) need a First meeting:\n" + - lines + - "/Thesis support" + "According to the information in SciPro, you haven't booked a First meeting with your thesis student(s) yet.\n" + + "\n" + + "Please book a first meeting in SciPro even if you have already agreed to a meeting with the students in any other way.\n" + + "\n" + + "To book a meeting, please see the instructions below:\n" + + "\n" + + "First meeting with the student(s)\n" + + " - A meeting is to be held within 3 days after the course start.\n" + + " - The meeting is scheduled by the supervisor before the course starts.\n" + + " - The meeting is scheduled under the “Ideas” tab (an email is automatically sent to the student(s))\n" + + " - To go directly to the \"Ideas\" tab go to " + + baseUrl + + "supervisor/projectideas\n" + + " - If you have already met the student(s), please create a First meeting after the course start anyway.\n" + + "\n" + + "The following project(s) need a First meeting:\n" + + lines + + "/Thesis support" ); return reminder; } @@ -151,33 +171,52 @@ public class FirstMeetingReminderWorker extends AbstractWorker { private MailEvent generateReminderToday(User supervisor, List ideas) { MailEvent reminder = new MailEvent(); reminder.getRecipients().add(supervisor); - Optional gru = Optional.ofNullable(supervisor.getUnit()).flatMap(unit -> Optional.ofNullable(unit.getMatchResponsible())).map(EmailRecipient::new); + Optional gru = Optional.ofNullable(supervisor.getUnit()) + .flatMap(unit -> Optional.ofNullable(unit.getMatchResponsible())) + .map(EmailRecipient::new); gru.ifPresent(gruEmail -> reminder.addRecipients(Set.of(gruEmail))); reminder.setSubject("A friendly reminder to book First meeting without further delay"); - String lines = ideas.stream().map(idea -> - "-Course start: " + idea.getCourseStartDate() + '\n' + - "-Authors: " + idea.getAuthorNames() + '\n' + - "-Supervisor: " + supervisor.getFullName() + '\n' + - "-Title: " + idea.getTitle() + '\n' + - '\n') - .collect(Collectors.joining()); + String lines = ideas + .stream() + .map( + idea -> + "-Course start: " + + idea.getCourseStartDate() + + '\n' + + "-Authors: " + + idea.getAuthorNames() + + '\n' + + "-Supervisor: " + + supervisor.getFullName() + + '\n' + + "-Title: " + + idea.getTitle() + + '\n' + + '\n' + ) + .collect(Collectors.joining()); reminder.setMessageBody( - "The thesis course has now started, and it is high time you booked a meeting with your student(s) if you haven't done that.\n" + - "\n" + - "It is recommended that you use the tab “Forum” to interact with the student(s) about when and where to have the \"First meeting\".\n" + - "\n" + - "Automatic e-mail(s) will then be sent out from SciPro to alert the student(s) about the meeting.\n" + - "\n" + - "The following project(s) need a First meeting:\n" + - lines + - "/Thesis support"); + "The thesis course has now started, and it is high time you booked a meeting with your student(s) if you haven't done that.\n" + + "\n" + + "It is recommended that you use the tab “Forum” to interact with the student(s) about when and where to have the \"First meeting\".\n" + + "\n" + + "Automatic e-mail(s) will then be sent out from SciPro to alert the student(s) about the meeting.\n" + + "\n" + + "The following project(s) need a First meeting:\n" + + lines + + "/Thesis support" + ); return reminder; } public static class FirstMeetingReminderWorkerSchedule { + @Inject - public FirstMeetingReminderWorkerSchedule(Scheduler scheduler, Provider firstMeetingReminderWorker) { + public FirstMeetingReminderWorkerSchedule( + Scheduler scheduler, + Provider firstMeetingReminderWorker + ) { scheduler.schedule("First meeting reminders").runBy(firstMeetingReminderWorker).dailyAt(11, 30); } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingService.java b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingService.java index 0debff0646..b481a312bd 100644 --- a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingService.java +++ b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingService.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.firstmeeting; -import se.su.dsv.scipro.project.Project; - import java.util.Date; import java.util.Optional; +import se.su.dsv.scipro.project.Project; public interface FirstMeetingService { Optional findByProject(Project project); diff --git a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingServiceImpl.java index 1ab1e575a8..6b22d71c46 100644 --- a/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingServiceImpl.java @@ -1,18 +1,20 @@ package se.su.dsv.scipro.firstmeeting; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; +import java.util.Date; +import java.util.Optional; import se.su.dsv.scipro.activityplan.Activity; import se.su.dsv.scipro.activityplan.ActivityPlanFacade; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.AbstractServiceImpl; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.Date; -import java.util.Optional; +public class FirstMeetingServiceImpl + extends AbstractServiceImpl + implements FirstMeetingService { -public class FirstMeetingServiceImpl extends AbstractServiceImpl implements FirstMeetingService { private final ActivityPlanFacade activityPlanFacade; @Inject @@ -23,18 +25,24 @@ public class FirstMeetingServiceImpl extends AbstractServiceImpl findByProject(final Project project) { - return Optional.ofNullable(findOne(QProjectFirstMeeting.projectFirstMeeting.activity.activityPlan.project.eq(project))); + return Optional.ofNullable( + findOne(QProjectFirstMeeting.projectFirstMeeting.activity.activityPlan.project.eq(project)) + ); } @Override @Transactional - public ProjectFirstMeeting schedule(final Project project, final Date date, final String room, final String description) { + public ProjectFirstMeeting schedule( + final Project project, + final Date date, + final String room, + final String description + ) { final Optional optFirstMeeting = findByProject(project); - final ProjectFirstMeeting firstMeeting = optFirstMeeting - .orElseGet(ProjectFirstMeeting::new); + final ProjectFirstMeeting firstMeeting = optFirstMeeting.orElseGet(ProjectFirstMeeting::new); final Activity activity = optFirstMeeting - .map(ProjectFirstMeeting::getActivity) - .orElseGet(() -> createNewActivity(project)); + .map(ProjectFirstMeeting::getActivity) + .orElseGet(() -> createNewActivity(project)); final Activity updated = updateActivity(activity, date, description); return updateFirstMeeting(firstMeeting, room, updated); @@ -53,7 +61,11 @@ public class FirstMeetingServiceImpl extends AbstractServiceImpl, QueryDslPredicateExecutor { -} +package se.su.dsv.scipro.forum; + +import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; + +public interface AbstractThreadRepository + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/forum/AbstractThreadRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/AbstractThreadRepositoryImpl.java index cc1db0a920..a3e419470d 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/AbstractThreadRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/AbstractThreadRepositoryImpl.java @@ -1,17 +1,16 @@ -package se.su.dsv.scipro.forum; - -import se.su.dsv.scipro.forum.dataobjects.ForumThread; -import se.su.dsv.scipro.forum.dataobjects.QForumThread; -import se.su.dsv.scipro.system.GenericRepo; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; - -public class AbstractThreadRepositoryImpl extends GenericRepo implements AbstractThreadRepository { - - @Inject - public AbstractThreadRepositoryImpl(Provider em) { - super(em, ForumThread.class, QForumThread.forumThread); - } -} +package se.su.dsv.scipro.forum; + +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.forum.dataobjects.QForumThread; +import se.su.dsv.scipro.system.GenericRepo; + +public class AbstractThreadRepositoryImpl extends GenericRepo implements AbstractThreadRepository { + + @Inject + public AbstractThreadRepositoryImpl(Provider em) { + super(em, ForumThread.class, QForumThread.forumThread); + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/forum/Attachment.java b/core/src/main/java/se/su/dsv/scipro/forum/Attachment.java index 6962f880dc..01bd104187 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/Attachment.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/Attachment.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.forum; +import java.util.*; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.file.FileUpload; -import java.util.*; - public abstract class Attachment { + // package-private Attachment() {} @@ -23,6 +23,7 @@ public abstract class Attachment { abstract FileReference createReference(final FileService fileService); private static final class Existing extends Attachment { + private final FileDescription existing; public Existing(final FileDescription existing) { @@ -49,6 +50,7 @@ public abstract class Attachment { } private static final class NewUpload extends Attachment { + private final FileUpload newUpload; public NewUpload(final FileUpload newUpload) { diff --git a/core/src/main/java/se/su/dsv/scipro/forum/BasicForumService.java b/core/src/main/java/se/su/dsv/scipro/forum/BasicForumService.java index a6cff8bdae..4bccf27413 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/BasicForumService.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/BasicForumService.java @@ -1,14 +1,12 @@ package se.su.dsv.scipro.forum; +import java.io.Serializable; +import java.util.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.system.User; -import java.io.Serializable; -import java.util.*; - public interface BasicForumService extends Serializable { - ForumPost createReply(ForumThread forumThread, User poster, String content, Set attachments); boolean setRead(User user, ForumPost post, boolean read); @@ -22,5 +20,4 @@ public interface BasicForumService extends Serializable { List getPosts(ForumThread forumThread); ForumThread createThread(String subject); - } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/BasicForumServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/BasicForumServiceImpl.java index 0dae3383bb..8da3bb70d6 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/BasicForumServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/BasicForumServiceImpl.java @@ -1,7 +1,10 @@ package se.su.dsv.scipro.forum; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.*; +import java.util.stream.Collectors; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.forum.dataobjects.ForumPost; @@ -9,10 +12,6 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPostReadState; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; -import java.util.stream.Collectors; - public class BasicForumServiceImpl implements BasicForumService { private final AbstractThreadRepository threadRepository; @@ -23,11 +22,12 @@ public class BasicForumServiceImpl implements BasicForumService { @Inject public BasicForumServiceImpl( - final ForumPostRepository postRepository, - final ForumPostReadStateRepository readStateRepository, - AbstractThreadRepository threadRepository, - final FileService fileService, - final EventBus eventBus) { + final ForumPostRepository postRepository, + final ForumPostReadStateRepository readStateRepository, + AbstractThreadRepository threadRepository, + final FileService fileService, + final EventBus eventBus + ) { this.postRepository = postRepository; this.readStateRepository = readStateRepository; this.threadRepository = threadRepository; @@ -35,7 +35,6 @@ public class BasicForumServiceImpl implements BasicForumService { this.eventBus = eventBus; } - @Override @Transactional public boolean setRead(User user, ForumPost post, boolean read) { @@ -97,9 +96,10 @@ public class BasicForumServiceImpl implements BasicForumService { } private ForumPost createForumPost(User user, String content, ForumThread forumThread, Set fileUploads) { - final HashSet storedAttachments = fileUploads.stream() - .map(attachment -> attachment.createReference(fileService)) - .collect(Collectors.toCollection(HashSet::new)); // Need to use an explicit collection since Hibernate likes to mutate the collection + final HashSet storedAttachments = fileUploads + .stream() + .map(attachment -> attachment.createReference(fileService)) + .collect(Collectors.toCollection(HashSet::new)); // Need to use an explicit collection since Hibernate likes to mutate the collection ForumPost post = new ForumPost(); post.setPostedBy(user); post.setContent(content); @@ -111,7 +111,12 @@ public class BasicForumServiceImpl implements BasicForumService { @Override @Transactional - public ForumPost createReply(final ForumThread forumThread, final User user, final String content, final Set attachments) { + public ForumPost createReply( + final ForumThread forumThread, + final User user, + final String content, + final Set attachments + ) { ForumPost post = createForumPost(user, content, forumThread, attachments); post = postRepository.save(post); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadEvent.java b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadEvent.java index 816c477c38..99ab0748dd 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadEvent.java @@ -3,5 +3,4 @@ package se.su.dsv.scipro.forum; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.system.User; -public record ForumPostReadEvent(ForumPost post, User user) { -} +public record ForumPostReadEvent(ForumPost post, User user) {} diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepository.java b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepository.java index 00dd52bb7c..ec48e21286 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepository.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.forum; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumPostReadState; import se.su.dsv.scipro.forum.dataobjects.ForumPostReadStateId; import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; import se.su.dsv.scipro.system.User; @Transactional public interface ForumPostReadStateRepository - extends JpaRepository, QueryDslPredicateExecutor { - + extends JpaRepository, QueryDslPredicateExecutor { ForumPostReadState find(User user, ForumPost post); void setThreadRead(User user, ForumThread forumThread, boolean read); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepositoryImpl.java index 862884445c..495b32e11f 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostReadStateRepositoryImpl.java @@ -1,7 +1,12 @@ package se.su.dsv.scipro.forum; -import jakarta.transaction.Transactional; +import static com.querydsl.core.types.dsl.Expressions.allOf; + +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; +import jakarta.transaction.Transactional; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumPostReadState; import se.su.dsv.scipro.forum.dataobjects.ForumPostReadStateId; @@ -10,13 +15,10 @@ import se.su.dsv.scipro.forum.dataobjects.QForumPostReadState; import se.su.dsv.scipro.system.GenericRepo; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; +public class ForumPostReadStateRepositoryImpl + extends GenericRepo + implements ForumPostReadStateRepository { -import static com.querydsl.core.types.dsl.Expressions.allOf; - -public class ForumPostReadStateRepositoryImpl extends GenericRepo implements ForumPostReadStateRepository { @Inject public ForumPostReadStateRepositoryImpl(Provider em) { super(em, ForumPostReadState.class, QForumPostReadState.forumPostReadState); @@ -24,7 +26,12 @@ public class ForumPostReadStateRepositoryImpl extends GenericRepo, QueryDslPredicateExecutor { - List findByThread(ForumThread forumThread); List> latestPost(Project project, int amount); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostRepositoryImpl.java index e4536e7582..207d02c9d5 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ForumPostRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ForumPostRepositoryImpl.java @@ -1,7 +1,12 @@ package se.su.dsv.scipro.forum; +import static com.querydsl.core.types.dsl.Expressions.allOf; + import com.querydsl.jpa.impl.JPAQuery; +import jakarta.inject.Inject; +import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import java.util.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; @@ -12,13 +17,8 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.GenericRepo; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.util.*; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - public class ForumPostRepositoryImpl extends GenericRepo implements ForumPostRepository { + @Inject public ForumPostRepositoryImpl(Provider em) { super(em, ForumPost.class, QForumPost.forumPost); @@ -32,18 +32,16 @@ public class ForumPostRepositoryImpl extends GenericRepo implem @Override public List> latestPost(Project project, int amount) { return new JPAQuery<>(em()) - .select(QProjectThread.projectThread, QForumPost.forumPost) - .from(QProjectThread.projectThread) - .innerJoin(QProjectThread.projectThread.forumThread) - .innerJoin(QForumThread.forumThread.posts, QForumPost.forumPost) - .where(QProjectThread.projectThread.project.eq(project)) - .orderBy(QForumPost.forumPost.dateCreated.desc()) - .limit(amount) - .fetch() - .stream() - .map(tuple -> new Pair<>( - tuple.get(QProjectThread.projectThread), - tuple.get(QForumPost.forumPost))) - .toList(); + .select(QProjectThread.projectThread, QForumPost.forumPost) + .from(QProjectThread.projectThread) + .innerJoin(QProjectThread.projectThread.forumThread) + .innerJoin(QForumThread.forumThread.posts, QForumPost.forumPost) + .where(QProjectThread.projectThread.project.eq(project)) + .orderBy(QForumPost.forumPost.dateCreated.desc()) + .limit(amount) + .fetch() + .stream() + .map(tuple -> new Pair<>(tuple.get(QProjectThread.projectThread), tuple.get(QForumPost.forumPost))) + .toList(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/GroupForumService.java b/core/src/main/java/se/su/dsv/scipro/forum/GroupForumService.java index 7e6e38e992..5d43341f3c 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/GroupForumService.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/GroupForumService.java @@ -1,14 +1,12 @@ package se.su.dsv.scipro.forum; +import java.util.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.system.User; -import java.util.*; - public interface GroupForumService { - GroupThread findOne(long threadId); GroupThread createThread(Group group, User user, String subject, String content, Set fileUploads); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/GroupForumServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/GroupForumServiceImpl.java index 0ba81e0b92..00c48751cd 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/GroupForumServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/GroupForumServiceImpl.java @@ -1,32 +1,32 @@ package se.su.dsv.scipro.forum; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class GroupForumServiceImpl implements GroupForumService { + private final GroupThreadRepository groupThreadRepository; private final BasicForumService basicForumService; private final EventBus eventBus; @Inject public GroupForumServiceImpl( - final GroupThreadRepository groupThreadRepository, - final BasicForumService basicForumService, - final EventBus eventBus) { + final GroupThreadRepository groupThreadRepository, + final BasicForumService basicForumService, + final EventBus eventBus + ) { this.groupThreadRepository = groupThreadRepository; this.basicForumService = basicForumService; this.eventBus = eventBus; } - @Override public GroupThread findOne(long threadId) { return groupThreadRepository.findOne(threadId); @@ -34,7 +34,13 @@ public class GroupForumServiceImpl implements GroupForumService { @Override @Transactional - public GroupThread createThread(Group group, User user, String subject, String content, Set fileUploads) { + public GroupThread createThread( + Group group, + User user, + String subject, + String content, + Set fileUploads + ) { ForumThread forumThread = basicForumService.createThread(subject); GroupThread groupThread = new GroupThread(); groupThread.setGroup(group); @@ -60,7 +66,12 @@ public class GroupForumServiceImpl implements GroupForumService { @Override @Transactional - public ForumPost createReply(final GroupThread groupThread, final User poster, final String content, final Set attachments) { + public ForumPost createReply( + final GroupThread groupThread, + final User poster, + final String content, + final Set attachments + ) { ForumPost reply = basicForumService.createReply(groupThread.getForumThread(), poster, content, attachments); eventBus.post(new NewGroupForumReplyEvent(groupThread, reply)); return reply; diff --git a/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepository.java b/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepository.java index 2c254d5bd2..14469ebe86 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepository.java @@ -1,16 +1,14 @@ package se.su.dsv.scipro.forum; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; +import java.util.List; import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.group.Group; - -import java.util.List; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; @Transactional -public interface GroupThreadRepository extends JpaRepository, QueryDslPredicateExecutor { - +public interface GroupThreadRepository + extends JpaRepository, QueryDslPredicateExecutor { List findByGroup(Group group); - } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepositoryImpl.java index 773f104ba2..8d956453a7 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/GroupThreadRepositoryImpl.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.forum; -import se.su.dsv.scipro.forum.dataobjects.GroupThread; -import se.su.dsv.scipro.forum.dataobjects.QGroupThread; -import se.su.dsv.scipro.group.Group; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.forum.dataobjects.GroupThread; +import se.su.dsv.scipro.forum.dataobjects.QGroupThread; +import se.su.dsv.scipro.group.Group; +import se.su.dsv.scipro.system.GenericRepo; public class GroupThreadRepositoryImpl extends GenericRepo implements GroupThreadRepository { @@ -21,5 +20,4 @@ public class GroupThreadRepositoryImpl extends GenericRepo im public List findByGroup(Group group) { return findAll(QGroupThread.groupThread.group.eq(group)); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/NewGroupForumReplyEvent.java b/core/src/main/java/se/su/dsv/scipro/forum/NewGroupForumReplyEvent.java index 2996a2c6a3..1c71b6ff81 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/NewGroupForumReplyEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/NewGroupForumReplyEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.GroupThread; public class NewGroupForumReplyEvent { + private final GroupThread groupThread; private final ForumPost reply; diff --git a/core/src/main/java/se/su/dsv/scipro/forum/NewProjectForumReplyEvent.java b/core/src/main/java/se/su/dsv/scipro/forum/NewProjectForumReplyEvent.java index 44cd5b7f70..13bd5fa21c 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/NewProjectForumReplyEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/NewProjectForumReplyEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; public class NewProjectForumReplyEvent { + private final ProjectThread projectThread; private final ForumPost reply; diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumService.java b/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumService.java index d3b1c35773..c8f9c3e020 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumService.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumService.java @@ -1,15 +1,13 @@ package se.su.dsv.scipro.forum; +import java.util.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Pair; -import java.util.*; - public interface ProjectForumService { - ProjectThread createThread(Project project, User user, String subject, String content, Set fileUploads); ForumPost createReply(ProjectThread projectThread, User poster, String content, Set attachments); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumServiceImpl.java index 1825a16197..5de733222a 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ProjectForumServiceImpl.java @@ -1,7 +1,9 @@ package se.su.dsv.scipro.forum; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.file.FileSource; import se.su.dsv.scipro.file.ProjectFileService; import se.su.dsv.scipro.forum.dataobjects.ForumPost; @@ -11,10 +13,8 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import java.util.*; - public class ProjectForumServiceImpl implements ProjectForumService { + private final ProjectThreadRepository projectThreadRepository; private final ForumPostRepository postRepository; private final ProjectFileService fileDescriptionService; @@ -23,11 +23,12 @@ public class ProjectForumServiceImpl implements ProjectForumService { @Inject public ProjectForumServiceImpl( - final ProjectThreadRepository projectThreadRepository, - final ForumPostRepository postRepository, - final ProjectFileService fileDescriptionService, - final BasicForumService basicForumService, - final EventBus eventBus) { + final ProjectThreadRepository projectThreadRepository, + final ForumPostRepository postRepository, + final ProjectFileService fileDescriptionService, + final BasicForumService basicForumService, + final EventBus eventBus + ) { this.projectThreadRepository = projectThreadRepository; this.postRepository = postRepository; this.fileDescriptionService = fileDescriptionService; @@ -38,11 +39,12 @@ public class ProjectForumServiceImpl implements ProjectForumService { @Override @Transactional public ProjectThread createThread( - final Project project, - final User user, - final String subject, - final String content, - final Set fileUploads) { + final Project project, + final User user, + final String subject, + final String content, + final Set fileUploads + ) { ProjectThread thread = createThread(project, subject); createThreadReply(thread, user, content, fileUploads); @@ -59,17 +61,33 @@ public class ProjectForumServiceImpl implements ProjectForumService { return projectThreadRepository.save(thread); } - private void createThreadReply(ProjectThread projectThread, final User user, final String content, final Set fileUploads) { + private void createThreadReply( + ProjectThread projectThread, + final User user, + final String content, + final Set fileUploads + ) { createReply(projectThread, user, content, fileUploads); } @Override @Transactional - public ForumPost createReply(final ProjectThread projectThread, final User poster, final String content, final Set attachments) { + public ForumPost createReply( + final ProjectThread projectThread, + final User poster, + final String content, + final Set attachments + ) { ForumPost reply = basicForumService.createReply(projectThread.getForumThread(), poster, content, attachments); - reply.getAttachments() - .forEach(attachment -> - fileDescriptionService.promote(attachment.getFileDescription(), projectThread.getProject(), FileSource.FORUM)); + reply + .getAttachments() + .forEach(attachment -> + fileDescriptionService.promote( + attachment.getFileDescription(), + projectThread.getProject(), + FileSource.FORUM + ) + ); eventBus.post(new NewProjectForumReplyEvent(projectThread, reply)); return reply; } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepository.java b/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepository.java index cbe28506a1..d0d4f27f60 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepository.java @@ -1,16 +1,14 @@ package se.su.dsv.scipro.forum; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; +import java.util.List; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.project.Project; - -import java.util.List; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; @Transactional -public interface ProjectThreadRepository extends JpaRepository, QueryDslPredicateExecutor { - +public interface ProjectThreadRepository + extends JpaRepository, QueryDslPredicateExecutor { List findByProject(Project project); - } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepositoryImpl.java index b278d1d214..f42cbdbe41 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/ProjectThreadRepositoryImpl.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.forum; -import se.su.dsv.scipro.forum.dataobjects.ProjectThread; -import se.su.dsv.scipro.forum.dataobjects.QProjectThread; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.forum.dataobjects.ProjectThread; +import se.su.dsv.scipro.forum.dataobjects.QProjectThread; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.GenericRepo; public class ProjectThreadRepositoryImpl extends GenericRepo implements ProjectThreadRepository { + @Inject public ProjectThreadRepositoryImpl(Provider em) { super(em, ProjectThread.class, QProjectThread.projectThread); @@ -20,5 +20,4 @@ public class ProjectThreadRepositoryImpl extends GenericRepo findByProject(Project project) { return findAll(QProjectThread.projectThread.project.eq(project)); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPost.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPost.java index aff80a655f..4e63d8c019 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPost.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPost.java @@ -1,14 +1,10 @@ package se.su.dsv.scipro.forum.dataobjects; import jakarta.persistence.Basic; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; @@ -16,10 +12,12 @@ import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import java.util.HashSet; import java.util.Objects; import java.util.Set; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "forum_post") @@ -53,9 +51,11 @@ public class ForumPost extends LazyDeletableDomainObject { // JPA-mappings of other tables referencing to this table "forum_post" // ---------------------------------------------------------------------------------- @OneToMany(orphanRemoval = true) - @JoinTable(name = "forum_post_file_reference", - joinColumns = {@JoinColumn(name = "forum_post_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "file_reference_id")}) + @JoinTable( + name = "forum_post_file_reference", + joinColumns = { @JoinColumn(name = "forum_post_id", referencedColumnName = "id") }, + inverseJoinColumns = { @JoinColumn(name = "file_reference_id") } + ) private Set attachments = new HashSet<>(); // ---------------------------------------------------------------------------------- @@ -110,29 +110,42 @@ public class ForumPost extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof ForumPost)) return false; final ForumPost other = (ForumPost) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getContent(), other.getContent()) - && Objects.equals(this.getPostedBy(), other.getPostedBy()) - && Objects.equals(this.getForumThread(), other.getForumThread()) - && Objects.equals(this.getAttachments(), other.getAttachments()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getContent(), other.getContent()) && + Objects.equals(this.getPostedBy(), other.getPostedBy()) && + Objects.equals(this.getForumThread(), other.getForumThread()) && + Objects.equals(this.getAttachments(), other.getAttachments()) + ); } @Override public int hashCode() { return Objects.hash( - this.getId(), - this.getContent(), - this.getPostedBy(), - this.getForumThread(), - this.getAttachments()); + this.getId(), + this.getContent(), + this.getPostedBy(), + this.getForumThread(), + this.getAttachments() + ); } @Override public String toString() { - return "ForumPost(id=" + this.getId() + ", content=" + this.getContent() + - ", postedBy=" + this.getPostedBy() + ", forumThread=" + this.getForumThread() + - ", attachments=" + this.getAttachments() + ")"; + return ( + "ForumPost(id=" + + this.getId() + + ", content=" + + this.getContent() + + ", postedBy=" + + this.getPostedBy() + + ", forumThread=" + + this.getForumThread() + + ", attachments=" + + this.getAttachments() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadState.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadState.java index eff11f8578..21491c6c05 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadState.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadState.java @@ -5,9 +5,8 @@ import jakarta.persistence.Column; import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "forum_post_read_state") @@ -26,8 +25,7 @@ public class ForumPostReadState implements Serializable { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public ForumPostReadState() { - } + public ForumPostReadState() {} public ForumPostReadState(final User user, final ForumPost post) { id = new ForumPostReadStateId(user, post); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadStateId.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadStateId.java index 818fd9ca86..74d177cfc6 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadStateId.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumPostReadStateId.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.forum.dataobjects; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Embeddable; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.system.User; @Embeddable public class ForumPostReadStateId implements Serializable { + @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User user; @@ -18,9 +18,7 @@ public class ForumPostReadStateId implements Serializable { @JoinColumn(name = "forum_post_id", nullable = false) private ForumPost post; - public ForumPostReadStateId() { - - } + public ForumPostReadStateId() {} public ForumPostReadStateId(final User user, final ForumPost post) { this.user = user; @@ -48,9 +46,11 @@ public class ForumPostReadStateId implements Serializable { if (o == this) return true; if (!(o instanceof ForumPostReadStateId)) return false; final ForumPostReadStateId other = (ForumPostReadStateId) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getPost(), other.getPost()); + return ( + other.canEqual(this) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getPost(), other.getPost()) + ); } protected boolean canEqual(final Object other) { @@ -70,6 +70,6 @@ public class ForumPostReadStateId implements Serializable { @Override public String toString() { - return "ForumPostReadStateId(user=" + this.getUser() + ", post=" + this.getPost() + ")"; + return ("ForumPostReadStateId(user=" + this.getUser() + ", post=" + this.getPost() + ")"); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumThread.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumThread.java index aaeaf4849e..1c61c2c563 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumThread.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ForumThread.java @@ -13,12 +13,11 @@ import jakarta.persistence.InheritanceType; import jakarta.persistence.OneToMany; import jakarta.persistence.PostLoad; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "thread") @@ -86,8 +85,7 @@ public class ForumThread extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof ForumThread)) return false; final ForumThread other = (ForumThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -97,7 +95,7 @@ public class ForumThread extends LazyDeletableDomainObject { @Override public String toString() { - return "ForumThread(id=" + this.getId() + ", subject=" + this.getSubject() + ")"; + return ("ForumThread(id=" + this.getId() + ", subject=" + this.getSubject() + ")"); } // ---------------------------------------------------------------------------------- @@ -115,7 +113,7 @@ public class ForumThread extends LazyDeletableDomainObject { return posts.size(); } - public User getCreatedBy(){ + public User getCreatedBy() { return getPosts().get(0).getPostedBy(); } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/GroupThread.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/GroupThread.java index ed7d45f410..699acb911c 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/GroupThread.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/GroupThread.java @@ -9,10 +9,9 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.group.Group; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.group.Group; @Entity @Table(name = "project_group_thread") @@ -40,7 +39,9 @@ public class GroupThread implements Serializable { // ---------------------------------------------------------------------------------- // Properties (Getters and Setters) // ---------------------------------------------------------------------------------- - public Long getId() { return id; } + public Long getId() { + return id; + } public void setId(Long id) { this.id = id; @@ -70,10 +71,12 @@ public class GroupThread implements Serializable { if (o == this) return true; if (!(o instanceof GroupThread)) return false; final GroupThread other = (GroupThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getGroup(), other.getGroup()) - && Objects.equals(this.getForumThread(), other.getForumThread()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getGroup(), other.getGroup()) && + Objects.equals(this.getForumThread(), other.getForumThread()) + ); } @Override @@ -83,8 +86,15 @@ public class GroupThread implements Serializable { @Override public String toString() { - return "GroupThread(id=" + this.getId() + ", group=" + this.getGroup() + ", forumThread=" + - this.getForumThread() + ")"; + return ( + "GroupThread(id=" + + this.getId() + + ", group=" + + this.getGroup() + + ", forumThread=" + + this.getForumThread() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ProjectThread.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ProjectThread.java index ba32a9f14f..56560dce61 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ProjectThread.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ProjectThread.java @@ -8,14 +8,14 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.project.Project; @Entity @Table(name = "project_thread") public class ProjectThread implements Serializable { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -70,10 +70,12 @@ public class ProjectThread implements Serializable { if (o == this) return true; if (!(o instanceof ProjectThread)) return false; final ProjectThread other = (ProjectThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getForumThread(), other.getForumThread()) - && Objects.equals(this.getProject(), other.getProject()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getForumThread(), other.getForumThread()) && + Objects.equals(this.getProject(), other.getProject()) + ); } @Override @@ -83,8 +85,15 @@ public class ProjectThread implements Serializable { @Override public String toString() { - return "ProjectThread(id=" + this.getId() + ", forumThread=" + this.getForumThread() + - ", project=" + this.getProject() + ")"; + return ( + "ProjectThread(id=" + + this.getId() + + ", forumThread=" + + this.getForumThread() + + ", project=" + + this.getProject() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ReviewerThread.java b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ReviewerThread.java index 5cce25c1ca..4ccee72a9d 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ReviewerThread.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/dataobjects/ReviewerThread.java @@ -1,95 +1,103 @@ -package se.su.dsv.scipro.forum.dataobjects; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; - -import java.util.Objects; - -@Entity -@Table(name = "reviewer_thread") -public class ReviewerThread { - - // ---------------------------------------------------------------------------------- - // Basic JPA-mapping - // ---------------------------------------------------------------------------------- - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - // ---------------------------------------------------------------------------------- - // JPA-mappings of foreign keys in this table (mail_event) referencing other - // tables. - // ---------------------------------------------------------------------------------- - @OneToOne - @JoinColumn(name = "project_id", referencedColumnName = "id", unique = true) - private Project project; - - @OneToOne(optional = false) - @JoinColumn(name = "thread_id", referencedColumnName = "id") - private ForumThread forumThread; - - // ---------------------------------------------------------------------------------- - // Properties (Getters and Setters) - // ---------------------------------------------------------------------------------- - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Project getProject() { - return this.project; - } - - public void setProject(Project project) { - this.project = project; - } - - public ForumThread getForumThread() { - return this.forumThread; - } - - public void setForumThread(ForumThread forumThread) { - this.forumThread = forumThread; - } - - // ---------------------------------------------------------------------------------- - // Methods Common To All Objects - // ---------------------------------------------------------------------------------- - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof ReviewerThread)) return false; - final ReviewerThread other = (ReviewerThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getForumThread(), other.getForumThread()) - && Objects.equals(this.getProject(), other.getProject()); - } - - @Override - public int hashCode() { - return Objects.hash(this.getId(), this.getForumThread(), this.getProject()); - } - - @Override - public String toString() { - return "ReviewerThread(id=" + this.getId() + ", forumThread=" + this.getForumThread() + - ", project=" + this.getProject() + ")"; - } - - // ---------------------------------------------------------------------------------- - // Other methods - // ---------------------------------------------------------------------------------- - protected boolean canEqual(final Object other) { - return other instanceof ReviewerThread; - } -} +package se.su.dsv.scipro.forum.dataobjects; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import java.util.Objects; +import se.su.dsv.scipro.project.Project; + +@Entity +@Table(name = "reviewer_thread") +public class ReviewerThread { + + // ---------------------------------------------------------------------------------- + // Basic JPA-mapping + // ---------------------------------------------------------------------------------- + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // ---------------------------------------------------------------------------------- + // JPA-mappings of foreign keys in this table (mail_event) referencing other + // tables. + // ---------------------------------------------------------------------------------- + @OneToOne + @JoinColumn(name = "project_id", referencedColumnName = "id", unique = true) + private Project project; + + @OneToOne(optional = false) + @JoinColumn(name = "thread_id", referencedColumnName = "id") + private ForumThread forumThread; + + // ---------------------------------------------------------------------------------- + // Properties (Getters and Setters) + // ---------------------------------------------------------------------------------- + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public Project getProject() { + return this.project; + } + + public void setProject(Project project) { + this.project = project; + } + + public ForumThread getForumThread() { + return this.forumThread; + } + + public void setForumThread(ForumThread forumThread) { + this.forumThread = forumThread; + } + + // ---------------------------------------------------------------------------------- + // Methods Common To All Objects + // ---------------------------------------------------------------------------------- + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof ReviewerThread)) return false; + final ReviewerThread other = (ReviewerThread) o; + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getForumThread(), other.getForumThread()) && + Objects.equals(this.getProject(), other.getProject()) + ); + } + + @Override + public int hashCode() { + return Objects.hash(this.getId(), this.getForumThread(), this.getProject()); + } + + @Override + public String toString() { + return ( + "ReviewerThread(id=" + + this.getId() + + ", forumThread=" + + this.getForumThread() + + ", project=" + + this.getProject() + + ")" + ); + } + + // ---------------------------------------------------------------------------------- + // Other methods + // ---------------------------------------------------------------------------------- + protected boolean canEqual(final Object other) { + return other instanceof ReviewerThread; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotification.java b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotification.java index fe2bc877e4..1d1422d11e 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotification.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotification.java @@ -7,15 +7,15 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.Table; -import se.su.dsv.scipro.forum.dataobjects.ForumPost; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.forum.dataobjects.ForumPost; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; @Entity @Table(name = "forum_notification") class ForumNotification { + // ---------------------------------------------------------------------------------- // Embedded JPA-mapping // ---------------------------------------------------------------------------------- @@ -39,7 +39,7 @@ class ForumNotification { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected ForumNotification() { } // JPA + protected ForumNotification() {} // JPA ForumNotification(final ForumPost forumPost, final NotificationEvent notificationEvent) { this.forumPost = forumPost; @@ -65,10 +65,12 @@ class ForumNotification { if (o == this) return true; if (!(o instanceof ForumNotification)) return false; final ForumNotification other = (ForumNotification) o; - return other.canEqual(this) - && Objects.equals(this.id, other.id) - && Objects.equals(this.getForumPost(), other.getForumPost()) - && Objects.equals(this.getNotificationEvent(), other.getNotificationEvent()); + return ( + other.canEqual(this) && + Objects.equals(this.id, other.id) && + Objects.equals(this.getForumPost(), other.getForumPost()) && + Objects.equals(this.getNotificationEvent(), other.getNotificationEvent()) + ); } @Override @@ -78,8 +80,15 @@ class ForumNotification { @Override public String toString() { - return "ForumNotification(id=" + this.id + ", forumPost=" + this.getForumPost() + - ", notificationEvent=" + this.getNotificationEvent() + ")"; + return ( + "ForumNotification(id=" + + this.id + + ", forumPost=" + + this.getForumPost() + + ", notificationEvent=" + + this.getNotificationEvent() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -94,6 +103,7 @@ class ForumNotification { // ---------------------------------------------------------------------------------- @Embeddable static class Id implements Serializable { + private Long forumPostId; private Long notificationEventId; @@ -118,9 +128,11 @@ class ForumNotification { if (o == this) return true; if (!(o instanceof Id)) return false; final Id other = (Id) o; - return other.canEqual(this) - && Objects.equals(this.getForumPostId(), other.getForumPostId()) - && Objects.equals(this.getNotificationEventId(), other.getNotificationEventId()); + return ( + other.canEqual(this) && + Objects.equals(this.getForumPostId(), other.getForumPostId()) && + Objects.equals(this.getNotificationEventId(), other.getNotificationEventId()) + ); } protected boolean canEqual(final Object other) { @@ -134,8 +146,13 @@ class ForumNotification { @Override public String toString() { - return "ForumNotification.Id(forumPostId=" + this.getForumPostId() + ", notificationEventId=" + - this.getNotificationEventId() + ")"; + return ( + "ForumNotification.Id(forumPostId=" + + this.getForumPostId() + + ", notificationEventId=" + + this.getNotificationEventId() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepository.java b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepository.java index 4e1f01122a..860504906c 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepository.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.forum.notifications; -import se.su.dsv.scipro.forum.dataobjects.ForumPost; - import java.util.Optional; +import se.su.dsv.scipro.forum.dataobjects.ForumPost; public interface ForumNotificationRepository { Optional findByForumPost(ForumPost forumPost); diff --git a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepositoryImpl.java index 658c936b0f..8f21f81297 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotificationRepositoryImpl.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.forum.notifications; import com.querydsl.jpa.impl.JPAQuery; -import se.su.dsv.scipro.forum.dataobjects.ForumPost; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.forum.dataobjects.ForumPost; public class ForumNotificationRepositoryImpl implements ForumNotificationRepository { + private final Provider entityManagerProvider; @Inject @@ -18,10 +18,12 @@ public class ForumNotificationRepositoryImpl implements ForumNotificationReposit @Override public Optional findByForumPost(final ForumPost forumPost) { - return Optional.ofNullable(new JPAQuery(entityManagerProvider.get()) + return Optional.ofNullable( + new JPAQuery(entityManagerProvider.get()) .from(QForumNotification.forumNotification) .where(QForumNotification.forumNotification.forumPost.eq(forumPost)) - .fetchOne()); + .fetchOne() + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotifications.java b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotifications.java index 5b1ff17920..ecc248828e 100644 --- a/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotifications.java +++ b/core/src/main/java/se/su/dsv/scipro/forum/notifications/ForumNotifications.java @@ -2,34 +2,35 @@ package se.su.dsv.scipro.forum.notifications; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.forum.dataobjects.ForumPost; +import java.util.Set; +import java.util.function.Function; import se.su.dsv.scipro.forum.ForumPostReadEvent; import se.su.dsv.scipro.forum.NewGroupForumReplyEvent; import se.su.dsv.scipro.forum.NewProjectForumReplyEvent; +import se.su.dsv.scipro.forum.dataobjects.ForumPost; +import se.su.dsv.scipro.notifications.NotificationController; +import se.su.dsv.scipro.notifications.NotificationService; import se.su.dsv.scipro.notifications.dataobject.GroupEvent; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectForumEvent; -import se.su.dsv.scipro.notifications.NotificationController; -import se.su.dsv.scipro.notifications.NotificationService; import se.su.dsv.scipro.reviewing.NewReviewerInteractionMessage; -import jakarta.inject.Inject; - -import java.util.Set; -import java.util.function.Function; - public class ForumNotifications { + private final NotificationController notificationController; private final ForumNotificationRepository forumNotificationRepository; private final NotificationService notificationService; @Inject - public ForumNotifications(EventBus eventBus, - NotificationController notificationController, - ForumNotificationRepository forumNotificationRepository, - NotificationService notificationService) { + public ForumNotifications( + EventBus eventBus, + NotificationController notificationController, + ForumNotificationRepository forumNotificationRepository, + NotificationService notificationService + ) { this.notificationController = notificationController; this.forumNotificationRepository = forumNotificationRepository; this.notificationService = notificationService; @@ -42,11 +43,17 @@ public class ForumNotifications { ForumPost post = forumReplyEvent.getReply(); ProjectForumEvent.Event event = post.getForumThread().getPostCount() == 1 - ? ProjectForumEvent.Event.NEW_FORUM_POST - : ProjectForumEvent.Event.NEW_FORUM_POST_COMMENT; + ? ProjectForumEvent.Event.NEW_FORUM_POST + : ProjectForumEvent.Event.NEW_FORUM_POST_COMMENT; sendAndConnect(post, source -> - notificationController.notifyProjectForum(event, source, forumReplyEvent.getProjectThread().getProject(), post.getPostedBy())); + notificationController.notifyProjectForum( + event, + source, + forumReplyEvent.getProjectThread().getProject(), + post.getPostedBy() + ) + ); } @Subscribe @@ -55,11 +62,17 @@ public class ForumNotifications { ForumPost post = forumReplyEvent.getReply(); GroupEvent.Event event = post.getForumThread().getPostCount() == 1 - ? GroupEvent.Event.MESSAGE_THREAD_CREATED - : GroupEvent.Event.MESSAGE_THREAD_REPLY; + ? GroupEvent.Event.MESSAGE_THREAD_CREATED + : GroupEvent.Event.MESSAGE_THREAD_REPLY; sendAndConnect(post, source -> - notificationController.notifyGroup(forumReplyEvent.getGroupThread().getGroup(), event, source, post.getPostedBy())); + notificationController.notifyGroup( + forumReplyEvent.getGroupThread().getGroup(), + event, + source, + post.getPostedBy() + ) + ); } @Subscribe @@ -67,11 +80,19 @@ public class ForumNotifications { public void newReviewerInteractionMessage(NewReviewerInteractionMessage event) { NotificationSource source = new NotificationSource(); source.setMessage(event.getMessage().getContent()); - Set notifications = notificationController.notifyProjectForum(ProjectForumEvent.Event.NEW_REVIEWER_INTERACTION, source, event.getProject()); - notifications.stream().map(Notification::getNotificationEvent).distinct().forEach(notificationEvent -> { - ForumNotification connection = new ForumNotification(event.getMessage(), notificationEvent); - forumNotificationRepository.save(connection); - }); + Set notifications = notificationController.notifyProjectForum( + ProjectForumEvent.Event.NEW_REVIEWER_INTERACTION, + source, + event.getProject() + ); + notifications + .stream() + .map(Notification::getNotificationEvent) + .distinct() + .forEach(notificationEvent -> { + ForumNotification connection = new ForumNotification(event.getMessage(), notificationEvent); + forumNotificationRepository.save(connection); + }); } private void sendAndConnect(ForumPost post, Function> send) { @@ -79,17 +100,21 @@ public class ForumNotifications { notificationSource.setMessage(String.format("Posted by %s\n\n%s", getPostedBy(post), post.getContent())); notificationSource.setAdditionalMessage(post.getSubject()); - send.apply(notificationSource).stream().map(Notification::getNotificationEvent).distinct().forEach(notificationEvent -> { - ForumNotification connection = new ForumNotification(post, notificationEvent); - forumNotificationRepository.save(connection); - }); + send + .apply(notificationSource) + .stream() + .map(Notification::getNotificationEvent) + .distinct() + .forEach(notificationEvent -> { + ForumNotification connection = new ForumNotification(post, notificationEvent); + forumNotificationRepository.save(connection); + }); } private String getPostedBy(ForumPost post) { if (post.getPostedBy() != null) { return post.getPostedBy().getFullName(); - } - else { + } else { return "SciPro"; } } @@ -97,7 +122,10 @@ public class ForumNotifications { @Subscribe @Transactional public void forumPostRead(ForumPostReadEvent forumPostReadEvent) { - forumNotificationRepository.findByForumPost(forumPostReadEvent.post()).ifPresent(connection -> - notificationService.setRead(forumPostReadEvent.user(), connection.getNotificationEvent(), true)); + forumNotificationRepository + .findByForumPost(forumPostReadEvent.post()) + .ifPresent(connection -> + notificationService.setRead(forumPostReadEvent.user(), connection.getNotificationEvent(), true) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/gdpr/Html.java b/core/src/main/java/se/su/dsv/scipro/gdpr/Html.java index 4f0ff2660b..08af4d8d69 100644 --- a/core/src/main/java/se/su/dsv/scipro/gdpr/Html.java +++ b/core/src/main/java/se/su/dsv/scipro/gdpr/Html.java @@ -5,11 +5,13 @@ import java.util.List; public final class Html { - public static abstract class Node { + public abstract static class Node { + abstract String toHtmlString(); } private static final class Element extends Node { + private final String element; private final List children; @@ -20,11 +22,20 @@ public final class Html { @Override String toHtmlString() { - return "<" + element + ">" + children.stream().map(Node::toHtmlString).reduce("", (s1, s2) -> s1 + s2) + ""; + return ( + "<" + + element + + ">" + + children.stream().map(Node::toHtmlString).reduce("", (s1, s2) -> s1 + s2) + + "" + ); } } private static final class Text extends Node { + private final String text; private Text(final String text) { diff --git a/core/src/main/java/se/su/dsv/scipro/gdpr/Reporter.java b/core/src/main/java/se/su/dsv/scipro/gdpr/Reporter.java index da76bcf8d8..9a7d96db73 100644 --- a/core/src/main/java/se/su/dsv/scipro/gdpr/Reporter.java +++ b/core/src/main/java/se/su/dsv/scipro/gdpr/Reporter.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.gdpr; -import se.su.dsv.scipro.system.User; - import java.io.IOException; import java.nio.file.Path; +import se.su.dsv.scipro.system.User; public interface Reporter { Path generate(User user) throws IOException; diff --git a/core/src/main/java/se/su/dsv/scipro/gdpr/ZipReporter.java b/core/src/main/java/se/su/dsv/scipro/gdpr/ZipReporter.java index 8de05293ca..d14eedd77c 100644 --- a/core/src/main/java/se/su/dsv/scipro/gdpr/ZipReporter.java +++ b/core/src/main/java/se/su/dsv/scipro/gdpr/ZipReporter.java @@ -1,5 +1,17 @@ package se.su.dsv.scipro.gdpr; +import static se.su.dsv.scipro.gdpr.Html.*; + +import jakarta.inject.Inject; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.*; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; @@ -31,20 +43,8 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.*; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static se.su.dsv.scipro.gdpr.Html.*; - public class ZipReporter implements Reporter { + private final FileService fileDescriptionService; private final ProjectService projectService; private final FinalSeminarService finalSeminarService; @@ -61,20 +61,20 @@ public class ZipReporter implements Reporter { @Inject public ZipReporter( - final FileService fileDescriptionService, - final ProjectService projectService, - final FinalSeminarService finalSeminarService, - final ProjectForumService projectForumService, - final PeerReviewService peerReviewService, - final PeerRequestService peerRequestService, - final GroupService groupService, - final GroupForumService groupForumService, - final IdeaService ideaService, - final GradingReportService gradingReportService, - final ReviewerInteractionService reviewerInteractionService, - final RoughDraftApprovalService roughDraftApprovalService, - final FinalSeminarApprovalService finalSeminarApprovalService) - { + final FileService fileDescriptionService, + final ProjectService projectService, + final FinalSeminarService finalSeminarService, + final ProjectForumService projectForumService, + final PeerReviewService peerReviewService, + final PeerRequestService peerRequestService, + final GroupService groupService, + final GroupForumService groupForumService, + final IdeaService ideaService, + final GradingReportService gradingReportService, + final ReviewerInteractionService reviewerInteractionService, + final RoughDraftApprovalService roughDraftApprovalService, + final FinalSeminarApprovalService finalSeminarApprovalService + ) { this.fileDescriptionService = fileDescriptionService; this.projectService = projectService; this.finalSeminarService = finalSeminarService; @@ -94,63 +94,73 @@ public class ZipReporter implements Reporter { public Path generate(final User user) throws IOException { final Path zipFile = Files.createTempFile(Paths.get(FileDescription.FILE_ROOT), "gdpr-report-", ".zip"); try (final FileSystem zipFileFS = getZipFileSystem(zipFile)) { - final List uploadedFiles = fileDescriptionService.findAll(QFileDescription.fileDescription.uploader.eq(user)); + final List uploadedFiles = fileDescriptionService.findAll( + QFileDescription.fileDescription.uploader.eq(user) + ); copyFiles(zipFileFS, uploadedFiles); final List projects = projectService.getProjectsByUser(user); - final List finalSeminarDocuments = projects.stream() - .map(finalSeminarService::findByProject) - .filter(Objects::nonNull) - .map(FinalSeminar::getDocument) - .filter(Objects::nonNull) - .map(FileReference::getFileDescription) - .toList(); + final List finalSeminarDocuments = projects + .stream() + .map(finalSeminarService::findByProject) + .filter(Objects::nonNull) + .map(FinalSeminar::getDocument) + .filter(Objects::nonNull) + .map(FileReference::getFileDescription) + .toList(); copyFiles(zipFileFS, finalSeminarDocuments); - final List personalInformation = new LinkedList<>(Arrays.asList( - dt("Name"), dd(text(user.getFullName())), - dt("E-mail"), dd(text(user.getEmailAddress())), - dt("Usernames"), dd( - ul(user.getUsernames() - .stream() - .map(username -> - li(textL(username.getUsername()))) - .toList()) - ), - dt("Created"), dd(text(dateString(user.getDateCreated()))), - dt("Program admissions"), dd( - ul(user.getPrograms() - .stream() - .map(program -> - li(textL(program.getNameEn() + " (" + program.getCode() + ")"))) - .toList() - ) + final List personalInformation = new LinkedList<>( + Arrays.asList( + dt("Name"), + dd(text(user.getFullName())), + dt("E-mail"), + dd(text(user.getEmailAddress())), + dt("Usernames"), + dd(ul(user.getUsernames().stream().map(username -> li(textL(username.getUsername()))).toList())), + dt("Created"), + dd(text(dateString(user.getDateCreated()))), + dt("Program admissions"), + dd( + ul( + user + .getPrograms() + .stream() + .map(program -> li(textL(program.getNameEn() + " (" + program.getCode() + ")"))) + .toList() + ) ) - )); + ) + ); if (user.getUnit() != null) { personalInformation.addAll(List.of(dt("Unit"), dd(text(user.getUnit().getTitle())))); } if (!user.getLanguages().isEmpty()) { - final String languages = user.getLanguages().stream().map(Language::name) - .collect(Collectors.joining(", ")); + final String languages = user + .getLanguages() + .stream() + .map(Language::name) + .collect(Collectors.joining(", ")); personalInformation.addAll(List.of(dt("Supervising languages"), dd(text(languages)))); } if (!user.getResearchAreas().isEmpty()) { - final String researchAreas = user.getResearchAreas().stream().map(ResearchArea::getTitle) - .collect(Collectors.joining(", ")); + final String researchAreas = user + .getResearchAreas() + .stream() + .map(ResearchArea::getTitle) + .collect(Collectors.joining(", ")); personalInformation.addAll(List.of(dt("Research areas"), dd(text(researchAreas)))); } - final List reportData = new LinkedList<>(Arrays.asList( + final List reportData = new LinkedList<>( + Arrays.asList( h1(text("GDPR report for " + user.getFullName() + " generated on " + dateString(new Date()))), h2(text("Personal data")), dl(personalInformation), h2(text("Authorships")), - ul(projects.stream() - .map(project -> authorshipReport(user, project)) - .toList() - ) - )); + ul(projects.stream().map(project -> authorshipReport(user, project)).toList()) + ) + ); reportData.addAll(groupReport(user)); reportData.addAll(ideaReport(user)); @@ -169,25 +179,53 @@ public class ZipReporter implements Reporter { private Collection supervisorIdeaReport(User user) { IdeaService.Filter filter = new IdeaService.Filter(); filter.setSupervisor(user); - final List ideas = ideaService.findAll(filter) - .stream() - .map(idea -> div(List.of( + final List ideas = ideaService + .findAll(filter) + .stream() + .map(idea -> + div( + List.of( h3(text(idea.getTitle())), - dl(List.of( - dt("Type"), dd(text(idea.getProjectType().getName())), - dt("language"), dd(text(idea.getLanguages().stream().map(Language::name).collect(Collectors.joining(", ")))), - dt("Research area"), dd(text(idea.getResearchArea().getTitle())), - dt("Keywords"), dd(text(idea.getKeywords().stream().map(Keyword::getKeyword).collect(Collectors.joining(", ")))), - dt("Description"), dd(text(idea.getDescription())), - dt("Prerequisites"), dd(text(idea.getPrerequisites())) - )) - ))) - .toList(); + dl( + List.of( + dt("Type"), + dd(text(idea.getProjectType().getName())), + dt("language"), + dd( + text( + idea + .getLanguages() + .stream() + .map(Language::name) + .collect(Collectors.joining(", ")) + ) + ), + dt("Research area"), + dd(text(idea.getResearchArea().getTitle())), + dt("Keywords"), + dd( + text( + idea + .getKeywords() + .stream() + .map(Keyword::getKeyword) + .collect(Collectors.joining(", ")) + ) + ), + dt("Description"), + dd(text(idea.getDescription())), + dt("Prerequisites"), + dd(text(idea.getPrerequisites())) + ) + ) + ) + ) + ) + .toList(); if (ideas.isEmpty()) { return Collections.emptyList(); - } - else { + } else { return List.of(h2(text("Supervisor ideas")), div(ideas)); } } @@ -202,11 +240,14 @@ public class ZipReporter implements Reporter { } return List.of( - h2(text("Reviewing")), - div(reviewedProjects.stream() - .map(project -> reviewerReport(user, project)) - .flatMap(Collection::stream) - .toList()) + h2(text("Reviewing")), + div( + reviewedProjects + .stream() + .map(project -> reviewerReport(user, project)) + .flatMap(Collection::stream) + .toList() + ) ); } @@ -222,23 +263,29 @@ public class ZipReporter implements Reporter { private Collection reviewerDecisions(Project project) { final List decisions = getReviewerDecisions(project) - .filter(decision -> decision.getStatus() != Status.UNDECIDED) - .map(decision -> li(List.of( - dl(List.of( - dt("Decided"), dd(text(dateTimeString(decision.getDecisionDate()))), - dt("Decision"), dd(text(decision.getStatus().name())), - dt("Type"), dd(text(decision.getReviewerApproval().getStep().name())), - dt("Feedback"), dd(text(Objects.requireNonNullElse(decision.getReason(), "-"))) - )) - ))) - .toList(); + .filter(decision -> decision.getStatus() != Status.UNDECIDED) + .map(decision -> + li( + List.of( + dl( + List.of( + dt("Decided"), + dd(text(dateTimeString(decision.getDecisionDate()))), + dt("Decision"), + dd(text(decision.getStatus().name())), + dt("Type"), + dd(text(decision.getReviewerApproval().getStep().name())), + dt("Feedback"), + dd(text(Objects.requireNonNullElse(decision.getReason(), "-"))) + ) + ) + ) + ) + ) + .toList(); if (!decisions.isEmpty()) { - return List.of( - h4(text("Reviewer decisions")), - ul(decisions) - ); - } - else { + return List.of(h4(text("Reviewer decisions")), ul(decisions)); + } else { return Collections.emptyList(); } } @@ -252,11 +299,14 @@ public class ZipReporter implements Reporter { } return List.of( - h2(text("Supervisorships")), - div(projects.stream() - .map(project -> supervisorshipReport(user, project)) - .flatMap(Collection::stream) - .toList()) + h2(text("Supervisorships")), + div( + projects + .stream() + .map(project -> supervisorshipReport(user, project)) + .flatMap(Collection::stream) + .toList() + ) ); } @@ -266,7 +316,7 @@ public class ZipReporter implements Reporter { supervisorshipReport.addAll(projectForumReports(user, project)); - supervisorshipReport.addAll(reviewerInteraction(user ,project)); + supervisorshipReport.addAll(reviewerInteraction(user, project)); supervisorshipReport.addAll(reviewerApprovals(project)); final List gradingReports = gradingReportService.getSupervisorGradingReports(project); @@ -281,49 +331,54 @@ public class ZipReporter implements Reporter { private Collection reviewerApprovals(Project project) { final List decisions = getReviewerDecisions(project) - .map(decision -> li(List.of( - dl(List.of( - dt("Requested"), dd(text(dateTimeString(decision.getRequested()))), - dt("Type"), dd(text(decision.getReviewerApproval().getStep().name())), - dt("Comment"), dd(text(Objects.requireNonNullElse(decision.getComment(), "-"))) - )) - ))) - .toList(); + .map(decision -> + li( + List.of( + dl( + List.of( + dt("Requested"), + dd(text(dateTimeString(decision.getRequested()))), + dt("Type"), + dd(text(decision.getReviewerApproval().getStep().name())), + dt("Comment"), + dd(text(Objects.requireNonNullElse(decision.getComment(), "-"))) + ) + ) + ) + ) + ) + .toList(); if (!decisions.isEmpty()) { - return List.of( - h4(text("Reviewer approvals requested")), - ul(decisions) - ); - } - else { + return List.of(h4(text("Reviewer approvals requested")), ul(decisions)); + } else { return Collections.emptyList(); } } private Stream getReviewerDecisions(Project project) { - final Stream roughDraftDecisions = roughDraftApprovalService.findBy(project) - .stream() - .map(RoughDraftApproval::getHistory) - .flatMap(Collection::stream); - final Stream finalSeminarDecisions = finalSeminarApprovalService.findBy(project) - .stream() - .map(FinalSeminarApproval::getHistory) - .flatMap(Collection::stream); + final Stream roughDraftDecisions = roughDraftApprovalService + .findBy(project) + .stream() + .map(RoughDraftApproval::getHistory) + .flatMap(Collection::stream); + final Stream finalSeminarDecisions = finalSeminarApprovalService + .findBy(project) + .stream() + .map(FinalSeminarApproval::getHistory) + .flatMap(Collection::stream); return Stream.concat(roughDraftDecisions, finalSeminarDecisions); } private Collection reviewerInteraction(User user, Project project) { - final List forumPosts = reviewerInteractionService.getPosts(project) - .stream() - .filter(forumPost -> forumPost.getPostedBy().equals(user)) - .map(forumPost -> li(forumPostToHtml(forumPost))) - .toList(); + final List forumPosts = reviewerInteractionService + .getPosts(project) + .stream() + .filter(forumPost -> forumPost.getPostedBy().equals(user)) + .map(forumPost -> li(forumPostToHtml(forumPost))) + .toList(); if (!forumPosts.isEmpty()) { - return List.of( - h4(text("Reviewer interactions")), - ul(forumPosts)); - } - else { + return List.of(h4(text("Reviewer interactions")), ul(forumPosts)); + } else { return Collections.emptyList(); } } @@ -343,16 +398,28 @@ public class ZipReporter implements Reporter { private Collection gradingReportHtml(SupervisorGradingReport gradingReport) { final List list = new LinkedList<>(); list.add(h4(text("Grading report for " + gradingReport.getUser().getFullName()))); - final List criteria = gradingReport.getGradingCriteria() - .stream() - .filter(this::hasAssessment) - .map(gc -> li(List.of( - strong(text(String.format("%s (%s/%d points)", - gc.getTitle(gradingReport.getReportLanguage()), - Objects.requireNonNullElse(gc.getPoints(), "-"), gc.getMaxPoints()))), + final List criteria = gradingReport + .getGradingCriteria() + .stream() + .filter(this::hasAssessment) + .map(gc -> + li( + List.of( + strong( + text( + String.format( + "%s (%s/%d points)", + gc.getTitle(gradingReport.getReportLanguage()), + Objects.requireNonNullElse(gc.getPoints(), "-"), + gc.getMaxPoints() + ) + ) + ), p(text(gc.getFeedback())) - ))) - .toList(); + ) + ) + ) + .toList(); list.add(ul(criteria)); return list; } @@ -360,25 +427,37 @@ public class ZipReporter implements Reporter { private List ideaReport(final User user) { final IdeaService.Filter filter = new IdeaService.Filter(); filter.setAuthor(user); - final List ideas = ideaService.findAll(filter) - .stream() - .map(idea -> - li(Arrays.asList( - h3(text(idea.getTitle())), - dl(Arrays.asList( - dt("Application period"), dd(text(idea.getApplicationPeriod().getName())), - dt("Type"), dd(text(idea.getProjectType().getName())), - dt("Status"), dd(text(idea.getMatchStatus().name())), - dt("Research area"), dd(text(Optional.ofNullable(idea.getResearchArea()).map(ResearchArea::getTitle).orElse("None"))) - )) - )) + final List ideas = ideaService + .findAll(filter) + .stream() + .map(idea -> + li( + Arrays.asList( + h3(text(idea.getTitle())), + dl( + Arrays.asList( + dt("Application period"), + dd(text(idea.getApplicationPeriod().getName())), + dt("Type"), + dd(text(idea.getProjectType().getName())), + dt("Status"), + dd(text(idea.getMatchStatus().name())), + dt("Research area"), + dd( + text( + Optional.ofNullable(idea.getResearchArea()) + .map(ResearchArea::getTitle) + .orElse("None") + ) + ) + ) + ) + ) ) - .toList(); + ) + .toList(); if (!ideas.isEmpty()) { - return Arrays.asList( - h2(text("Ideas")), - ul(ideas) - ); + return Arrays.asList(h2(text("Ideas")), ul(ideas)); } else { return Collections.emptyList(); } @@ -394,48 +473,69 @@ public class ZipReporter implements Reporter { final List supervisorGroups = groupService.findAll(supervisorFilter); final List posts = Stream.concat(authorGroups.stream(), supervisorGroups.stream()) - .distinct() - .map(groupForumService::getThreads).flatMap(List::stream) - .map(groupForumService::getPosts).flatMap(List::stream) - .filter(post -> post.getPostedBy().equals(user)) - .sorted(Comparator.comparing(ForumPost::getDateCreated)) - .map(post -> li(forumPostToHtml(post))) - .toList(); + .distinct() + .map(groupForumService::getThreads) + .flatMap(List::stream) + .map(groupForumService::getPosts) + .flatMap(List::stream) + .filter(post -> post.getPostedBy().equals(user)) + .sorted(Comparator.comparing(ForumPost::getDateCreated)) + .map(post -> li(forumPostToHtml(post))) + .toList(); if (!posts.isEmpty()) { - return Arrays.asList( - h2(text("Group forum posts")), - ul(posts) - ); - } - else { + return Arrays.asList(h2(text("Group forum posts")), ul(posts)); + } else { return Collections.emptyList(); } } private Node authorshipReport(final User user, final Project project) { - final List children = new LinkedList<>(Arrays.asList( + final List children = new LinkedList<>( + Arrays.asList( h3(text(project.getTitle())), - dl(Arrays.asList( - dt("Type"), dd(text(project.getProjectType().getName())), - dt("Credits"), dd(text(Integer.toString(project.getCredits()))), - dt("Status"), dd(text(project.getProjectStatus().name())), - dt("Created"), dd(text(dateString(project.getStartDate()))), - dt("Research area"), dd(text(Optional.ofNullable(project.getResearchArea()).map(ResearchArea::getTitle).orElse("None"))), - dt("Language"), dd(text(Optional.ofNullable(project.getLanguage()).map(Language::name).orElse("None"))) - )) - )); + dl( + Arrays.asList( + dt("Type"), + dd(text(project.getProjectType().getName())), + dt("Credits"), + dd(text(Integer.toString(project.getCredits()))), + dt("Status"), + dd(text(project.getProjectStatus().name())), + dt("Created"), + dd(text(dateString(project.getStartDate()))), + dt("Research area"), + dd( + text( + Optional.ofNullable(project.getResearchArea()) + .map(ResearchArea::getTitle) + .orElse("None") + ) + ), + dt("Language"), + dd(text(Optional.ofNullable(project.getLanguage()).map(Language::name).orElse("None"))) + ) + ) + ) + ); final FinalSeminar finalSeminar = finalSeminarService.findByProject(project); if (finalSeminar != null) { children.addAll(finalSeminarReport(finalSeminar)); } - final List oppositions = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), user); + final List oppositions = + finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), user); if (!oppositions.isEmpty()) { List seminars = oppositions.stream().map(FinalSeminarParticipation::getFinalSeminar).toList(); children.addAll(oppositionsReport("Oppositions", seminars)); } - final List participations = finalSeminarService.findUserParticipating(project, user); + final List participations = finalSeminarService.findUserParticipating( + project, + user + ); if (!participations.isEmpty()) { - List seminars = participations.stream().map(FinalSeminarActiveParticipation::getFinalSeminar).toList(); + List seminars = participations + .stream() + .map(FinalSeminarActiveParticipation::getFinalSeminar) + .toList(); children.addAll(oppositionsReport("Active participations", seminars)); } final List peerRequests = peerRequestService.findByRequesterAndProject(user, project); @@ -452,135 +552,157 @@ public class ZipReporter implements Reporter { private List oppositionsReport(final String heading, final List oppositions) { return Arrays.asList( - h4(text(heading)), - ul(oppositions.stream() - .map(opposition -> li(finalSeminarParticipantReport(opposition))) - .toList() - ) + h4(text(heading)), + ul(oppositions.stream().map(opposition -> li(finalSeminarParticipantReport(opposition))).toList()) ); } private List finalSeminarParticipantReport(final FinalSeminar finalSeminar) { - return Collections.singletonList(dl(Arrays.asList( - dt("Project"), dd(text(finalSeminar.getProject().getTitle())), - dt("Seminar held on"), dd(text(dateTimeString(finalSeminar.getStartDate()))), - dt("Location"), dd(text(finalSeminar.getRoom())) - ))); + return Collections.singletonList( + dl( + Arrays.asList( + dt("Project"), + dd(text(finalSeminar.getProject().getTitle())), + dt("Seminar held on"), + dd(text(dateTimeString(finalSeminar.getStartDate()))), + dt("Location"), + dd(text(finalSeminar.getRoom())) + ) + ) + ); } private List projectForumReports(final User user, final Project project) { - final List posts = projectForumService.getThreads(project) - .stream() - .map(projectForumService::getPosts) - .flatMap(List::stream) - .filter(post -> post.getPostedBy().equals(user)) - .sorted(Comparator.comparing(ForumPost::getDateCreated)) - .map(post -> li(forumPostToHtml(post))) - .toList(); + final List posts = projectForumService + .getThreads(project) + .stream() + .map(projectForumService::getPosts) + .flatMap(List::stream) + .filter(post -> post.getPostedBy().equals(user)) + .sorted(Comparator.comparing(ForumPost::getDateCreated)) + .map(post -> li(forumPostToHtml(post))) + .toList(); if (!posts.isEmpty()) { - return Arrays.asList( - h4(text("Forum posts")), - ul(posts) - ); - } - else { + return Arrays.asList(h4(text("Forum posts")), ul(posts)); + } else { return Collections.emptyList(); } } private List peerReviewsReport(final List peerReviews) { return Arrays.asList( - h4(text("Peer reviews")), - ul(peerReviews.stream() - .map(peerReview -> li(peerReviewReport(peerReview))) - .toList() - ) + h4(text("Peer reviews")), + ul(peerReviews.stream().map(peerReview -> li(peerReviewReport(peerReview))).toList()) ); } private List peerReviewReport(final PeerReview peerReview) { final List nodes = new LinkedList<>(); - nodes.addAll(Arrays.asList( - dt("Started"), dd(text(dateString(peerReview.getDateCreated()))) - )); - nodes.addAll(Arrays.asList( - dt("Status"), dd(text(peerReview.getStatus().name())) - )); + nodes.addAll(Arrays.asList(dt("Started"), dd(text(dateString(peerReview.getDateCreated()))))); + nodes.addAll(Arrays.asList(dt("Status"), dd(text(peerReview.getStatus().name())))); if (peerReview.getComment() != null) { - nodes.addAll(Arrays.asList( - dt("Comment"), dd(text(peerReview.getComment())) - )); + nodes.addAll(Arrays.asList(dt("Comment"), dd(text(peerReview.getComment())))); } final FileReference file = peerReview.getFile(); if (file != null) { - nodes.addAll(Arrays.asList( - dt("Attached comments"), dd(text("See Attachments/" + file.getId() + "-" + file.getName())) - )); + nodes.addAll( + Arrays.asList( + dt("Attached comments"), + dd(text("See Attachments/" + file.getId() + "-" + file.getName())) + ) + ); } if (!peerReview.getAnswers().isEmpty()) { - nodes.addAll(Arrays.asList( - dt("Checklist answers"), dd( - ol(peerReview.getAnswers() - .stream() - .map(answer -> - li(Collections.singletonList( - dl(Arrays.asList( - dt(answer.getQuestion()), - dd(text(answer.getAnswer().name() + - Optional.ofNullable(answer.getMotivation()).map(m -> " - " + m).orElse(""))) - )) - )) + nodes.addAll( + Arrays.asList( + dt("Checklist answers"), + dd( + ol( + peerReview + .getAnswers() + .stream() + .map(answer -> + li( + Collections.singletonList( + dl( + Arrays.asList( + dt(answer.getQuestion()), + dd( + text( + answer.getAnswer().name() + + Optional.ofNullable(answer.getMotivation()) + .map(m -> " - " + m) + .orElse("") + ) + ) + ) + ) + ) ) - .toList() - ) + ) + .toList() + ) ) - )); + ) + ); } return Collections.singletonList(dl(nodes)); } private List peerRequestsReport(final List peerRequests) { return Arrays.asList( - h4(text("Peer requests")), - ul(peerRequests.stream() - .map(peerRequest -> li(peerRequestReport(peerRequest))) - .toList() - ) + h4(text("Peer requests")), + ul(peerRequests.stream().map(peerRequest -> li(peerRequestReport(peerRequest))).toList()) ); } private List peerRequestReport(final PeerRequest peerRequest) { final FileDescription file = peerRequest.getFile().getFileDescription(); return Collections.singletonList( - dl(Arrays.asList( - dt("Requested"), dd(text(dateString(peerRequest.getDateCreated()))), - dt("Status"), dd(text(peerRequest.getStatus().name())), - dt("Comment"), dd(text(Optional.ofNullable(peerRequest.getComment()).orElse("None"))), - dt("Language"), dd(text(peerRequest.getLanguage().name())), - dt("Document to be reviewed"), dd(text("See Attachments/" + getFilename(file))) - )) + dl( + Arrays.asList( + dt("Requested"), + dd(text(dateString(peerRequest.getDateCreated()))), + dt("Status"), + dd(text(peerRequest.getStatus().name())), + dt("Comment"), + dd(text(Optional.ofNullable(peerRequest.getComment()).orElse("None"))), + dt("Language"), + dd(text(peerRequest.getLanguage().name())), + dt("Document to be reviewed"), + dd(text("See Attachments/" + getFilename(file))) + ) + ) ); } private List finalSeminarReport(final FinalSeminar finalSeminar) { - final FileDescription document = finalSeminar.getDocument() != null ? finalSeminar.getDocument().getFileDescription() : null; + final FileDescription document = finalSeminar.getDocument() != null + ? finalSeminar.getDocument().getFileDescription() + : null; return Arrays.asList( - h4(text("Final seminar")), - dl(Arrays.asList( - dt("Held on"), dd(text(dateTimeString(finalSeminar.getStartDate()))), - dt("Location"), dd(text(finalSeminar.getRoom())), - dt("Scheduled"), dd(text(dateString(finalSeminar.getDateCreated()))), - dt("Document"), dd(text(document != null ? "See Attachments/" + getFilename(document) : "None")) - )) + h4(text("Final seminar")), + dl( + Arrays.asList( + dt("Held on"), + dd(text(dateTimeString(finalSeminar.getStartDate()))), + dt("Location"), + dd(text(finalSeminar.getRoom())), + dt("Scheduled"), + dd(text(dateString(finalSeminar.getDateCreated()))), + dt("Document"), + dd(text(document != null ? "See Attachments/" + getFilename(document) : "None")) + ) + ) ); } private List forumPostToHtml(ForumPost post) { return Arrays.asList( - h5(text(post.getSubject())), - text(dateTimeString(post.getDateCreated())), - text(" "), - text(post.getContent()) + h5(text(post.getSubject())), + text(dateTimeString(post.getDateCreated())), + text(" "), + text(post.getContent()) ); } diff --git a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettings.java b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettings.java index 511fd841b4..6f813e29de 100755 --- a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettings.java @@ -1,16 +1,17 @@ package se.su.dsv.scipro.generalsystemsettings; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.SystemModule; - import jakarta.persistence.*; import java.util.*; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.SystemModule; @Entity @Table(name = "general_system_settings") @Cacheable(true) public class GeneralSystemSettings extends DomainObject { + public static final int DEFAULT_NUMER_OF_LATEST_REVIEWS_DISPLAYED = 3; + @Id private Long id = null; @@ -21,14 +22,18 @@ public class GeneralSystemSettings extends DomainObject { private String daisySelectResearchAreaURL; @ElementCollection - @CollectionTable(name = "general_system_settings_alarm_recipient", - joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id")) + @CollectionTable( + name = "general_system_settings_alarm_recipient", + joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id") + ) @Column(name = "mail") private List alarmMails = new ArrayList<>(); @ElementCollection - @CollectionTable(name = "general_system_settings_supervisor_change_recipient", - joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id")) + @CollectionTable( + name = "general_system_settings_supervisor_change_recipient", + joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id") + ) @Column(name = "mail") private List supervisorChangeMails = new ArrayList<>(); @@ -67,8 +72,10 @@ public class GeneralSystemSettings extends DomainObject { @ElementCollection @Enumerated(EnumType.STRING) - @CollectionTable(name = "general_system_settings_system_module", - joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id")) + @CollectionTable( + name = "general_system_settings_system_module", + joinColumns = @JoinColumn(name = "general_system_settings_id", referencedColumnName = "id") + ) @Column(name = "system_module") private Set systemModules = EnumSet.allOf(SystemModule.class); @@ -96,8 +103,7 @@ public class GeneralSystemSettings extends DomainObject { @Column(name = "active_project_idea_support_mail") private String activeProjectIdeaSupportMail; - public GeneralSystemSettings() { - } + public GeneralSystemSettings() {} /** * Not part of the public API, do NOT USE @@ -305,7 +311,57 @@ public class GeneralSystemSettings extends DomainObject { @Override public String toString() { - return "GeneralSystemSettings(id=" + this.getId() + ", daisyProfileLinkBaseURL=" + this.getDaisyProfileLinkBaseURL() + ", alarmMails=" + this.getAlarmMails() + ", supervisorChangeMails=" + this.getSupervisorChangeMails() + ", projectPartnerDaysToLive=" + this.getProjectPartnerDaysToLive() + ", mailNotifications=" + this.isMailNotifications() + ", mailFromName=" + this.getMailFromName() + ", systemFromMail=" + this.getSystemFromMail() + ", smtpServer=" + this.getSmtpServer() + ", peerDisplayLatestReviews=" + this.isPeerDisplayLatestReviews() + ", numberOfLatestReviewsDisplayed=" + this.getNumberOfLatestReviewsDisplayed() + ", publicReviewsActivated=" + this.isPublicReviewsActivated() + ", peerDownloadEnabled=" + this.isPeerDownloadEnabled() + ", sciproURL=" + this.getSciproURL() + ", showSingleSignOn=" + this.isShowSingleSignOn() + ", systemModules=" + this.getSystemModules() + ", matchResponsibleMail=" + this.getMatchResponsibleMail() + ", reviewerSupportMail=" + this.getReviewerSupportMail() + ", thesisSupportMail=" + this.getThesisSupportMail() + ", externalRoomBookingURL=" + this.getExternalRoomBookingURL() + ", externalGettingStartedWithIdeaURL=" + this.getExternalGettingStartedWithIdeaURL() + ", externalGradingURL=" + this.getExternalGradingURL() + ", finalSurveyAvailable=" + this.isFinalSurveyAvailable() + ", activeProjectIdeaSupportMail=" + this.getActiveProjectIdeaSupportMail() + ")"; + return ( + "GeneralSystemSettings(id=" + + this.getId() + + ", daisyProfileLinkBaseURL=" + + this.getDaisyProfileLinkBaseURL() + + ", alarmMails=" + + this.getAlarmMails() + + ", supervisorChangeMails=" + + this.getSupervisorChangeMails() + + ", projectPartnerDaysToLive=" + + this.getProjectPartnerDaysToLive() + + ", mailNotifications=" + + this.isMailNotifications() + + ", mailFromName=" + + this.getMailFromName() + + ", systemFromMail=" + + this.getSystemFromMail() + + ", smtpServer=" + + this.getSmtpServer() + + ", peerDisplayLatestReviews=" + + this.isPeerDisplayLatestReviews() + + ", numberOfLatestReviewsDisplayed=" + + this.getNumberOfLatestReviewsDisplayed() + + ", publicReviewsActivated=" + + this.isPublicReviewsActivated() + + ", peerDownloadEnabled=" + + this.isPeerDownloadEnabled() + + ", sciproURL=" + + this.getSciproURL() + + ", showSingleSignOn=" + + this.isShowSingleSignOn() + + ", systemModules=" + + this.getSystemModules() + + ", matchResponsibleMail=" + + this.getMatchResponsibleMail() + + ", reviewerSupportMail=" + + this.getReviewerSupportMail() + + ", thesisSupportMail=" + + this.getThesisSupportMail() + + ", externalRoomBookingURL=" + + this.getExternalRoomBookingURL() + + ", externalGettingStartedWithIdeaURL=" + + this.getExternalGettingStartedWithIdeaURL() + + ", externalGradingURL=" + + this.getExternalGradingURL() + + ", finalSurveyAvailable=" + + this.isFinalSurveyAvailable() + + ", activeProjectIdeaSupportMail=" + + this.getActiveProjectIdeaSupportMail() + + ")" + ); } @Override @@ -313,32 +369,34 @@ public class GeneralSystemSettings extends DomainObject { if (o == this) return true; if (!(o instanceof GeneralSystemSettings)) return false; final GeneralSystemSettings other = (GeneralSystemSettings) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getDaisyProfileLinkBaseURL(), other.getDaisyProfileLinkBaseURL()) - && Objects.equals(this.getAlarmMails(), other.getAlarmMails()) - && Objects.equals(this.getSupervisorChangeMails(), other.getSupervisorChangeMails()) - && this.getProjectPartnerDaysToLive() == other.getProjectPartnerDaysToLive() - && this.isMailNotifications() == other.isMailNotifications() - && Objects.equals(this.getMailFromName(), other.getMailFromName()) - && Objects.equals(this.getSystemFromMail(), other.getSystemFromMail()) - && Objects.equals(this.getSmtpServer(), other.getSmtpServer()) - && this.isPeerDisplayLatestReviews() == other.isPeerDisplayLatestReviews() - && this.getNumberOfLatestReviewsDisplayed() == other.getNumberOfLatestReviewsDisplayed() - && this.isPublicReviewsActivated() == other.isPublicReviewsActivated() - && this.isPeerDownloadEnabled() == other.isPeerDownloadEnabled() - && Objects.equals(this.getSciproURL(), other.getSciproURL()) - && this.isShowSingleSignOn() == other.isShowSingleSignOn() - && Objects.equals(this.getSystemModules(), other.getSystemModules()) - && Objects.equals(this.getMatchResponsibleMail(), other.getMatchResponsibleMail()) - && Objects.equals(this.getReviewerSupportMail(), other.getReviewerSupportMail()) - && Objects.equals(this.getThesisSupportMail(), other.getThesisSupportMail()) - && Objects.equals(this.getExternalRoomBookingURL(), other.getExternalRoomBookingURL()) - && Objects.equals(this.getExternalGettingStartedWithIdeaURL(), other.getExternalGettingStartedWithIdeaURL()) - && Objects.equals(this.getExternalGradingURL(), other.getExternalGradingURL()) - && this.isFinalSurveyAvailable() == other.isFinalSurveyAvailable() - && Objects.equals(this.getActiveProjectIdeaSupportMail(), other.getActiveProjectIdeaSupportMail()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getDaisyProfileLinkBaseURL(), other.getDaisyProfileLinkBaseURL()) && + Objects.equals(this.getAlarmMails(), other.getAlarmMails()) && + Objects.equals(this.getSupervisorChangeMails(), other.getSupervisorChangeMails()) && + this.getProjectPartnerDaysToLive() == other.getProjectPartnerDaysToLive() && + this.isMailNotifications() == other.isMailNotifications() && + Objects.equals(this.getMailFromName(), other.getMailFromName()) && + Objects.equals(this.getSystemFromMail(), other.getSystemFromMail()) && + Objects.equals(this.getSmtpServer(), other.getSmtpServer()) && + this.isPeerDisplayLatestReviews() == other.isPeerDisplayLatestReviews() && + this.getNumberOfLatestReviewsDisplayed() == other.getNumberOfLatestReviewsDisplayed() && + this.isPublicReviewsActivated() == other.isPublicReviewsActivated() && + this.isPeerDownloadEnabled() == other.isPeerDownloadEnabled() && + Objects.equals(this.getSciproURL(), other.getSciproURL()) && + this.isShowSingleSignOn() == other.isShowSingleSignOn() && + Objects.equals(this.getSystemModules(), other.getSystemModules()) && + Objects.equals(this.getMatchResponsibleMail(), other.getMatchResponsibleMail()) && + Objects.equals(this.getReviewerSupportMail(), other.getReviewerSupportMail()) && + Objects.equals(this.getThesisSupportMail(), other.getThesisSupportMail()) && + Objects.equals(this.getExternalRoomBookingURL(), other.getExternalRoomBookingURL()) && + Objects.equals(this.getExternalGettingStartedWithIdeaURL(), other.getExternalGettingStartedWithIdeaURL()) && + Objects.equals(this.getExternalGradingURL(), other.getExternalGradingURL()) && + this.isFinalSurveyAvailable() == other.isFinalSurveyAvailable() && + Objects.equals(this.getActiveProjectIdeaSupportMail(), other.getActiveProjectIdeaSupportMail()) + ); } protected boolean canEqual(final Object other) { @@ -347,29 +405,31 @@ public class GeneralSystemSettings extends DomainObject { @Override public int hashCode() { - return Objects.hash(this.getId(), - this.getDaisyProfileLinkBaseURL(), - this.getAlarmMails(), - this.getSupervisorChangeMails(), - this.getProjectPartnerDaysToLive(), - this.isMailNotifications(), - this.getMailFromName(), - this.getSystemFromMail(), - this.getSmtpServer(), - this.isPeerDisplayLatestReviews(), - this.getNumberOfLatestReviewsDisplayed(), - this.isPublicReviewsActivated(), - this.isPeerDownloadEnabled(), - this.getSciproURL(), - this.isShowSingleSignOn(), - this.getSystemModules(), - this.getMatchResponsibleMail(), - this.getReviewerSupportMail(), - this.getThesisSupportMail(), - this.getExternalRoomBookingURL(), - this.getExternalGettingStartedWithIdeaURL(), - this.getExternalGradingURL(), - this.isFinalSurveyAvailable(), - this.getActiveProjectIdeaSupportMail()); + return Objects.hash( + this.getId(), + this.getDaisyProfileLinkBaseURL(), + this.getAlarmMails(), + this.getSupervisorChangeMails(), + this.getProjectPartnerDaysToLive(), + this.isMailNotifications(), + this.getMailFromName(), + this.getSystemFromMail(), + this.getSmtpServer(), + this.isPeerDisplayLatestReviews(), + this.getNumberOfLatestReviewsDisplayed(), + this.isPublicReviewsActivated(), + this.isPeerDownloadEnabled(), + this.getSciproURL(), + this.isShowSingleSignOn(), + this.getSystemModules(), + this.getMatchResponsibleMail(), + this.getReviewerSupportMail(), + this.getThesisSupportMail(), + this.getExternalRoomBookingURL(), + this.getExternalGettingStartedWithIdeaURL(), + this.getExternalGradingURL(), + this.isFinalSurveyAvailable(), + this.getActiveProjectIdeaSupportMail() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsService.java b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsService.java index 1664234428..baa487aca5 100755 --- a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsService.java +++ b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsService.java @@ -3,6 +3,6 @@ package se.su.dsv.scipro.generalsystemsettings; import se.su.dsv.scipro.system.GenericService; public interface GeneralSystemSettingsService extends GenericService { - GeneralSystemSettings getGeneralSystemSettingsInstance(); + GeneralSystemSettings getGeneralSystemSettingsInstance(); String getExternalGettingStartedWithIdeaURL(); } diff --git a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsServiceImpl.java index 5450f5b837..c5a5f6d48d 100755 --- a/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/generalsystemsettings/GeneralSystemSettingsServiceImpl.java @@ -1,13 +1,14 @@ package se.su.dsv.scipro.generalsystemsettings; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.system.AbstractServiceImpl; -public class GeneralSystemSettingsServiceImpl extends AbstractServiceImpl implements GeneralSystemSettingsService { +public class GeneralSystemSettingsServiceImpl + extends AbstractServiceImpl + implements GeneralSystemSettingsService { private static final long INSTANCE_ID = 1L; @@ -31,7 +32,9 @@ public class GeneralSystemSettingsServiceImpl extends AbstractServiceImpl S save(S object) { if (object.getId() == null) { - throw new UnsupportedOperationException("You're not supposed to be creating new instances of this object manually!"); + throw new UnsupportedOperationException( + "You're not supposed to be creating new instances of this object manually!" + ); } return super.save(object); } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/grading/ApprovedEvent.java index 88160eb8a9..a9f3acb1a3 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ApprovedEvent.java @@ -10,10 +10,9 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import se.su.dsv.scipro.project.Project; - import java.time.Instant; import java.util.Objects; +import se.su.dsv.scipro.project.Project; @Entity @Table(name = "grading_history_approval") @@ -71,10 +70,12 @@ public class ApprovedEvent { @Override public boolean equals(Object o) { if (this == o) return true; - return o instanceof ApprovedEvent that - && Objects.equals(id, that.id) - && Objects.equals(project, that.project) - && Objects.equals(when, that.when); + return ( + o instanceof ApprovedEvent that && + Objects.equals(id, that.id) && + Objects.equals(project, that.project) && + Objects.equals(when, that.when) + ); } @Override @@ -84,7 +85,6 @@ public class ApprovedEvent { @Override public String toString() { - return "ApprovedEvent{" + "id=" + id + ", project=" + project + - ", when=" + when + '}'; + return ("ApprovedEvent{" + "id=" + id + ", project=" + project + ", when=" + when + '}'); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/Examination.java b/core/src/main/java/se/su/dsv/scipro/grading/Examination.java index 198d452577..f5c876bed9 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/Examination.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/Examination.java @@ -2,21 +2,18 @@ package se.su.dsv.scipro.grading; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; - import java.math.BigDecimal; import java.util.*; @JsonIgnoreProperties(ignoreUnknown = true) public record Examination( - @JsonProperty("id") int id, - @JsonProperty("name") Name name, - @JsonProperty("provkod") String provkod, - @JsonProperty("points") BigDecimal points, - @JsonProperty("grades") List grades) -{ + @JsonProperty("id") int id, + @JsonProperty("name") Name name, + @JsonProperty("provkod") String provkod, + @JsonProperty("points") BigDecimal points, + @JsonProperty("grades") List grades +) { public boolean hasManyPassingGrades() { - return grades.stream() - .filter(grade -> grade.type() == Grade.Type.PASSING) - .count() > 1; + return (grades.stream().filter(grade -> grade.type() == Grade.Type.PASSING).count() > 1); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelineService.java b/core/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelineService.java index 6a0afcc50b..6e2f48b5da 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelineService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelineService.java @@ -1,13 +1,11 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.time.Instant; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; public interface ExaminerTimelineService { - /** * @return all the events sorted by time, descending (newest first) */ @@ -32,5 +30,4 @@ public interface ExaminerTimelineService { record Approved(Instant when) implements Event {} } - } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/Grade.java b/core/src/main/java/se/su/dsv/scipro/grading/Grade.java index c8d350f94a..10b765f459 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/Grade.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/Grade.java @@ -4,10 +4,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public record Grade( - @JsonProperty("type") - @JsonDeserialize(using = GradingTypeConverter.class) - Type type, - @JsonProperty("letter") String letter) -{ - public enum Type {PASSING, CREDITED, FAILING} + @JsonProperty("type") @JsonDeserialize(using = GradingTypeConverter.class) Type type, + @JsonProperty("letter") String letter +) { + public enum Type { + PASSING, + CREDITED, + FAILING, + } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingBasis.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingBasis.java index 9f080bda73..59fac71689 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingBasis.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingBasis.java @@ -4,13 +4,20 @@ import java.util.List; import java.util.Objects; public final class GradingBasis { + private final List criteria; private final boolean locked; private String overallMotivation; private final String rejectionComment; private String rejectionCommentFeedback; - public GradingBasis(List criteria, boolean locked, String overallMotivation, String rejectionComment, String rejectionCommentFeedback) { + public GradingBasis( + List criteria, + boolean locked, + String overallMotivation, + String rejectionComment, + String rejectionCommentFeedback + ) { this.criteria = criteria; this.locked = locked; this.overallMotivation = overallMotivation; @@ -49,12 +56,14 @@ public final class GradingBasis { @Override public boolean equals(Object obj) { if (obj == this) return true; - return obj instanceof GradingBasis that - && Objects.equals(this.criteria, that.criteria) - && Objects.equals(this.overallMotivation, that.overallMotivation) - && Objects.equals(this.locked, that.locked) - && Objects.equals(this.rejectionComment, that.rejectionComment) - && Objects.equals(this.rejectionCommentFeedback, that.rejectionCommentFeedback); + return ( + obj instanceof GradingBasis that && + Objects.equals(this.criteria, that.criteria) && + Objects.equals(this.overallMotivation, that.overallMotivation) && + Objects.equals(this.locked, that.locked) && + Objects.equals(this.rejectionComment, that.rejectionComment) && + Objects.equals(this.rejectionCommentFeedback, that.rejectionCommentFeedback) + ); } @Override @@ -64,16 +73,27 @@ public final class GradingBasis { @Override public String toString() { - return "GradingBasis{" + - "criteria=" + criteria + - ", locked=" + locked + - ", overallMotivation='" + overallMotivation + '\'' + - ", rejectionComment='" + rejectionComment + '\'' + - ", rejectionCommentFeedback='" + rejectionCommentFeedback + '\'' + - '}'; + return ( + "GradingBasis{" + + "criteria=" + + criteria + + ", locked=" + + locked + + ", overallMotivation='" + + overallMotivation + + '\'' + + ", rejectionComment='" + + rejectionComment + + '\'' + + ", rejectionCommentFeedback='" + + rejectionCommentFeedback + + '\'' + + '}' + ); } public static final class Assessment { + private final Criterion criterion; private Integer points; @@ -97,9 +117,11 @@ public final class GradingBasis { @Override public boolean equals(Object obj) { if (obj == this) return true; - return obj instanceof Assessment that - && Objects.equals(this.criterion, that.criterion) - && Objects.equals(this.points, that.points); + return ( + obj instanceof Assessment that && + Objects.equals(this.criterion, that.criterion) && + Objects.equals(this.points, that.points) + ); } @Override @@ -109,27 +131,23 @@ public final class GradingBasis { @Override public String toString() { - return "Assessment[" + - "criterion=" + criterion + ", " + - "points=" + points + ']'; + return ("Assessment[" + "criterion=" + criterion + ", " + "points=" + points + ']'); } } public record Criterion(String title, List requirements, int minimumPoints) { - public boolean isPassFail() { return minimumPoints() == 1 && maxPoints() == 1; } public int maxPoints() { return requirements() - .stream() - .mapToInt(Requirement::points) - .max() - .orElseThrow(() -> new IllegalStateException("Criterion without requirements: " + title())); + .stream() + .mapToInt(Requirement::points) + .max() + .orElseThrow(() -> new IllegalStateException("Criterion without requirements: " + title())); } - public record Requirement(int points, String description) { - } + public record Requirement(int points, String description) {} } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingCompletedEvent.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingCompletedEvent.java index 6032381838..4d4253e651 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingCompletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingCompletedEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; public class GradingCompletedEvent { + private final Project project; private final User student; diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistory.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistory.java index 8b1181ae68..94d34d8cd0 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistory.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistory.java @@ -1,21 +1,21 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; -public class GradingHistory implements +public class GradingHistory + implements ExaminerTimelineService, ThesisRejectionHistoryService, ThesisApprovedHistoryService, - ThesisSubmissionHistoryService -{ + ThesisSubmissionHistoryService { + private final GradingHistoryEventRepository gradingHistoryEventRepository; @Inject @@ -32,10 +32,9 @@ public class GradingHistory implements if (submission.getCorrections() == null || submission.getCorrections().isBlank()) { events.add(new Event.InitialSubmission(submission.getWhen(), submission.getAuthor())); } else { - events.add(new Event.Resubmitted( - submission.getWhen(), - submission.getAuthor(), - submission.getCorrections())); + events.add( + new Event.Resubmitted(submission.getWhen(), submission.getAuthor(), submission.getCorrections()) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepository.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepository.java index 6407d3c852..1fa1f0ab1a 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepository.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; - import java.util.Collection; +import se.su.dsv.scipro.project.Project; public interface GradingHistoryEventRepository { void save(RejectionEvent rejectionEvent); diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepositoryImpl.java index de3f36ac13..25e99a7ab0 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingHistoryEventRepositoryImpl.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.grading; -import jakarta.transaction.Transactional; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.Collection; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractRepository; public class GradingHistoryEventRepositoryImpl extends AbstractRepository implements GradingHistoryEventRepository { + @Inject public GradingHistoryEventRepositoryImpl(Provider em) { super(em); @@ -23,9 +23,7 @@ public class GradingHistoryEventRepositoryImpl extends AbstractRepository implem @Override public Collection findRejections(Project project) { - return from(QRejectionEvent.rejectionEvent) - .where(QRejectionEvent.rejectionEvent.project.eq(project)) - .fetch(); + return from(QRejectionEvent.rejectionEvent).where(QRejectionEvent.rejectionEvent.project.eq(project)).fetch(); } @Override @@ -36,9 +34,7 @@ public class GradingHistoryEventRepositoryImpl extends AbstractRepository implem @Override public Collection findApprovals(Project project) { - return from(QApprovedEvent.approvedEvent) - .where(QApprovedEvent.approvedEvent.project.eq(project)) - .fetch(); + return from(QApprovedEvent.approvedEvent).where(QApprovedEvent.approvedEvent.project.eq(project)).fetch(); } @Override @@ -50,7 +46,7 @@ public class GradingHistoryEventRepositoryImpl extends AbstractRepository implem @Override public Collection findSubmissions(Project project) { return from(QSubmissionEvent.submissionEvent) - .where(QSubmissionEvent.submissionEvent.project.eq(project)) - .fetch(); + .where(QSubmissionEvent.submissionEvent.project.eq(project)) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateService.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateService.java index 1c23b7c0a5..6b5daf224b 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateService.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.report.DuplicateDateException; -import se.su.dsv.scipro.report.GradingReportTemplate; -import se.su.dsv.scipro.report.ValidDateMustBeInTheFutureException; -import se.su.dsv.scipro.report.NoSuchTemplateException; -import se.su.dsv.scipro.report.TemplateLockedException; -import se.su.dsv.scipro.system.ProjectType; - import java.time.LocalDate; import java.util.List; +import se.su.dsv.scipro.report.DuplicateDateException; +import se.su.dsv.scipro.report.GradingReportTemplate; +import se.su.dsv.scipro.report.NoSuchTemplateException; +import se.su.dsv.scipro.report.TemplateLockedException; +import se.su.dsv.scipro.report.ValidDateMustBeInTheFutureException; +import se.su.dsv.scipro.system.ProjectType; public interface GradingReportTemplateService { List getProjectTypes(); @@ -28,14 +27,8 @@ public interface GradingReportTemplateService { List getUpcomingTemplates(ProjectType projectType); GradingReportTemplate update(long templateId, GradingReportTemplateUpdate update) - throws - ValidDateMustBeInTheFutureException, - NoSuchTemplateException, - DuplicateDateException, - TemplateLockedException; + throws ValidDateMustBeInTheFutureException, NoSuchTemplateException, DuplicateDateException, TemplateLockedException; GradingReportTemplate create(ProjectType projectType, GradingReportTemplateUpdate update) - throws - ValidDateMustBeInTheFutureException, - DuplicateDateException; + throws ValidDateMustBeInTheFutureException, DuplicateDateException; } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateUpdate.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateUpdate.java index ce7a1b70aa..3e61581ab9 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateUpdate.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingReportTemplateUpdate.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.grading; import jakarta.annotation.Nullable; - import java.time.LocalDate; import java.util.List; import java.util.Objects; public record GradingReportTemplateUpdate( - LocalDate validFrom, - @Nullable String note, - String failingGrade, - List gradeLimits, - List criteria) -{ + LocalDate validFrom, + @Nullable String note, + String failingGrade, + List gradeLimits, + List criteria +) { public GradingReportTemplateUpdate { Objects.requireNonNull(validFrom, "Valid from must not be null"); Objects.requireNonNull(failingGrade, "Failing grade must not be null"); @@ -22,9 +21,12 @@ public record GradingReportTemplateUpdate( for (GradeLimit gradeLimit1 : gradeLimits) { for (GradeLimit gradeLimit2 : gradeLimits) { if (gradeLimit1 != gradeLimit2 && gradeLimit1.minimumPoints() == gradeLimit2.minimumPoints()) { - throw new IllegalArgumentException("Duplicate minimum points on grades: %s and %s".formatted( - gradeLimit1.grade(), - gradeLimit2.grade())); + throw new IllegalArgumentException( + "Duplicate minimum points on grades: %s and %s".formatted( + gradeLimit1.grade(), + gradeLimit2.grade() + ) + ); } } } @@ -37,14 +39,20 @@ public record GradingReportTemplateUpdate( } public record Criteria( - LocalizedString title, - Type type, - int minimumPointsRequiredToPass, - @Nullable Flag flag, - List requirements) - { - public enum Type {THESIS, INDIVIDUAL} - public enum Flag {OPPOSITION, REFLECTION} + LocalizedString title, + Type type, + int minimumPointsRequiredToPass, + @Nullable Flag flag, + List requirements + ) { + public enum Type { + THESIS, + INDIVIDUAL, + } + public enum Flag { + OPPOSITION, + REFLECTION, + } public Criteria { Objects.requireNonNull(title, "Title must not be null"); diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingService.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingService.java index 6172f3c280..e8e6cbf91c 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.util.Either; - import java.io.InputStream; import java.time.LocalDate; import java.util.*; +import se.su.dsv.scipro.util.Either; public interface GradingService { /** @@ -14,11 +13,30 @@ public interface GradingService { Either> getResult(String token, long projectId, long authorId, long examinationId); - Either reportGrade(String token, long projectId, long authorId, int examinationId, String grade, LocalDate reported); + Either reportGrade( + String token, + long projectId, + long authorId, + int examinationId, + String grade, + LocalDate reported + ); - Either sendProtocol(String token, long projectId, long authorId, int examinationId, byte[] data, String contentType); + Either sendProtocol( + String token, + long projectId, + long authorId, + int examinationId, + byte[] data, + String contentType + ); - Either sendTextMatchingDocument(String token, long projectId, InputStream data, String contentType); + Either sendTextMatchingDocument( + String token, + long projectId, + InputStream data, + String contentType + ); boolean hasTextMatchingDocument(String token, long projectId); } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingServiceImpl.java index efd271ba90..ac6633a11f 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingServiceImpl.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.grading; -import org.glassfish.jersey.jackson.JacksonFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.util.Either; - import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.client.Client; @@ -16,6 +11,10 @@ import jakarta.ws.rs.core.Response; import java.io.InputStream; import java.time.LocalDate; import java.util.*; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import se.su.dsv.scipro.util.Either; public class GradingServiceImpl implements GradingService { @@ -28,46 +27,51 @@ public class GradingServiceImpl implements GradingService { public GradingServiceImpl(@Named("service.grading.url") final String url) { this.url = url; - this.client = ClientBuilder.newBuilder() - .register(JacksonFeature.class) - .build(); + this.client = ClientBuilder.newBuilder().register(JacksonFeature.class).build(); } @Override public List getExaminations(final String token, final long projectId, final long authorId) { final WebTarget client = service(); final Response response = client - .path("thesis").path(Long.toString(projectId)) - .path("author").path(Long.toString(authorId)) - .request() - .header("Authorization", "Bearer " + token) - .get(); + .path("thesis") + .path(Long.toString(projectId)) + .path("author") + .path(Long.toString(authorId)) + .request() + .header("Authorization", "Bearer " + token) + .get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(EXAMINATION_LIST); - } - else { + } else { return null; } } @Override - public Either> getResult(final String token, final long projectId, final long authorId, final long examinationId) { + public Either> getResult( + final String token, + final long projectId, + final long authorId, + final long examinationId + ) { final WebTarget client = service(); final Response response = client - .path("thesis").path(Long.toString(projectId)) - .path("author").path(Long.toString(authorId)) - .path("examination").path(Long.toString(examinationId)) - .request() - .header("Authorization", "Bearer " + token) - .get(); + .path("thesis") + .path(Long.toString(projectId)) + .path("author") + .path(Long.toString(authorId)) + .path("examination") + .path(Long.toString(examinationId)) + .request() + .header("Authorization", "Bearer " + token) + .get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { final Result result = response.readEntity(Result.class); return Either.right(Optional.of(result)); - } - else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) { + } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) { return Either.right(Optional.empty()); - } - else { + } else { final GetGradeError getGradeError = response.readEntity(GetGradeError.class); return Either.left(getGradeError); } @@ -75,59 +79,75 @@ public class GradingServiceImpl implements GradingService { @Override public Either reportGrade( - final String token, - final long projectId, - final long authorId, - final int examinationId, - final String grade, - final LocalDate reported) - { + final String token, + final long projectId, + final long authorId, + final int examinationId, + final String grade, + final LocalDate reported + ) { final Response response = service() - .path("thesis").path(Long.toString(projectId)) - .path("author").path(Long.toString(authorId)) - .path("examination").path(Long.toString(examinationId)) - .request() - .header("Authorization", "Bearer " + token) - .post(Entity.json(new ReportGradeRequest(grade, reported))); + .path("thesis") + .path(Long.toString(projectId)) + .path("author") + .path(Long.toString(authorId)) + .path("examination") + .path(Long.toString(examinationId)) + .request() + .header("Authorization", "Bearer " + token) + .post(Entity.json(new ReportGradeRequest(grade, reported))); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return Either.right(null); - } - else { + } else { final ReportGradeError error = response.readEntity(ReportGradeError.class); return Either.left(error); } } @Override - public Either sendProtocol(final String token, final long projectId, final long authorId, final int examinationId, final byte[] data, final String contentType) { + public Either sendProtocol( + final String token, + final long projectId, + final long authorId, + final int examinationId, + final byte[] data, + final String contentType + ) { final Response response = service() - .path("thesis").path(Long.toString(projectId)) - .path("author").path(Long.toString(authorId)) - .path("examination").path(Long.toString(examinationId)) - .path("protocol") - .request() - .header("Authorization", "Bearer " + token) - .post(Entity.entity(data, contentType)); + .path("thesis") + .path(Long.toString(projectId)) + .path("author") + .path(Long.toString(authorId)) + .path("examination") + .path(Long.toString(examinationId)) + .path("protocol") + .request() + .header("Authorization", "Bearer " + token) + .post(Entity.entity(data, contentType)); if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { return Either.right(null); - } - else { + } else { return Either.left(UploadProtocolError.ANY_ERROR); } } @Override - public Either sendTextMatchingDocument(final String token, final long projectId, final InputStream data, final String contentType) { + public Either sendTextMatchingDocument( + final String token, + final long projectId, + final InputStream data, + final String contentType + ) { final Response response = service() - .path("thesis").path(Long.toString(projectId)) - .path("plagiarism") - .request() - .header("Authorization", "Bearer " + token) - .post(Entity.entity(data, contentType)); + .path("thesis") + .path(Long.toString(projectId)) + .path("plagiarism") + .request() + .header("Authorization", "Bearer " + token) + .post(Entity.entity(data, contentType)); if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { return Either.right(null); - } - else { + } else { LOG.info(response.readEntity(String.class)); return Either.left(UploadTextMatchingError.ANY_ERROR); } @@ -136,16 +156,16 @@ public class GradingServiceImpl implements GradingService { @Override public boolean hasTextMatchingDocument(final String token, final long projectId) { final Response response = service() - .path("thesis").path(Long.toString(projectId)) - .path("plagiarism") - .request() - .header("Authorization", "Bearer " + token) - .get(); + .path("thesis") + .path(Long.toString(projectId)) + .path("plagiarism") + .request() + .header("Authorization", "Bearer " + token) + .get(); return response.getStatus() == Response.Status.OK.getStatusCode(); } private WebTarget service() { - return this.client - .target(url); + return this.client.target(url); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/GradingTypeConverter.java b/core/src/main/java/se/su/dsv/scipro/grading/GradingTypeConverter.java index 3cf27b3810..97593806d3 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/GradingTypeConverter.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/GradingTypeConverter.java @@ -5,10 +5,10 @@ import com.fasterxml.jackson.core.JsonTokenId; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.exc.InvalidFormatException; - import java.io.IOException; public class GradingTypeConverter extends JsonDeserializer { + @Override public Grade.Type deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { if (p.currentTokenId() == JsonTokenId.ID_STRING) { diff --git a/core/src/main/java/se/su/dsv/scipro/grading/Name.java b/core/src/main/java/se/su/dsv/scipro/grading/Name.java index 4bcc9f9d0b..718f353959 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/Name.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/Name.java @@ -2,8 +2,4 @@ package se.su.dsv.scipro.grading; import com.fasterxml.jackson.annotation.JsonProperty; -public record Name( - @JsonProperty("swedish") String swedish, - @JsonProperty("english") String english) -{ -} +public record Name(@JsonProperty("swedish") String swedish, @JsonProperty("english") String english) {} diff --git a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategory.java b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategory.java index c2ec2aa67e..6acc02f73c 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategory.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategory.java @@ -6,12 +6,12 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Table; - import java.util.Objects; @Entity @Table(name = "national_subject_category") public class NationalSubjectCategory { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -43,8 +43,7 @@ public class NationalSubjectCategory { // ---------------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------------- - public NationalSubjectCategory() { - } + public NationalSubjectCategory() {} // ---------------------------------------------------------------------------------- // Properties (Getters and Setters) @@ -111,11 +110,13 @@ public class NationalSubjectCategory { if (this.id != null) { return Objects.equals(this.id, that.id); } - return Objects.equals(this.externalId, that.externalId) - && Objects.equals(this.swedishName, that.swedishName) - && Objects.equals(this.englishName, that.englishName) - && Objects.equals(this.active, that.active) - && Objects.equals(this.preselected, that.preselected); + return ( + Objects.equals(this.externalId, that.externalId) && + Objects.equals(this.swedishName, that.swedishName) && + Objects.equals(this.englishName, that.englishName) && + Objects.equals(this.active, that.active) && + Objects.equals(this.preselected, that.preselected) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryRepositoryImpl.java index 90c2723739..06a435f102 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryRepositoryImpl.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.grading; -import jakarta.transaction.Transactional; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.List; import java.util.Optional; +import se.su.dsv.scipro.system.AbstractRepository; public class NationalSubjectCategoryRepositoryImpl - extends AbstractRepository - implements NationalSubjectCategoryRepository -{ + extends AbstractRepository + implements NationalSubjectCategoryRepository { + @Inject public NationalSubjectCategoryRepositoryImpl(Provider em) { super(em); @@ -24,8 +23,7 @@ public class NationalSubjectCategoryRepositoryImpl EntityManager entityManager = em(); if (entityManager.contains(nationalSubjectCategory)) { entityManager.merge(nationalSubjectCategory); - } - else { + } else { entityManager.persist(nationalSubjectCategory); } } @@ -33,16 +31,16 @@ public class NationalSubjectCategoryRepositoryImpl @Override public Optional findByExternalId(Integer externalId) { NationalSubjectCategory nationalSubjectCategory = from(QNationalSubjectCategory.nationalSubjectCategory) - .where(QNationalSubjectCategory.nationalSubjectCategory.externalId.eq(externalId)) - .select(QNationalSubjectCategory.nationalSubjectCategory) - .fetchOne(); + .where(QNationalSubjectCategory.nationalSubjectCategory.externalId.eq(externalId)) + .select(QNationalSubjectCategory.nationalSubjectCategory) + .fetchOne(); return Optional.ofNullable(nationalSubjectCategory); } @Override public List findAll() { return from(QNationalSubjectCategory.nationalSubjectCategory) - .select(QNationalSubjectCategory.nationalSubjectCategory) - .fetch(); + .select(QNationalSubjectCategory.nationalSubjectCategory) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryServiceImpl.java index dbb34d8bd1..921c83860e 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/NationalSubjectCategoryServiceImpl.java @@ -4,9 +4,8 @@ import jakarta.inject.Inject; import java.util.List; import java.util.Optional; -public class NationalSubjectCategoryServiceImpl - implements NationalSubjectCategoryService -{ +public class NationalSubjectCategoryServiceImpl implements NationalSubjectCategoryService { + private final NationalSubjectCategoryRepository nationalSubjectCategoryRepository; @Inject diff --git a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadata.java b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadata.java index 2fe7236e6c..a739738a13 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadata.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadata.java @@ -10,13 +10,13 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; - import java.util.Objects; +import se.su.dsv.scipro.project.Project; @Entity @Table(name = "publication_metadata") public class PublicationMetadata { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -46,7 +46,7 @@ public class PublicationMetadata { // ---------------------------------------------------------------------------------- @ManyToOne @JoinColumn(name = "national_subject_category_id") - private NationalSubjectCategory nationalSubjectCategory;; + private NationalSubjectCategory nationalSubjectCategory; @OneToOne(optional = false) @JoinColumn(name = "project_id") @@ -116,8 +116,7 @@ public class PublicationMetadata { // ---------------------------------------------------------------------------------- @Override public boolean equals(Object o) { - return o instanceof PublicationMetadata that && - Objects.equals(id, that.id); + return (o instanceof PublicationMetadata that && Objects.equals(id, that.id)); } @Override @@ -127,12 +126,28 @@ public class PublicationMetadata { @Override public String toString() { - return "PublicationMetadata{" + "id=" + id + ", project=" + project + - ", abstractSwedish='" + abstractSwedish + '\'' + - ", abstractEnglish='" + abstractEnglish + '\'' + - ", keywordsSwedish='" + keywordsSwedish + '\'' + - ", keywordsEnglish='" + keywordsEnglish + '\'' + - ", nationalSubjectCategory=" + nationalSubjectCategory + '\'' + - '}'; + return ( + "PublicationMetadata{" + + "id=" + + id + + ", project=" + + project + + ", abstractSwedish='" + + abstractSwedish + + '\'' + + ", abstractEnglish='" + + abstractEnglish + + '\'' + + ", keywordsSwedish='" + + keywordsSwedish + + '\'' + + ", keywordsEnglish='" + + keywordsEnglish + + '\'' + + ", nationalSubjectCategory=" + + nationalSubjectCategory + + '\'' + + '}' + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataRepositoryImpl.java index 503b62f6ec..3feb93ee35 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataRepositoryImpl.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.grading; -import jakarta.transaction.Transactional; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractRepository; public class PublicationMetadataRepositoryImpl extends AbstractRepository implements PublicationMetadataRepository { + @Inject public PublicationMetadataRepositoryImpl(Provider em) { super(em); @@ -20,8 +20,7 @@ public class PublicationMetadataRepositoryImpl extends AbstractRepository implem EntityManager entityManager = em(); if (entityManager.contains(publicationMetadata)) { entityManager.merge(publicationMetadata); - } - else { + } else { entityManager.persist(publicationMetadata); } } @@ -29,7 +28,7 @@ public class PublicationMetadataRepositoryImpl extends AbstractRepository implem @Override public PublicationMetadata findByProject(Project project) { return from(QPublicationMetadata.publicationMetadata) - .where(QPublicationMetadata.publicationMetadata.project.eq(project)) - .fetchOne(); + .where(QPublicationMetadata.publicationMetadata.project.eq(project)) + .fetchOne(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataServiceImpl.java index 684e24ae7b..5a504df56a 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataServiceImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.Language; - import jakarta.inject.Inject; import java.util.Objects; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Language; public class PublicationMetadataServiceImpl implements PublicationMetadataService { + private final PublicationMetadataRepository publicationMetadataRepository; @Inject @@ -34,13 +34,14 @@ public class PublicationMetadataServiceImpl implements PublicationMetadataServic @Override public boolean hasSuppliedPublicationMetadata(Project project, boolean noNationalSubjectCategoriesAvailable) { final PublicationMetadata metadata = getByProject(project); - return notBlank(metadata.getAbstractEnglish()) && - (project.getLanguage() == Language.ENGLISH || notBlank(metadata.getAbstractSwedish())) && - (noNationalSubjectCategoriesAvailable || metadata.getNationalSubjectCategory() != null); + return ( + notBlank(metadata.getAbstractEnglish()) && + (project.getLanguage() == Language.ENGLISH || notBlank(metadata.getAbstractSwedish())) && + (noNationalSubjectCategoriesAvailable || metadata.getNationalSubjectCategory() != null) + ); } private boolean notBlank(String s) { return s != null && !s.isBlank(); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/RejectionEvent.java b/core/src/main/java/se/su/dsv/scipro/grading/RejectionEvent.java index d7a24907e3..877e37e1db 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/RejectionEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/RejectionEvent.java @@ -11,10 +11,9 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import se.su.dsv.scipro.project.Project; - import java.time.Instant; import java.util.Objects; +import se.su.dsv.scipro.project.Project; @Entity @Table(name = "grading_history_rejection") @@ -84,11 +83,13 @@ public class RejectionEvent { @Override public boolean equals(Object o) { if (this == o) return true; - return o instanceof RejectionEvent that - && Objects.equals(id, that.id) - && Objects.equals(project, that.project) - && Objects.equals(when, that.when) - && Objects.equals(reason, that.reason); + return ( + o instanceof RejectionEvent that && + Objects.equals(id, that.id) && + Objects.equals(project, that.project) && + Objects.equals(when, that.when) && + Objects.equals(reason, that.reason) + ); } @Override @@ -98,11 +99,18 @@ public class RejectionEvent { @Override public String toString() { - return "RejectionEvent{" + - "id=" + id + - ", project=" + project + - ", when=" + when + - ", reason='" + reason + '\'' + - '}'; + return ( + "RejectionEvent{" + + "id=" + + id + + ", project=" + + project + + ", when=" + + when + + ", reason='" + + reason + + '\'' + + '}' + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeError.java b/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeError.java index 9d4b9eecae..ce07bf5c06 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeError.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeError.java @@ -9,5 +9,5 @@ public enum ReportGradeError { PUBLICATION_MISSING, REPORTED_IN_THE_FUTURE, TITLE_MISSING, - REPORTED_BEFORE_PROJECT_STARTED + REPORTED_BEFORE_PROJECT_STARTED, } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeRequest.java b/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeRequest.java index 49d3467f62..b9366f157f 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeRequest.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ReportGradeRequest.java @@ -2,11 +2,9 @@ package se.su.dsv.scipro.grading; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; - import java.time.LocalDate; public record ReportGradeRequest( - @JsonProperty("grade") String grade, - @JsonProperty("reported") @JsonFormat(pattern = "yyyy-MM-dd") LocalDate reported) -{ -} + @JsonProperty("grade") String grade, + @JsonProperty("reported") @JsonFormat(pattern = "yyyy-MM-dd") LocalDate reported +) {} diff --git a/core/src/main/java/se/su/dsv/scipro/grading/Result.java b/core/src/main/java/se/su/dsv/scipro/grading/Result.java index 5515b7b286..3d47beb63b 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/Result.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/Result.java @@ -3,12 +3,10 @@ package se.su.dsv.scipro.grading; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; - import java.time.LocalDate; @JsonIgnoreProperties(ignoreUnknown = true) public record Result( - @JsonProperty("grade") String letter, - @JsonProperty("reported") @JsonFormat(pattern = "yyyy-MM-dd") LocalDate reported) -{ -} + @JsonProperty("grade") String letter, + @JsonProperty("reported") @JsonFormat(pattern = "yyyy-MM-dd") LocalDate reported +) {} diff --git a/core/src/main/java/se/su/dsv/scipro/grading/SubmissionEvent.java b/core/src/main/java/se/su/dsv/scipro/grading/SubmissionEvent.java index fd88070c36..e56e191816 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/SubmissionEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/SubmissionEvent.java @@ -11,15 +11,15 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.time.Instant; import java.util.Objects; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "grading_history_submission") public class SubmissionEvent { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -96,12 +96,14 @@ public class SubmissionEvent { @Override public boolean equals(Object o) { if (this == o) return true; - return o instanceof SubmissionEvent that - && Objects.equals(id, that.id) - && Objects.equals(project, that.project) - && Objects.equals(author, that.author) - && Objects.equals(when, that.when) - && Objects.equals(corrections, that.corrections); + return ( + o instanceof SubmissionEvent that && + Objects.equals(id, that.id) && + Objects.equals(project, that.project) && + Objects.equals(author, that.author) && + Objects.equals(when, that.when) && + Objects.equals(corrections, that.corrections) + ); } @Override @@ -111,9 +113,20 @@ public class SubmissionEvent { @Override public String toString() { - return "RejectionEvent{" + "id=" + id + ", project=" + project + - ", author=" + author + ", when=" + when + - ", corrections='" + corrections + '\'' + - '}'; + return ( + "RejectionEvent{" + + "id=" + + id + + ", project=" + + project + + ", author=" + + author + + ", when=" + + when + + ", corrections='" + + corrections + + '\'' + + '}' + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedHistoryService.java b/core/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedHistoryService.java index 557d7eb16e..f3372806f5 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedHistoryService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedHistoryService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; - import java.time.Instant; +import se.su.dsv.scipro.project.Project; public interface ThesisApprovedHistoryService { void addApproved(Project project, Instant when); diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ThesisRejectionHistoryService.java b/core/src/main/java/se/su/dsv/scipro/grading/ThesisRejectionHistoryService.java index 74c44dd9fe..b83bc0e199 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ThesisRejectionHistoryService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ThesisRejectionHistoryService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.project.Project; - import java.time.Instant; +import se.su.dsv.scipro.project.Project; public interface ThesisRejectionHistoryService { void addRejection(Project project, String reason, Instant when); diff --git a/core/src/main/java/se/su/dsv/scipro/grading/ThesisSubmissionHistoryService.java b/core/src/main/java/se/su/dsv/scipro/grading/ThesisSubmissionHistoryService.java index b9fd8aabe9..b825b2ce84 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/ThesisSubmissionHistoryService.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/ThesisSubmissionHistoryService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.grading; +import java.time.Instant; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.time.Instant; - public interface ThesisSubmissionHistoryService { void addInitialSubmission(Project project, User author, Instant when); diff --git a/core/src/main/java/se/su/dsv/scipro/grading/UploadProtocolError.java b/core/src/main/java/se/su/dsv/scipro/grading/UploadProtocolError.java index fe9c259b2c..f647c3ed7b 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/UploadProtocolError.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/UploadProtocolError.java @@ -1,5 +1,5 @@ package se.su.dsv.scipro.grading; public enum UploadProtocolError { - ANY_ERROR + ANY_ERROR, } diff --git a/core/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingError.java b/core/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingError.java index 0ae664fb79..d9c224126e 100644 --- a/core/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingError.java +++ b/core/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingError.java @@ -1,5 +1,5 @@ package se.su.dsv.scipro.grading; public enum UploadTextMatchingError { - ANY_ERROR + ANY_ERROR, } diff --git a/core/src/main/java/se/su/dsv/scipro/group/Group.java b/core/src/main/java/se/su/dsv/scipro/group/Group.java index 11aecf59e8..66a9723c26 100644 --- a/core/src/main/java/se/su/dsv/scipro/group/Group.java +++ b/core/src/main/java/se/su/dsv/scipro/group/Group.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.group; -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.*; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "project_group") @@ -49,9 +48,11 @@ public class Group extends DomainObject { // @ManyToMany JPA-mappings // ---------------------------------------------------------------------------------- @ManyToMany - @JoinTable(name = "project_group_project", - joinColumns = @JoinColumn(name = "project_group_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id")) + @JoinTable( + name = "project_group_project", + joinColumns = @JoinColumn(name = "project_group_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id") + ) private Set projects = new HashSet<>(); // ---------------------------------------------------------------------------------- @@ -114,8 +115,7 @@ public class Group extends DomainObject { if (o == this) return true; if (!(o instanceof Group)) return false; final Group other = (Group) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -125,9 +125,21 @@ public class Group extends DomainObject { @Override public String toString() { - return "Group(id=" + this.getId() + ", title=" + this.getTitle() + ", description=" + - this.getDescription() + ", user=" + this.getUser() + ", projects=" + - this.getProjects() + ", active=" + this.isActive() + ")"; + return ( + "Group(id=" + + this.getId() + + ", title=" + + this.getTitle() + + ", description=" + + this.getDescription() + + ", user=" + + this.getUser() + + ", projects=" + + this.getProjects() + + ", active=" + + this.isActive() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -147,9 +159,10 @@ public class Group extends DomainObject { } public List getMembers() { - return projects.stream() - .flatMap(project -> project.getMembers().stream()) - .filter(member -> member.getType() != Member.Type.REVIEWER) - .toList(); + return projects + .stream() + .flatMap(project -> project.getMembers().stream()) + .filter(member -> member.getType() != Member.Type.REVIEWER) + .toList(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/group/GroupFacade.java b/core/src/main/java/se/su/dsv/scipro/group/GroupFacade.java index 8ed4192533..7ab796d08d 100644 --- a/core/src/main/java/se/su/dsv/scipro/group/GroupFacade.java +++ b/core/src/main/java/se/su/dsv/scipro/group/GroupFacade.java @@ -4,5 +4,4 @@ import se.su.dsv.scipro.system.User; public interface GroupFacade { boolean isSupervisorOrFollower(final Group group, final User user); - } diff --git a/core/src/main/java/se/su/dsv/scipro/group/GroupFacadeImpl.java b/core/src/main/java/se/su/dsv/scipro/group/GroupFacadeImpl.java index 49fc6ed36e..640aa7eb62 100755 --- a/core/src/main/java/se/su/dsv/scipro/group/GroupFacadeImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/group/GroupFacadeImpl.java @@ -7,15 +7,14 @@ public class GroupFacadeImpl implements GroupFacade { @Override public boolean isSupervisorOrFollower(final Group group, final User user) { - if (group.getUser().equals(user)){ + if (group.getUser().equals(user)) { return true; } - for (Project project : group.getProjects()){ + for (Project project : group.getProjects()) { if (project.getHeadSupervisor().equals(user) || project.getCoSupervisors().contains(user)) { return true; } } return false; } - -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/group/GroupService.java b/core/src/main/java/se/su/dsv/scipro/group/GroupService.java index 8b6e67b192..9c73a665e1 100755 --- a/core/src/main/java/se/su/dsv/scipro/group/GroupService.java +++ b/core/src/main/java/se/su/dsv/scipro/group/GroupService.java @@ -1,19 +1,18 @@ package se.su.dsv.scipro.group; +import java.io.Serializable; +import java.util.List; +import java.util.Objects; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.FilteredService; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; -import java.io.Serializable; -import java.util.List; -import java.util.Objects; - public interface GroupService extends GenericService, FilteredService { - List findAll(final Filter filter); class Filter implements Serializable { + private User author; private User creator; private User nonAuthorInvolvee; @@ -65,12 +64,14 @@ public interface GroupService extends GenericService, FilteredServi if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getAuthor(), other.getAuthor()) - && Objects.equals(this.getCreator(), other.getCreator()) - && Objects.equals(this.getNonAuthorInvolvee(), other.getNonAuthorInvolvee()) - && Objects.equals(this.getActive(), other.getActive()) - && Objects.equals(this.getProject(), other.getProject()); + return ( + other.canEqual(this) && + Objects.equals(this.getAuthor(), other.getAuthor()) && + Objects.equals(this.getCreator(), other.getCreator()) && + Objects.equals(this.getNonAuthorInvolvee(), other.getNonAuthorInvolvee()) && + Objects.equals(this.getActive(), other.getActive()) && + Objects.equals(this.getProject(), other.getProject()) + ); } protected boolean canEqual(final Object other) { @@ -79,12 +80,30 @@ public interface GroupService extends GenericService, FilteredServi @Override public int hashCode() { - return Objects.hash(this.getAuthor(), this.getCreator(), this.getNonAuthorInvolvee(), this.getActive(), this.getProject()); + return Objects.hash( + this.getAuthor(), + this.getCreator(), + this.getNonAuthorInvolvee(), + this.getActive(), + this.getProject() + ); } @Override public String toString() { - return "GroupService.Filter(author=" + this.getAuthor() + ", creator=" + this.getCreator() + ", nonAuthorInvolvee=" + this.getNonAuthorInvolvee() + ", active=" + this.getActive() + ", project=" + this.getProject() + ")"; + return ( + "GroupService.Filter(author=" + + this.getAuthor() + + ", creator=" + + this.getCreator() + + ", nonAuthorInvolvee=" + + this.getNonAuthorInvolvee() + + ", active=" + + this.getActive() + + ", project=" + + this.getProject() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/group/GroupServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/group/GroupServiceImpl.java index 0eae8d41e7..e2a5101be8 100755 --- a/core/src/main/java/se/su/dsv/scipro/group/GroupServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/group/GroupServiceImpl.java @@ -2,37 +2,37 @@ package se.su.dsv.scipro.group; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.FilteredService; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.FilteredService; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.User; -public class GroupServiceImpl extends AbstractServiceImpl implements GroupService, FilteredService { +public class GroupServiceImpl + extends AbstractServiceImpl + implements GroupService, FilteredService { @Inject public GroupServiceImpl(Provider em) { super(em, Group.class, QGroup.group); } - private BooleanBuilder fromParams(GroupService.Filter params) { BooleanBuilder bb = new BooleanBuilder(); - if (params.getAuthor() != null){ + if (params.getAuthor() != null) { bb.and(hasAuthor(params.getAuthor())); } - if (params.getCreator() != null){ + if (params.getCreator() != null) { bb.and(isCreator(params.getCreator())); } - if (params.getNonAuthorInvolvee() != null){ + if (params.getNonAuthorInvolvee() != null) { bb.and(hasNonAuthorInvolvee(params.getNonAuthorInvolvee())); } - if (params.getActive() != null){ + if (params.getActive() != null) { bb.and(isActive(params.getActive())); } if (params.getProject() != null) { @@ -58,9 +58,10 @@ public class GroupServiceImpl extends AbstractServiceImpl implement } private BooleanExpression hasNonAuthorInvolvee(final User user) { - return QGroup.group.user.eq(user) - .or(QGroup.group.projects.any().headSupervisor.eq(user)) - .or(QGroup.group.projects.any().coSupervisors.any().eq(user)); + return QGroup.group.user + .eq(user) + .or(QGroup.group.projects.any().headSupervisor.eq(user)) + .or(QGroup.group.projects.any().coSupervisors.any().eq(user)); } @Override @@ -77,4 +78,4 @@ public class GroupServiceImpl extends AbstractServiceImpl implement public List findAll(final Filter filter) { return findAll(fromParams(filter)); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminar.java b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminar.java index 7a34082b32..9202980470 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminar.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminar.java @@ -9,16 +9,15 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.Table; - -import se.su.dsv.scipro.activityplan.Activity; -import se.su.dsv.scipro.finalseminar.FinalSeminar; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.activityplan.Activity; +import se.su.dsv.scipro.finalseminar.FinalSeminar; @Entity @Table(name = "activity_final_seminar") class ActivityFinalSeminar { + // ---------------------------------------------------------------------------------- // embedded JPA-mappings // ---------------------------------------------------------------------------------- @@ -76,10 +75,12 @@ class ActivityFinalSeminar { if (o == this) return true; if (!(o instanceof ActivityFinalSeminar)) return false; final ActivityFinalSeminar other = (ActivityFinalSeminar) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getActivity(), other.getActivity()) - && Objects.equals(this.getFinalSeminar(), other.getFinalSeminar()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getActivity(), other.getActivity()) && + Objects.equals(this.getFinalSeminar(), other.getFinalSeminar()) + ); } @Override @@ -89,7 +90,15 @@ class ActivityFinalSeminar { @Override public String toString() { - return "ActivityFinalSeminar(id=" + this.getId() + ", activity=" + this.getActivity() + ", finalSeminar=" + this.getFinalSeminar() + ")"; + return ( + "ActivityFinalSeminar(id=" + + this.getId() + + ", activity=" + + this.getActivity() + + ", finalSeminar=" + + this.getFinalSeminar() + + ")" + ); } protected boolean canEqual(final Object other) { @@ -101,6 +110,7 @@ class ActivityFinalSeminar { // ---------------------------------------------------------------------------------- @Embeddable static class Id implements Serializable { + private Long activityId; private Long finalSeminarId; @@ -125,9 +135,11 @@ class ActivityFinalSeminar { if (o == this) return true; if (!(o instanceof Id)) return false; final Id other = (Id) o; - return other.canEqual(this) - && Objects.equals(this.getActivityId(), other.getActivityId()) - && Objects.equals(this.getFinalSeminarId(), other.getFinalSeminarId()); + return ( + other.canEqual(this) && + Objects.equals(this.getActivityId(), other.getActivityId()) && + Objects.equals(this.getFinalSeminarId(), other.getFinalSeminarId()) + ); } protected boolean canEqual(final Object other) { @@ -141,7 +153,13 @@ class ActivityFinalSeminar { @Override public String toString() { - return "ActivityFinalSeminar.Id(activityId=" + this.getActivityId() + ", finalSeminarId=" + this.getFinalSeminarId() + ")"; + return ( + "ActivityFinalSeminar.Id(activityId=" + + this.getActivityId() + + ", finalSeminarId=" + + this.getFinalSeminarId() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepository.java b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepository.java index 6f1af4098c..94fdbb7801 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepository.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.integration.activityfinalseminar; import jakarta.transaction.Transactional; +import java.util.Optional; +import se.su.dsv.scipro.finalseminar.FinalSeminar; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -import se.su.dsv.scipro.finalseminar.FinalSeminar; - -import java.util.Optional; @Transactional -public interface ActivityFinalSeminarRepository extends JpaRepository, QueryDslPredicateExecutor { +public interface ActivityFinalSeminarRepository + extends JpaRepository, QueryDslPredicateExecutor { Optional findByFinalSeminar(FinalSeminar finalSeminar); } diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepositoryImpl.java index a1f0317143..4d944e9123 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/ActivityFinalSeminarRepositoryImpl.java @@ -1,14 +1,15 @@ package se.su.dsv.scipro.integration.activityfinalseminar; -import se.su.dsv.scipro.finalseminar.FinalSeminar; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.finalseminar.FinalSeminar; +import se.su.dsv.scipro.system.GenericRepo; -public class ActivityFinalSeminarRepositoryImpl extends GenericRepo implements ActivityFinalSeminarRepository { +public class ActivityFinalSeminarRepositoryImpl + extends GenericRepo + implements ActivityFinalSeminarRepository { @Inject public ActivityFinalSeminarRepositoryImpl(Provider em) { diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandler.java b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandler.java index 5fe5f5149c..3537a2baec 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandler.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandler.java @@ -2,6 +2,9 @@ package se.su.dsv.scipro.integration.activityfinalseminar; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.*; import se.su.dsv.scipro.activityplan.Action; import se.su.dsv.scipro.activityplan.Activity; import se.su.dsv.scipro.activityplan.ActivityPlanFacade; @@ -11,10 +14,6 @@ import se.su.dsv.scipro.finalseminar.FinalSeminarCreatedEvent; import se.su.dsv.scipro.finalseminar.FinalSeminarDeletedEvent; import se.su.dsv.scipro.finalseminar.FinalSeminarMovedEvent; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import java.util.*; - @Singleton public class FinalSeminarActivityHandler { @@ -22,9 +21,11 @@ public class FinalSeminarActivityHandler { private final ActivityFinalSeminarRepository activityFinalSeminarRepository; @Inject - public FinalSeminarActivityHandler(final ActivityPlanFacade activityPlanFacade, - final ActivityFinalSeminarRepository activityFinalSeminarRepository, - final EventBus eventBus) { + public FinalSeminarActivityHandler( + final ActivityPlanFacade activityPlanFacade, + final ActivityFinalSeminarRepository activityFinalSeminarRepository, + final EventBus eventBus + ) { this.activityPlanFacade = activityPlanFacade; this.activityFinalSeminarRepository = activityFinalSeminarRepository; eventBus.register(this); @@ -32,7 +33,10 @@ public class FinalSeminarActivityHandler { @Subscribe public void finalSeminarMoved(FinalSeminarMovedEvent finalSeminarMovedEvent) { - synchronizeFinalSeminarActivity(finalSeminarMovedEvent.finalSeminar(), finalSeminarMovedEvent.finalSeminar().getStartDate()); + synchronizeFinalSeminarActivity( + finalSeminarMovedEvent.finalSeminar(), + finalSeminarMovedEvent.finalSeminar().getStartDate() + ); } @Subscribe @@ -42,24 +46,24 @@ public class FinalSeminarActivityHandler { } private void synchronizeFinalSeminarActivity(final FinalSeminar finalSeminar, final Date finalSeminarStartDate) { - final Optional optFinalSeminarActivity = activityFinalSeminarRepository.findByFinalSeminar(finalSeminar); + final Optional optFinalSeminarActivity = + activityFinalSeminarRepository.findByFinalSeminar(finalSeminar); if (optFinalSeminarActivity.isPresent()) { updateActivity(optFinalSeminarActivity.get().getActivity(), finalSeminar.getStartDate()); - } - else { + } else { createNewActivity(finalSeminar, finalSeminarStartDate); } } private void createNewActivity(final FinalSeminar finalSeminar, final Date finalSeminarStartDate) { - final Activity activity = Activity.builder(). - activityPlan(activityPlanFacade.retrieveActivityPlan(finalSeminar.getProject())). - date(finalSeminarStartDate). - name("Final seminar"). - description("Actual final seminar"). - editable(false). - build(); + final Activity activity = Activity.builder() + .activityPlan(activityPlanFacade.retrieveActivityPlan(finalSeminar.getProject())) + .date(finalSeminarStartDate) + .name("Final seminar") + .description("Actual final seminar") + .editable(false) + .build(); activity.setAction(Action.FINAL_SEMINAR); final Activity savedActivity = activityPlanFacade.saveActivity(activity); final ActivityFinalSeminar finalSeminarActivity = new ActivityFinalSeminar(savedActivity, finalSeminar); @@ -82,7 +86,8 @@ public class FinalSeminarActivityHandler { } private void removeActivity(final FinalSeminar finalSeminar) { - final Optional optFinalSeminarActivity = activityFinalSeminarRepository.findByFinalSeminar(finalSeminar); + final Optional optFinalSeminarActivity = + activityFinalSeminarRepository.findByFinalSeminar(finalSeminar); if (optFinalSeminarActivity.isPresent()) { ActivityFinalSeminar finalSeminarActivity = optFinalSeminarActivity.get(); @@ -90,4 +95,4 @@ public class FinalSeminarActivityHandler { activityPlanFacade.deleteActivity(finalSeminarActivity.getActivity()); } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThread.java b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThread.java index a890466fc5..279cf1fd61 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThread.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThread.java @@ -7,16 +7,15 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.Table; - -import se.su.dsv.scipro.activityplan.Activity; -import se.su.dsv.scipro.forum.dataobjects.ProjectThread; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.activityplan.Activity; +import se.su.dsv.scipro.forum.dataobjects.ProjectThread; @Entity @Table(name = "activity_thread") class ActivityThread { + // ---------------------------------------------------------------------------------- // basic and embedded JPA-mappings // ---------------------------------------------------------------------------------- @@ -71,10 +70,12 @@ class ActivityThread { if (o == this) return true; if (!(o instanceof ActivityThread)) return false; final ActivityThread other = (ActivityThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getThread(), other.getThread()) - && Objects.equals(this.getActivity(), other.getActivity()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getThread(), other.getThread()) && + Objects.equals(this.getActivity(), other.getActivity()) + ); } @Override @@ -84,7 +85,15 @@ class ActivityThread { @Override public String toString() { - return "ActivityThread(id=" + this.getId() + ", thread=" + this.getThread() + ", activity=" + this.getActivity() + ")"; + return ( + "ActivityThread(id=" + + this.getId() + + ", thread=" + + this.getThread() + + ", activity=" + + this.getActivity() + + ")" + ); } protected boolean canEqual(final Object other) { @@ -96,6 +105,7 @@ class ActivityThread { // ---------------------------------------------------------------------------------- @Embeddable static class Id implements Serializable { + private Long threadId; private Long activityId; @@ -120,9 +130,11 @@ class ActivityThread { if (o == this) return true; if (!(o instanceof Id)) return false; final Id other = (Id) o; - return other.canEqual(this) - && Objects.equals(this.getThreadId(), other.getThreadId()) - && Objects.equals(this.getActivityId(), other.getActivityId()); + return ( + other.canEqual(this) && + Objects.equals(this.getThreadId(), other.getThreadId()) && + Objects.equals(this.getActivityId(), other.getActivityId()) + ); } protected boolean canEqual(final Object other) { @@ -136,7 +148,7 @@ class ActivityThread { @Override public String toString() { - return "ActivityThread.Id(threadId=" + this.getThreadId() + ", activityId=" + this.getActivityId() + ")"; + return ("ActivityThread.Id(threadId=" + this.getThreadId() + ", activityId=" + this.getActivityId() + ")"); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepository.java b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepository.java index 55e19129cd..225eb91918 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.integration.activityforum; +import java.util.Optional; import se.su.dsv.scipro.activityplan.Activity; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; -import java.util.Optional; - public interface ActivityThreadRepository { Optional findByActivity(Activity activity); void save(ActivityThread activityThread); diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepositoryImpl.java index a161abb4a6..0594842fd7 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/ActivityThreadRepositoryImpl.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.integration.activityforum; import com.querydsl.jpa.impl.JPAQuery; -import se.su.dsv.scipro.activityplan.Activity; -import se.su.dsv.scipro.forum.dataobjects.ProjectThread; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.activityplan.Activity; +import se.su.dsv.scipro.forum.dataobjects.ProjectThread; public class ActivityThreadRepositoryImpl implements ActivityThreadRepository { + private final Provider entityManagerProvider; @Inject @@ -19,11 +19,13 @@ public class ActivityThreadRepositoryImpl implements ActivityThreadRepository { @Override public Optional findByActivity(final Activity activity) { - return Optional.ofNullable(new JPAQuery(entityManagerProvider.get()) + return Optional.ofNullable( + new JPAQuery(entityManagerProvider.get()) .select(QActivityThread.activityThread.thread) .from(QActivityThread.activityThread) .where(QActivityThread.activityThread.activity.eq(activity)) - .fetchOne()); + .fetchOne() + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForum.java b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForum.java index 07edadf118..ecb14239ec 100644 --- a/core/src/main/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForum.java +++ b/core/src/main/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForum.java @@ -2,6 +2,9 @@ package se.su.dsv.scipro.integration.activityforum; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.*; import se.su.dsv.scipro.activityplan.Activity; import se.su.dsv.scipro.activityplan.ActivityFileUploadedEvent; import se.su.dsv.scipro.file.FileDescription; @@ -10,19 +13,18 @@ import se.su.dsv.scipro.forum.ProjectForumService; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import java.util.*; - @Singleton public class PostActivityUploadToForum { + private final ProjectForumService projectForumService; private final ActivityThreadRepository activityThreadRepository; @Inject - public PostActivityUploadToForum(final ProjectForumService projectForumService, - final ActivityThreadRepository activityThreadRepository, - final EventBus eventBus) { + public PostActivityUploadToForum( + final ProjectForumService projectForumService, + final ActivityThreadRepository activityThreadRepository, + final EventBus eventBus + ) { this.projectForumService = projectForumService; this.activityThreadRepository = activityThreadRepository; eventBus.register(this); @@ -38,15 +40,20 @@ public class PostActivityUploadToForum { final Optional activityThread = activityThreadRepository.findByActivity(activity); if (activityThread.isPresent()) { final ProjectThread projectThread = activityThread.get(); - projectForumService.createReply(projectThread, fileDescription.getUploader(), activity.getDescription(), attachments); - } - else { + projectForumService.createReply( + projectThread, + fileDescription.getUploader(), + activity.getDescription(), + attachments + ); + } else { final ProjectThread thread = projectForumService.createThread( - activity.getActivityPlan().getProject(), - uploader, - activity.getTitle(), - activity.getDescription(), - attachments); + activity.getActivityPlan().getProject(), + uploader, + activity.getTitle(), + activity.getDescription(), + attachments + ); ActivityThread newActivityThread = new ActivityThread(thread, activity); activityThreadRepository.save(newActivityThread); } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/EmailRecipient.java b/core/src/main/java/se/su/dsv/scipro/mail/EmailRecipient.java index 1b9d26f81e..618f005da1 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/EmailRecipient.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/EmailRecipient.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.mail; import java.util.Objects; public class EmailRecipient implements Recipient { + private final String email; public EmailRecipient(final String email) { @@ -23,8 +24,7 @@ public class EmailRecipient implements Recipient { if (o == this) return true; if (!(o instanceof EmailRecipient)) return false; final EmailRecipient other = (EmailRecipient) o; - return other.canEqual(this) - && Objects.equals(this.getEmail(), other.getEmail()); + return (other.canEqual(this) && Objects.equals(this.getEmail(), other.getEmail())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/mail/Failure.java b/core/src/main/java/se/su/dsv/scipro/mail/Failure.java index 7c9ab81733..3b4cd3278f 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/Failure.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/Failure.java @@ -2,11 +2,11 @@ package se.su.dsv.scipro.mail; import jakarta.mail.SendFailedException; import jakarta.mail.internet.MimeMessage; +import java.util.*; import org.slf4j.Logger; -import java.util.*; - class Failure extends SMTPMailResult { + private final SendFailedException exception; public Failure(final MimeMessage message, final SendFailedException exception) { @@ -16,7 +16,9 @@ class Failure extends SMTPMailResult { @Override public void log(final Logger logger) { - logger.info("Failed to deliver the mail to all recipients. Specified recipients: " + Arrays.toString(getAllRecipients())); + logger.info( + "Failed to deliver the mail to all recipients. Specified recipients: " + Arrays.toString(getAllRecipients()) + ); if (exception.getValidSentAddresses() != null) { logger.info("Delivered to: " + Arrays.toString(exception.getValidSentAddresses())); } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/Mail.java b/core/src/main/java/se/su/dsv/scipro/mail/Mail.java index a41c528259..8080393a5d 100755 --- a/core/src/main/java/se/su/dsv/scipro/mail/Mail.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/Mail.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.mail; +import jakarta.inject.Inject; import jakarta.mail.Session; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; import se.su.dsv.scipro.file.FileService; -import jakarta.inject.Inject; - public class Mail extends SMTPMailer { @Inject diff --git a/core/src/main/java/se/su/dsv/scipro/mail/MailEvent.java b/core/src/main/java/se/su/dsv/scipro/mail/MailEvent.java index a8b99efd4d..3ef843f30c 100755 --- a/core/src/main/java/se/su/dsv/scipro/mail/MailEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/MailEvent.java @@ -1,18 +1,14 @@ package se.su.dsv.scipro.mail; -import jakarta.persistence.CollectionTable; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; +import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; @@ -20,16 +16,19 @@ import jakarta.persistence.Lob; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "mail_event") @Cacheable(false) public class MailEvent extends DomainObject { + public static final int STRING_MAX_LENGTH = 255; // ---------------------------------------------------------------------------------- @@ -76,25 +75,33 @@ public class MailEvent extends DomainObject { // @ManyToMany JPA-mappings // ---------------------------------------------------------------------------------- @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "mail_event_recipient", - joinColumns = @JoinColumn(name = "mail_event_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "recipient_id", referencedColumnName = "id")) + @JoinTable( + name = "mail_event_recipient", + joinColumns = @JoinColumn(name = "mail_event_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "recipient_id", referencedColumnName = "id") + ) private Set recipients = new HashSet<>(); @ElementCollection - @CollectionTable(name = "mail_event_non_user_recipient", - joinColumns = @JoinColumn(name = "mail_event_id", referencedColumnName = "id")) + @CollectionTable( + name = "mail_event_non_user_recipient", + joinColumns = @JoinColumn(name = "mail_event_id", referencedColumnName = "id") + ) @Column(name = "non_user_recipient") private Set nonUserRecipients = new HashSet<>(); // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public MailEvent() { - } + public MailEvent() {} - public MailEvent(final String subject, final String messageBody, final User recipient, final String fromName, - final String fromEmail) { + public MailEvent( + final String subject, + final String messageBody, + final User recipient, + final String fromName, + final String fromEmail + ) { this.subject = subject; this.messageBody = messageBody; this.recipients.add(recipient); @@ -102,8 +109,13 @@ public class MailEvent extends DomainObject { this.fromEmail = fromEmail; } - public MailEvent(final String subject, final String messageBody, final Collection recipients, - final String fromName, final String fromEmail) { + public MailEvent( + final String subject, + final String messageBody, + final Collection recipients, + final String fromName, + final String fromEmail + ) { this.subject = subject; this.messageBody = messageBody; this.recipients.addAll(recipients); @@ -203,8 +215,7 @@ public class MailEvent extends DomainObject { if (o == this) return true; if (!(o instanceof MailEvent)) return false; final MailEvent other = (MailEvent) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -214,12 +225,29 @@ public class MailEvent extends DomainObject { @Override public String toString() { - return "MailEvent(id=" + this.getId() + ", recipients=" + this.getRecipients() + - ", nonUserRecipients=" + this.getNonUserRecipients() + ", subject=" + - this.getSubject() + ", fromName=" + this.getFromName() + - ", fromEmail=" + this.getFromEmail() + ", messageBody=" + this.getMessageBody() + - ", sent=" + this.isSent() + ", messageID=" + this.getMessageID() + - ", attachment=" + this.getAttachment() + ")"; + return ( + "MailEvent(id=" + + this.getId() + + ", recipients=" + + this.getRecipients() + + ", nonUserRecipients=" + + this.getNonUserRecipients() + + ", subject=" + + this.getSubject() + + ", fromName=" + + this.getFromName() + + ", fromEmail=" + + this.getFromEmail() + + ", messageBody=" + + this.getMessageBody() + + ", sent=" + + this.isSent() + + ", messageID=" + + this.getMessageID() + + ", attachment=" + + this.getAttachment() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -231,17 +259,19 @@ public class MailEvent extends DomainObject { public void addRecipients(final Iterable recipients) { for (Recipient recipient : recipients) { - recipient.accept(new RecipientVisitor() { - @Override - public Boolean visit(final EmailRecipient emailRecipient) { - return getNonUserRecipients().add(emailRecipient.getEmail()); - } + recipient.accept( + new RecipientVisitor() { + @Override + public Boolean visit(final EmailRecipient emailRecipient) { + return getNonUserRecipients().add(emailRecipient.getEmail()); + } - @Override - public Boolean visit(final UserRecipient userRecipient) { - return getRecipients().add(userRecipient.getUser()); + @Override + public Boolean visit(final UserRecipient userRecipient) { + return getRecipients().add(userRecipient.getUser()); + } } - }); + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/MailEventService.java b/core/src/main/java/se/su/dsv/scipro/mail/MailEventService.java index c811fb702a..4d791ee279 100755 --- a/core/src/main/java/se/su/dsv/scipro/mail/MailEventService.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/MailEventService.java @@ -1,18 +1,18 @@ package se.su.dsv.scipro.mail; -import se.su.dsv.scipro.system.FilteredService; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.system.FilteredService; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.User; -public interface MailEventService extends GenericService, - FilteredService { +public interface MailEventService + extends GenericService, FilteredService { Iterable findUnsent(); class Filter implements Serializable { + private User user; private String subject; private Date sentAfter; @@ -55,11 +55,13 @@ public interface MailEventService extends GenericService, if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getSubject(), other.getSubject()) - && Objects.equals(this.getSentAfter(), other.getSentAfter()) - && Objects.equals(this.getSentBefore(), other.getSentBefore()); + return ( + other.canEqual(this) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getSubject(), other.getSubject()) && + Objects.equals(this.getSentAfter(), other.getSentAfter()) && + Objects.equals(this.getSentBefore(), other.getSentBefore()) + ); } protected boolean canEqual(final Object other) { @@ -73,8 +75,17 @@ public interface MailEventService extends GenericService, @Override public String toString() { - return "MailEventService.Filter(user=" + this.getUser() + ", subject=" + this.getSubject() + ", sentAfter=" + this.getSentAfter() + ", sentBefore=" + this.getSentBefore() + ")"; + return ( + "MailEventService.Filter(user=" + + this.getUser() + + ", subject=" + + this.getSubject() + + ", sentAfter=" + + this.getSentAfter() + + ", sentBefore=" + + this.getSentBefore() + + ")" + ); } } } - diff --git a/core/src/main/java/se/su/dsv/scipro/mail/MailEventServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/mail/MailEventServiceImpl.java index 93ffe55a60..3ec82255ca 100755 --- a/core/src/main/java/se/su/dsv/scipro/mail/MailEventServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/MailEventServiceImpl.java @@ -2,15 +2,15 @@ package se.su.dsv.scipro.mail; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; + +public class MailEventServiceImpl extends AbstractServiceImpl implements MailEventService { -public class MailEventServiceImpl extends AbstractServiceImpl implements MailEventService { @Inject public MailEventServiceImpl(Provider em) { super(em, MailEvent.class, QMailEvent.mailEvent); diff --git a/core/src/main/java/se/su/dsv/scipro/mail/MailEventWorker.java b/core/src/main/java/se/su/dsv/scipro/mail/MailEventWorker.java index c18364b1ad..347c3da80d 100755 --- a/core/src/main/java/se/su/dsv/scipro/mail/MailEventWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/MailEventWorker.java @@ -1,6 +1,9 @@ package se.su.dsv.scipro.mail; +import jakarta.inject.Inject; import jakarta.mail.MessagingException; +import java.util.*; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.file.FileDescription; @@ -9,10 +12,6 @@ import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import java.util.*; -import java.util.stream.Collectors; - public class MailEventWorker extends AbstractWorker { private static final Logger LOGGER = LoggerFactory.getLogger(MailEventWorker.class); @@ -22,9 +21,11 @@ public class MailEventWorker extends AbstractWorker { private final Mailer mailer; @Inject - public MailEventWorker(MailEventService mailEventService, - GeneralSystemSettingsService systemSettingsService, - Mailer mailer) { + public MailEventWorker( + MailEventService mailEventService, + GeneralSystemSettingsService systemSettingsService, + Mailer mailer + ) { this.mailEventService = mailEventService; this.systemSettingsService = systemSettingsService; this.mailer = mailer; @@ -52,23 +53,33 @@ public class MailEventWorker extends AbstractWorker { String fromName = Objects.requireNonNullElse(mailEvent.getFromName(), systemSettings.getMailFromName()); - String fromEmail = Objects.requireNonNullElse(mailEvent.getFromEmail(), systemSettings.getSystemFromMail()); + String fromEmail = Objects.requireNonNullElse( + mailEvent.getFromEmail(), + systemSettings.getSystemFromMail() + ); final String[] recipientsEmails = generateRecipients(mailEvent); final String messageBody = mailEvent.getMessageBody(); if (recipientsEmails.length > 0) { //Vanish if no notifications or empty - final FileDescription attachment = mailEvent.getAttachment() != null ? mailEvent.getAttachment().getFileDescription() : null; - MailResult mailResult = mailer.mail(fromName, fromEmail, recipientsEmails, subject, messageBody, attachment); + final FileDescription attachment = mailEvent.getAttachment() != null + ? mailEvent.getAttachment().getFileDescription() + : null; + MailResult mailResult = mailer.mail( + fromName, + fromEmail, + recipientsEmails, + subject, + messageBody, + attachment + ); mailResult.log(LOGGER); mailEvent.markSent(mailResult.getMessageID()); mailEventService.save(mailEvent); - } - else { + } else { mailEventService.delete(mailEvent); } this.commitTransaction(); - } catch (MessagingException e) { this.rollbackTransaction(); LOGGER.error("Messaging error", e); @@ -95,10 +106,11 @@ public class MailEventWorker extends AbstractWorker { return recipientsEmails; } - private Set filteredRecipients(Set input){ - return input.stream() - .filter(u -> !u.getEmailAddress().isBlank()) - .filter(u -> !u.isDeceased()) - .collect(Collectors.toSet()); + private Set filteredRecipients(Set input) { + return input + .stream() + .filter(u -> !u.getEmailAddress().isBlank()) + .filter(u -> !u.isDeceased()) + .collect(Collectors.toSet()); } } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/Mailer.java b/core/src/main/java/se/su/dsv/scipro/mail/Mailer.java index c0a2a9f544..9d58a0f2ca 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/Mailer.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/Mailer.java @@ -1,9 +1,15 @@ package se.su.dsv.scipro.mail; +import jakarta.mail.MessagingException; import se.su.dsv.scipro.file.FileDescription; -import jakarta.mail.MessagingException; - public interface Mailer { - MailResult mail(String fromName, String fromEmail, String[] recipients, String subject, String message, FileDescription attachment) throws MessagingException; + MailResult mail( + String fromName, + String fromEmail, + String[] recipients, + String subject, + String message, + FileDescription attachment + ) throws MessagingException; } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/PrintingMailer.java b/core/src/main/java/se/su/dsv/scipro/mail/PrintingMailer.java index 179bffc02c..36eeb50157 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/PrintingMailer.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/PrintingMailer.java @@ -1,14 +1,21 @@ package se.su.dsv.scipro.mail; -import org.slf4j.Logger; -import se.su.dsv.scipro.file.FileDescription; - import java.util.Arrays; import java.util.UUID; +import org.slf4j.Logger; +import se.su.dsv.scipro.file.FileDescription; public class PrintingMailer implements Mailer { + @Override - public MailResult mail(final String fromName, final String fromEmail, final String[] recipients, final String subject, final String message, final FileDescription attachment) { + public MailResult mail( + final String fromName, + final String fromEmail, + final String[] recipients, + final String subject, + final String message, + final FileDescription attachment + ) { return new MailResult() { final String messageID = UUID.randomUUID().toString(); diff --git a/core/src/main/java/se/su/dsv/scipro/mail/RedirectingMailer.java b/core/src/main/java/se/su/dsv/scipro/mail/RedirectingMailer.java index 80a790144e..427eca3af6 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/RedirectingMailer.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/RedirectingMailer.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.mail; +import jakarta.inject.Inject; import jakarta.mail.Session; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; import se.su.dsv.scipro.file.FileService; -import jakarta.inject.Inject; - public class RedirectingMailer extends SMTPMailer { + private final String redirectTo; @Inject @@ -18,6 +18,6 @@ public class RedirectingMailer extends SMTPMailer { @Override InternetAddress[] getRecipients(final String[] recipients) throws AddressException { - return new InternetAddress[]{new InternetAddress(redirectTo)}; + return new InternetAddress[] { new InternetAddress(redirectTo) }; } } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailResult.java b/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailResult.java index 035a9ec811..acd053d118 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailResult.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailResult.java @@ -5,6 +5,7 @@ import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; abstract class SMTPMailResult implements MailResult { + private final MimeMessage message; SMTPMailResult(final MimeMessage message) { @@ -27,5 +28,4 @@ abstract class SMTPMailResult implements MailResult { throw new RuntimeException(e); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailer.java b/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailer.java index 75442f2c1f..4146848588 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailer.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/SMTPMailer.java @@ -1,21 +1,20 @@ package se.su.dsv.scipro.mail; -import jakarta.mail.internet.MimeMessage; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileService; - import jakarta.activation.DataHandler; import jakarta.activation.DataSource; import jakarta.mail.*; import jakarta.mail.internet.AddressException; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeBodyPart; +import jakarta.mail.internet.MimeMessage; import jakarta.mail.internet.MimeMultipart; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Date; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileService; abstract class SMTPMailer implements Mailer { @@ -28,8 +27,14 @@ abstract class SMTPMailer implements Mailer { } @Override - public MailResult mail(String fromName, String fromEmail, String[] recipients, String subject, String message, final FileDescription attachment) throws MessagingException { - + public MailResult mail( + String fromName, + String fromEmail, + String[] recipients, + String subject, + String message, + final FileDescription attachment + ) throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setSentDate(new Date()); @@ -48,7 +53,7 @@ abstract class SMTPMailer implements Mailer { textBodyPart.setText(message, "UTF-8"); multipart.addBodyPart(textBodyPart); - if (attachment!=null){ + if (attachment != null) { MimeBodyPart fileBodyPart = new MimeBodyPart(); DataSource source = new DataSource() { @@ -83,8 +88,7 @@ abstract class SMTPMailer implements Mailer { try { Transport.send(msg); return new Success(msg); - } - catch (SendFailedException ex) { + } catch (SendFailedException ex) { return new Failure(msg, ex); } } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/Success.java b/core/src/main/java/se/su/dsv/scipro/mail/Success.java index 428b62cd9a..1df13b570b 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/Success.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/Success.java @@ -4,11 +4,11 @@ import jakarta.mail.internet.MimeMessage; import org.slf4j.Logger; class Success extends SMTPMailResult { + public Success(final MimeMessage message) { super(message); } @Override - public void log(final Logger logger) { - } + public void log(final Logger logger) {} } diff --git a/core/src/main/java/se/su/dsv/scipro/mail/UserRecipient.java b/core/src/main/java/se/su/dsv/scipro/mail/UserRecipient.java index cc1b31a83e..5f57df9d36 100644 --- a/core/src/main/java/se/su/dsv/scipro/mail/UserRecipient.java +++ b/core/src/main/java/se/su/dsv/scipro/mail/UserRecipient.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.mail; +import java.util.Objects; import se.su.dsv.scipro.system.User; -import java.util.Objects; - public class UserRecipient implements Recipient { + private final User user; public UserRecipient(final User user) { @@ -25,8 +25,7 @@ public class UserRecipient implements Recipient { if (o == this) return true; if (!(o instanceof UserRecipient)) return false; final UserRecipient other = (UserRecipient) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()); + return (other.canEqual(this) && Objects.equals(this.getUser(), other.getUser())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStart.java b/core/src/main/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStart.java index 3b75bea8d2..dccf244fce 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStart.java +++ b/core/src/main/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStart.java @@ -2,51 +2,48 @@ package se.su.dsv.scipro.match; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; -import se.su.dsv.scipro.activityplan.ActivityPlanFacade; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.ProjectModule; - import jakarta.inject.Inject; import java.time.Instant; import java.time.ZoneId; import java.util.Date; +import se.su.dsv.scipro.activityplan.ActivityPlanFacade; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.ProjectModule; public class AddActivityPlanOnProjectStart { - private final ActivityPlanFacade activityPlanFacade; - public AddActivityPlanOnProjectStart(final ActivityPlanFacade activityPlanFacade) { - this.activityPlanFacade = activityPlanFacade; - } + private final ActivityPlanFacade activityPlanFacade; - @Inject - public AddActivityPlanOnProjectStart(final ActivityPlanFacade activityPlanFacade, final EventBus eventBus) { - this(activityPlanFacade); - eventBus.register(this); - } + public AddActivityPlanOnProjectStart(final ActivityPlanFacade activityPlanFacade) { + this.activityPlanFacade = activityPlanFacade; + } - @Subscribe - public void projectStarted(ProjectStartedEvent event) { - final Idea idea = event.getIdea(); - final ApplicationPeriod applicationPeriod = idea.getApplicationPeriod(); - final Project project = idea.getProject(); + @Inject + public AddActivityPlanOnProjectStart(final ActivityPlanFacade activityPlanFacade, final EventBus eventBus) { + this(activityPlanFacade); + eventBus.register(this); + } - applicationPeriod.getApplicationPeriodProjectTypes() + @Subscribe + public void projectStarted(ProjectStartedEvent event) { + final Idea idea = event.getIdea(); + final ApplicationPeriod applicationPeriod = idea.getApplicationPeriod(); + final Project project = idea.getProject(); + + applicationPeriod + .getApplicationPeriodProjectTypes() .stream() .filter(appt -> appt.getProjectType() == project.getProjectType()) .findFirst() .map(ApplicationPeriodProjectType::getActivityPlanTemplate) .filter(appt -> project.hasModule(ProjectModule.ACTIVITY_PLAN)) - .ifPresent(template -> - { - final Instant courseStartDate = applicationPeriod - .getCourseStartDate() - .atTime(applicationPeriod.getCourseStartTime()) - .atZone(ZoneId.systemDefault()) - .toInstant(); - activityPlanFacade.addActivitiesFromTemplate( - project, - template, - Date.from(courseStartDate)); + .ifPresent(template -> { + final Instant courseStartDate = applicationPeriod + .getCourseStartDate() + .atTime(applicationPeriod.getCourseStartTime()) + .atZone(ZoneId.systemDefault()) + .toInstant(); + activityPlanFacade.addActivitiesFromTemplate(project, template, Date.from(courseStartDate)); }); - } + } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/AllowAllIdeaCreationJudge.java b/core/src/main/java/se/su/dsv/scipro/match/AllowAllIdeaCreationJudge.java index 6a91588ff1..fbdf982f26 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/AllowAllIdeaCreationJudge.java +++ b/core/src/main/java/se/su/dsv/scipro/match/AllowAllIdeaCreationJudge.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.match; public class AllowAllIdeaCreationJudge implements IdeaCreationJudge { + @Override public Decision ruling(Idea idea) { return Decision.allowed(); diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriod.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriod.java index d3c7a21e50..9dc48661d9 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriod.java @@ -1,12 +1,5 @@ package se.su.dsv.scipro.match; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; @@ -18,20 +11,25 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.ProjectType; @Entity @Cacheable(true) -@Table(name="application_period") +@Table(name = "application_period") public class ApplicationPeriod extends DomainObject { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade=CascadeType.ALL, orphanRemoval=true) + @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade = CascadeType.ALL, orphanRemoval = true) private Set projectTypes = new HashSet<>(); private String name; @@ -48,14 +46,13 @@ public class ApplicationPeriod extends DomainObject { @Column(name = "course_end_date") private LocalDate courseEndDate; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade=CascadeType.ALL, orphanRemoval=true) + @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade = CascadeType.ALL, orphanRemoval = true) private Set applicationPeriodExemptions = new HashSet<>(); - @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade=CascadeType.ALL, orphanRemoval=true) + @OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationPeriod", cascade = CascadeType.ALL, orphanRemoval = true) private Set targets = new HashSet<>(); - public ApplicationPeriod() { - } + public ApplicationPeriod() {} public ApplicationPeriod(String name) { this.name = name; @@ -69,23 +66,23 @@ public class ApplicationPeriod extends DomainObject { this.applicationPeriodExemptions = new HashSet<>(applicationPeriodExemptions); } - public void addApplicationPeriodExemption(final ApplicationPeriodExemption exemption){ + public void addApplicationPeriodExemption(final ApplicationPeriodExemption exemption) { applicationPeriodExemptions.add(exemption); } - public void removeApplicationPeriodExemption(final ApplicationPeriodExemption exemption){ + public void removeApplicationPeriodExemption(final ApplicationPeriodExemption exemption) { applicationPeriodExemptions.remove(exemption); } - public int noOfExemptions(){ + public int noOfExemptions() { return applicationPeriodExemptions.size(); } - public long noOfExemptedStudents(){ + public long noOfExemptedStudents() { return applicationPeriodExemptions.stream().map(ApplicationPeriodExemption::getUser).distinct().count(); } - public boolean hasApplicationPeriodExemptions(){ + public boolean hasApplicationPeriodExemptions() { return !applicationPeriodExemptions.isEmpty(); } @@ -135,12 +132,12 @@ public class ApplicationPeriod extends DomainObject { } public void setCourseStartDate(LocalDate courseStartDate) { - setCourseStartDateTime(courseStartDate.atTime(getCourseStartTime())); - } + setCourseStartDateTime(courseStartDate.atTime(getCourseStartTime())); + } - public LocalDate getCourseStartDate() { - return courseStartDateTime.toLocalDate(); - } + public LocalDate getCourseStartDate() { + return courseStartDateTime.toLocalDate(); + } public LocalDate getCourseEndDate() { return courseEndDate; @@ -159,9 +156,9 @@ public class ApplicationPeriod extends DomainObject { } @Override - public String toString() { - return name; - } + public String toString() { + return name; + } public boolean isOpen(final LocalDate now) { return !(now.isBefore(startDate) || now.isAfter(endDate)); @@ -173,7 +170,7 @@ public class ApplicationPeriod extends DomainObject { public Set getProjectTypes() { Set answerSet = new HashSet<>(); - for (ApplicationPeriodProjectType appt : getApplicationPeriodProjectTypes()){ + for (ApplicationPeriodProjectType appt : getApplicationPeriodProjectTypes()) { answerSet.add(appt.getProjectType()); } return Collections.unmodifiableSet(answerSet); @@ -181,7 +178,7 @@ public class ApplicationPeriod extends DomainObject { public void setProjectTypes(Iterable projectTypes) { this.projectTypes.clear(); - for (ProjectType pt : projectTypes){ + for (ProjectType pt : projectTypes) { this.projectTypes.add(new ApplicationPeriodProjectType(this, pt)); } } @@ -193,4 +190,4 @@ public class ApplicationPeriod extends DomainObject { public void removeProjectType(ProjectType projectType) { this.projectTypes.removeIf(next -> next.getProjectType().equals(projectType)); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemption.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemption.java index 82197dc73d..8df4af1ba6 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemption.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemption.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.match; -import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Objects; - import jakarta.persistence.AttributeOverride; import jakarta.persistence.Column; import jakarta.persistence.EmbeddedId; @@ -13,12 +8,16 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.Table; - +import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Objects; import se.su.dsv.scipro.system.User; @Entity @Table(name = "application_period_exemption") public class ApplicationPeriodExemption implements Serializable { + public enum Type { SUBMIT_STUDENT_IDEA(true), SELECT_SUPERVISOR_IDEA(true), @@ -128,7 +127,25 @@ public class ApplicationPeriodExemption implements Serializable { @Override public String toString() { - return "ApplicationPeriodExemption(applicationperiodexemptionId=" + this.getApplicationperiodexemptionId() + ", user=" + this.getUser() + ", applicationPeriod=" + this.getApplicationPeriod() + ", endDate=" + this.getEndDate() + ", comment=" + this.getComment() + ", grantedBy=" + this.getGrantedBy() + ", grantedOn=" + this.getGrantedOn() + ", type=" + this.getType() + ")"; + return ( + "ApplicationPeriodExemption(applicationperiodexemptionId=" + + this.getApplicationperiodexemptionId() + + ", user=" + + this.getUser() + + ", applicationPeriod=" + + this.getApplicationPeriod() + + ", endDate=" + + this.getEndDate() + + ", comment=" + + this.getComment() + + ", grantedBy=" + + this.getGrantedBy() + + ", grantedOn=" + + this.getGrantedOn() + + ", type=" + + this.getType() + + ")" + ); } @Override @@ -136,10 +153,12 @@ public class ApplicationPeriodExemption implements Serializable { if (o == this) return true; if (!(o instanceof ApplicationPeriodExemption)) return false; final ApplicationPeriodExemption other = (ApplicationPeriodExemption) o; - return other.canEqual(this) - && Objects.equals(this.getApplicationperiodexemptionId(), other.getApplicationperiodexemptionId()) - && Objects.equals(this.getEndDate(), other.getEndDate()) - && Objects.equals(this.getType(), other.getType()); + return ( + other.canEqual(this) && + Objects.equals(this.getApplicationperiodexemptionId(), other.getApplicationperiodexemptionId()) && + Objects.equals(this.getEndDate(), other.getEndDate()) && + Objects.equals(this.getType(), other.getType()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemptionId.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemptionId.java index 911d0d47d8..dd55fa38da 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemptionId.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodExemptionId.java @@ -9,6 +9,7 @@ import java.util.Objects; @Embeddable class ApplicationPeriodExemptionId implements Serializable { + @Basic private Long studentId; @@ -45,7 +46,15 @@ class ApplicationPeriodExemptionId implements Serializable { @Override public String toString() { - return "ApplicationPeriodExemptionId(studentId=" + this.getStudentId() + ", applicationPeriodId=" + this.getApplicationPeriodId() + ", exemptionType=" + this.getType() + ")"; + return ( + "ApplicationPeriodExemptionId(studentId=" + + this.getStudentId() + + ", applicationPeriodId=" + + this.getApplicationPeriodId() + + ", exemptionType=" + + this.getType() + + ")" + ); } @Override @@ -53,10 +62,12 @@ class ApplicationPeriodExemptionId implements Serializable { if (o == this) return true; if (!(o instanceof ApplicationPeriodExemptionId)) return false; final ApplicationPeriodExemptionId other = (ApplicationPeriodExemptionId) o; - return other.canEqual(this) - && Objects.equals(this.getStudentId(), other.getStudentId()) - && Objects.equals(this.getApplicationPeriodId(), other.getApplicationPeriodId()) - && Objects.equals(this.getType(), other.getType()); + return ( + other.canEqual(this) && + Objects.equals(this.getStudentId(), other.getStudentId()) && + Objects.equals(this.getApplicationPeriodId(), other.getApplicationPeriodId()) && + Objects.equals(this.getType(), other.getType()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacade.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacade.java index a45bb7493a..ef53bfdea5 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacade.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacade.java @@ -3,8 +3,6 @@ package se.su.dsv.scipro.match; import se.su.dsv.scipro.system.ProjectType; public interface ApplicationPeriodFacade { - int remainingTargets(ApplicationPeriod ap, ProjectType projectType); int totalTargets(ApplicationPeriod ap, ProjectType projectType); - } diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacadeImpl.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacadeImpl.java index 5edd84a832..899e0ef3b1 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacadeImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodFacadeImpl.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import se.su.dsv.scipro.reusable.SciProUtilities; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class ApplicationPeriodFacadeImpl implements ApplicationPeriodFacade { @Inject @@ -31,7 +30,6 @@ public class ApplicationPeriodFacadeImpl implements ApplicationPeriodFacade { total += ideaService.countMatched(ap, e, projectType); } } - return totalTargets(ap, projectType) - SciProUtilities.safeLongToInt(total); + return (totalTargets(ap, projectType) - SciProUtilities.safeLongToInt(total)); } - -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectType.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectType.java index eac5ccfbc2..83be7f857d 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectType.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectType.java @@ -1,19 +1,19 @@ package se.su.dsv.scipro.match; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.Table; -import se.su.dsv.scipro.activityplan.ActivityPlanTemplate; -import se.su.dsv.scipro.system.ProjectType; - import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; +import jakarta.persistence.Table; import java.io.Serializable; +import se.su.dsv.scipro.activityplan.ActivityPlanTemplate; +import se.su.dsv.scipro.system.ProjectType; @Entity @Table(name = "application_period_project_type") public class ApplicationPeriodProjectType implements Serializable { + @EmbeddedId private ApplicationPeriodProjectTypeId applicationPeriodProjectTypeId = new ApplicationPeriodProjectTypeId(); @@ -57,4 +57,4 @@ public class ApplicationPeriodProjectType implements Serializable { public void setActivityPlanTemplate(ActivityPlanTemplate activityPlanTemplate) { this.activityPlanTemplate = activityPlanTemplate; } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeId.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeId.java index 9082c95273..9bd0930140 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeId.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeId.java @@ -7,6 +7,7 @@ import java.util.Objects; @Embeddable class ApplicationPeriodProjectTypeId implements Serializable { + @Basic private Long applicationPeriodId; @@ -18,9 +19,11 @@ class ApplicationPeriodProjectTypeId implements Serializable { if (o == this) return true; if (!(o instanceof ApplicationPeriodProjectTypeId)) return false; final ApplicationPeriodProjectTypeId other = (ApplicationPeriodProjectTypeId) o; - return other.canEqual(this) - && Objects.equals(this.applicationPeriodId, other.applicationPeriodId) - && Objects.equals(this.projectTypeId, other.projectTypeId); + return ( + other.canEqual(this) && + Objects.equals(this.applicationPeriodId, other.applicationPeriodId) && + Objects.equals(this.projectTypeId, other.projectTypeId) + ); } protected boolean canEqual(final Object other) { @@ -31,4 +34,4 @@ class ApplicationPeriodProjectTypeId implements Serializable { public int hashCode() { return Objects.hash(this.applicationPeriodId, this.projectTypeId); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeService.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeService.java index aeddb333d4..a142a808d2 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeService.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.match; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.ProjectType; -public interface ApplicationPeriodProjectTypeService extends GenericService { +public interface ApplicationPeriodProjectTypeService + extends GenericService { ApplicationPeriodProjectType findOne(ApplicationPeriod applicationPeriod, ProjectType projectType); } diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeServiceImpl.java index aad6e262be..1f2de009fa 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodProjectTypeServiceImpl.java @@ -1,14 +1,16 @@ package se.su.dsv.scipro.match; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.ProjectType; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.ProjectType; + +public class ApplicationPeriodProjectTypeServiceImpl + extends AbstractServiceImpl + implements ApplicationPeriodProjectTypeService { -public class ApplicationPeriodProjectTypeServiceImpl extends AbstractServiceImpl implements ApplicationPeriodProjectTypeService { @Inject public ApplicationPeriodProjectTypeServiceImpl(Provider em) { super(em, ApplicationPeriodProjectType.class, QApplicationPeriodProjectType.applicationPeriodProjectType); diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodService.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodService.java index 392ea3cf8e..f4c672c731 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodService.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.match; +import java.util.Collection; +import java.util.List; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.Collection; -import java.util.List; - public interface ApplicationPeriodService extends GenericService { - List getCurrentPeriods(); + List getCurrentPeriods(); List getCurrentStudentPeriods(final User student); List getTypesForStudent(ApplicationPeriod applicationPeriod, User student); List getCurrentSupervisorPeriods(User supervisor); diff --git a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImpl.java index 29499c6f0c..74bd3c6256 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImpl.java @@ -1,28 +1,29 @@ package se.su.dsv.scipro.match; -import jakarta.transaction.Transactional; +import static com.querydsl.core.types.dsl.Expressions.allOf; +import static com.querydsl.core.types.dsl.Expressions.anyOf; + import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.time.Clock; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.Sort; +import se.su.dsv.scipro.system.User; -import static com.querydsl.core.types.dsl.Expressions.allOf; -import static com.querydsl.core.types.dsl.Expressions.anyOf; - -public class ApplicationPeriodServiceImpl extends AbstractServiceImpl implements ApplicationPeriodService { +public class ApplicationPeriodServiceImpl + extends AbstractServiceImpl + implements ApplicationPeriodService { private final Clock clock; @@ -47,15 +48,27 @@ public class ApplicationPeriodServiceImpl extends AbstractServiceImpl phs = new HashSet<>(getCurrentPeriods(currentDate)); QApplicationPeriodExemption exemption = QApplicationPeriodExemption.applicationPeriodExemption; final List currentExemptions = from(exemption) - .where(allOf(exemption.user.eq(student), anyOf(exemption.endDate.goe(currentDate), exemption.endDate.isNull()))) - .fetch(); - final Map> periodExemptions = currentExemptions.stream() - .collect(Collectors.groupingBy(ApplicationPeriodExemption::getApplicationPeriod, - Collectors.mapping(ApplicationPeriodExemption::getType, Collectors.toList()))); + .where( + allOf(exemption.user.eq(student), anyOf(exemption.endDate.goe(currentDate), exemption.endDate.isNull())) + ) + .fetch(); + final Map> periodExemptions = currentExemptions + .stream() + .collect( + Collectors.groupingBy( + ApplicationPeriodExemption::getApplicationPeriod, + Collectors.mapping(ApplicationPeriodExemption::getType, Collectors.toList()) + ) + ); final List studentPeriods = new ArrayList<>(); for (ApplicationPeriod openApplicationPeriod : phs) { - studentPeriods.add(new OpenPeriod(openApplicationPeriod, periodExemptions.getOrDefault(openApplicationPeriod, Collections.emptyList()))); + studentPeriods.add( + new OpenPeriod( + openApplicationPeriod, + periodExemptions.getOrDefault(openApplicationPeriod, Collections.emptyList()) + ) + ); } for (var entry : periodExemptions.entrySet()) { final ApplicationPeriod applicationPeriod = entry.getKey(); @@ -68,10 +81,13 @@ public class ApplicationPeriodServiceImpl extends AbstractServiceImpl exemptions) { - return exemptions.stream() - .anyMatch(exemptionType -> - exemptionType == ApplicationPeriodExemption.Type.SELECT_SUPERVISOR_IDEA - || exemptionType == ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA); + return exemptions + .stream() + .anyMatch( + exemptionType -> + exemptionType == ApplicationPeriodExemption.Type.SELECT_SUPERVISOR_IDEA || + exemptionType == ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA + ); } @Override @@ -79,46 +95,58 @@ public class ApplicationPeriodServiceImpl extends AbstractServiceImpl(applicationPeriod.getProjectTypes()); } else { - return applicationPeriod.getProjectTypes() - .stream() - .filter(projectType -> projectType.getDegreeType() == student.getDegreeType()) - .toList(); + return applicationPeriod + .getProjectTypes() + .stream() + .filter(projectType -> projectType.getDegreeType() == student.getDegreeType()) + .toList(); } } private boolean hasTypeExemption(ApplicationPeriod applicationPeriod, User student) { - return null != getExemptionForExemptionType(applicationPeriod, student, ApplicationPeriodExemption.Type.PROJECT_TYPE); + return ( + null != + getExemptionForExemptionType(applicationPeriod, student, ApplicationPeriodExemption.Type.PROJECT_TYPE) + ); } - private ApplicationPeriodExemption getExemptionForExemptionType(ApplicationPeriod applicationPeriod, User student, ApplicationPeriodExemption.Type type) { + private ApplicationPeriodExemption getExemptionForExemptionType( + ApplicationPeriod applicationPeriod, + User student, + ApplicationPeriodExemption.Type type + ) { final QApplicationPeriodExemption QApe = QApplicationPeriodExemption.applicationPeriodExemption; return from(QApe) - .where(allOf( - QApe.user.eq(student), - QApe.applicationPeriod.eq(applicationPeriod), - QApe.applicationperiodexemptionId.type.eq(type) - )) - .fetchOne(); + .where( + allOf( + QApe.user.eq(student), + QApe.applicationPeriod.eq(applicationPeriod), + QApe.applicationperiodexemptionId.type.eq(type) + ) + ) + .fetchOne(); } @Override public boolean hasIdeaSizeExemption(User student, ApplicationPeriod applicationPeriod) { - return null != getExemptionForExemptionType(applicationPeriod, student, ApplicationPeriodExemption.Type.NUMBER_OF_AUTHORS); + return ( + null != + getExemptionForExemptionType(applicationPeriod, student, ApplicationPeriodExemption.Type.NUMBER_OF_AUTHORS) + ); } @Override public List getCurrentSupervisorPeriods(final User supervisor) { LocalDateTime now = LocalDateTime.now(clock); - return findAll(Expressions.allOf( - startedBeforeOrAt(now.toLocalDate()), - courseStartAfterOrAt(now) - )); + return findAll(Expressions.allOf(startedBeforeOrAt(now.toLocalDate()), courseStartAfterOrAt(now))); } @Override public Collection getPreviousPeriods(ApplicationPeriod applicationPeriod, int limit) { - return findAll(endedBefore(applicationPeriod.getStartDate()), - new PageRequest(0, limit, new Sort(Sort.Direction.DESC, "startDate"))); + return findAll( + endedBefore(applicationPeriod.getStartDate()), + new PageRequest(0, limit, new Sort(Sort.Direction.DESC, "startDate")) + ); } private List getPreviousPeriodsByProjectType(ProjectType pc) { @@ -145,7 +173,6 @@ public class ApplicationPeriodServiceImpl extends AbstractServiceImpl fromNewPeriod, final Set fromOldPeriod) { for (ProjectType projectType : fromNewPeriod) { - if(fromOldPeriod.contains(projectType)) { + if (fromOldPeriod.contains(projectType)) { return true; } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/Decision.java b/core/src/main/java/se/su/dsv/scipro/match/Decision.java index 60e5c1a879..de81d47cf4 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/Decision.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Decision.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.match; public final class Decision { + private final boolean allowed; private final String reason; private final Integer identifier; private Decision(final boolean allowed, final String reason, Integer identifier) { - this.allowed = allowed; this.reason = reason; this.identifier = identifier; diff --git a/core/src/main/java/se/su/dsv/scipro/match/ExemptedPeriod.java b/core/src/main/java/se/su/dsv/scipro/match/ExemptedPeriod.java index 0a1f0fead1..43db4f3934 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ExemptedPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ExemptedPeriod.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Objects; public final class ExemptedPeriod extends StudentPeriod implements Serializable { + private final ApplicationPeriod applicationPeriod; private final List exemptions; @@ -34,7 +35,7 @@ public final class ExemptedPeriod extends StudentPeriod implements Serializable @Override public String toString() { - return "ExemptedPeriod(applicationPeriod=" + this.getApplicationPeriod() + ")"; + return ("ExemptedPeriod(applicationPeriod=" + this.getApplicationPeriod() + ")"); } @Override @@ -42,8 +43,10 @@ public final class ExemptedPeriod extends StudentPeriod implements Serializable if (o == this) return true; if (!(o instanceof ExemptedPeriod)) return false; final ExemptedPeriod other = (ExemptedPeriod) o; - return Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) - && Objects.equals(this.exemptions, other.exemptions); + return ( + Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) && + Objects.equals(this.exemptions, other.exemptions) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/match/FirstMeeting.java b/core/src/main/java/se/su/dsv/scipro/match/FirstMeeting.java index 4367c24d73..675a212648 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/FirstMeeting.java +++ b/core/src/main/java/se/su/dsv/scipro/match/FirstMeeting.java @@ -10,7 +10,6 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.io.Serializable; import java.util.Date; import java.util.Objects; @@ -19,6 +18,7 @@ import java.util.Objects; @Table(name = "idea_first_meeting") @Cacheable(true) public class FirstMeeting implements Serializable { + private static final int LENGTH = 1024; // ---------------------------------------------------------------------------------- @@ -51,7 +51,7 @@ public class FirstMeeting implements Serializable { // ---------------------------------------------------------------------------------- // constructors // ---------------------------------------------------------------------------------- - public FirstMeeting() { } + public FirstMeeting() {} public FirstMeeting(Date firstMeetingDate, Idea idea) { this.firstMeetingDate = firstMeetingDate; @@ -110,12 +110,14 @@ public class FirstMeeting implements Serializable { if (o == this) return true; if (!(o instanceof FirstMeeting)) return false; final FirstMeeting other = (FirstMeeting) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getFirstMeetingDate(), other.getFirstMeetingDate()) - && Objects.equals(this.getRoom(), other.getRoom()) - && Objects.equals(this.getDescription(), other.getDescription()) - && Objects.equals(this.getIdea(), other.getIdea()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getFirstMeetingDate(), other.getFirstMeetingDate()) && + Objects.equals(this.getRoom(), other.getRoom()) && + Objects.equals(this.getDescription(), other.getDescription()) && + Objects.equals(this.getIdea(), other.getIdea()) + ); } protected boolean canEqual(final Object other) { @@ -124,13 +126,29 @@ public class FirstMeeting implements Serializable { @Override public int hashCode() { - return Objects.hash(this.getId(), this.getFirstMeetingDate(), this.getRoom(), this.getDescription(), - this.getIdea()); + return Objects.hash( + this.getId(), + this.getFirstMeetingDate(), + this.getRoom(), + this.getDescription(), + this.getIdea() + ); } @Override public String toString() { - return "FirstMeeting(id=" + this.getId() + ", firstMeetingDate=" + this.getFirstMeetingDate() + ", room=" + - this.getRoom() + ", description=" + this.getDescription() + ", idea=" + this.getIdea() + ")"; + return ( + "FirstMeeting(id=" + + this.getId() + + ", firstMeetingDate=" + + this.getFirstMeetingDate() + + ", room=" + + this.getRoom() + + ", description=" + + this.getDescription() + + ", idea=" + + this.getIdea() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepository.java b/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepository.java index caa4bab050..3c08f23f2c 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepository.java @@ -4,8 +4,6 @@ import jakarta.transaction.Transactional; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; - @Transactional -public interface FirstMeetingRepository extends JpaRepository, QueryDslPredicateExecutor { - -} +public interface FirstMeetingRepository + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepositoryImpl.java index 8ed543e2b3..2f225178af 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/FirstMeetingRepositoryImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class FirstMeetingRepositoryImpl extends GenericRepo implements FirstMeetingRepository { + @Inject public FirstMeetingRepositoryImpl(Provider em) { super(em, FirstMeeting.class, QFirstMeeting.firstMeeting); diff --git a/core/src/main/java/se/su/dsv/scipro/match/Idea.java b/core/src/main/java/se/su/dsv/scipro/match/Idea.java index 1ab583880a..c98f1bc7ec 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/Idea.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Idea.java @@ -30,15 +30,6 @@ import jakarta.persistence.PostUpdate; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; import jakarta.persistence.Table; - -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.ResearchArea; -import se.su.dsv.scipro.system.User; - import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; @@ -49,11 +40,19 @@ import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.ResearchArea; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "idea") @Cacheable(true) public class Idea extends DomainObject { + private static final int DESCRIPTION_LENGTH = 4000; private static final int PREREQUISITES_LENGTH = 4000; private static final int TITLE_LENGTH = 1024; @@ -94,23 +93,36 @@ public class Idea extends DomainObject { private boolean inactive = false; @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "practicalHow", column = @Column(name = "practical_how", insertable = false, updatable = false)), - @AttributeOverride(name = "theoryHow", column = @Column(name = "theory_how", insertable = false, updatable = false)), + @AttributeOverrides( + { + @AttributeOverride( + name = "practicalHow", + column = @Column(name = "practical_how", insertable = false, updatable = false) + ), + @AttributeOverride( + name = "theoryHow", + column = @Column(name = "theory_how", insertable = false, updatable = false) + ), @AttributeOverride(name = "what", column = @Column(name = "what", insertable = false, updatable = false)), @AttributeOverride(name = "why", column = @Column(name = "why", insertable = false, updatable = false)), - @AttributeOverride(name = "literature", column = @Column(name = "literature", insertable = false, updatable = false)) - }) + @AttributeOverride( + name = "literature", + column = @Column(name = "literature", insertable = false, updatable = false) + ), + } + ) private Watson watson; @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "literature", column = @Column(name = "literature")), - @AttributeOverride(name = "background", column = @Column(name = "background")), - @AttributeOverride(name = "problem", column = @Column(name = "problem")), - @AttributeOverride(name = "method", column = @Column(name = "method")), - @AttributeOverride(name = "interests", column = @Column(name = "interests")) - }) + @AttributeOverrides( + { + @AttributeOverride(name = "literature", column = @Column(name = "literature")), + @AttributeOverride(name = "background", column = @Column(name = "background")), + @AttributeOverride(name = "problem", column = @Column(name = "problem")), + @AttributeOverride(name = "method", column = @Column(name = "method")), + @AttributeOverride(name = "interests", column = @Column(name = "interests")), + } + ) private TholanderBox tholanderBox = new TholanderBox(); // ---------------------------------------------------------------------------------- @@ -126,7 +138,7 @@ public class Idea extends DomainObject { @OneToOne(optional = true, cascade = CascadeType.ALL) @JoinColumn(name = "latest_match_id", referencedColumnName = "id") - @QueryInit({"supervisor.user", "supervisor.unit"}) + @QueryInit({ "supervisor.user", "supervisor.unit" }) private Match match; @OneToOne @@ -147,9 +159,11 @@ public class Idea extends DomainObject { // many-to-many from table "keyword" through table "idea_keyword" @ManyToMany - @JoinTable(name="idea_keyword", - joinColumns = @JoinColumn(name = "idea_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "keyword_id", referencedColumnName = "id")) + @JoinTable( + name = "idea_keyword", + joinColumns = @JoinColumn(name = "idea_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "keyword_id", referencedColumnName = "id") + ) private Set keywords = new HashSet<>(); // ---------------------------------------------------------------------------------- @@ -158,8 +172,7 @@ public class Idea extends DomainObject { // from table idea_language @ElementCollection - @CollectionTable(name = "idea_language", - joinColumns = @JoinColumn(name = "idea_id", referencedColumnName = "id")) + @CollectionTable(name = "idea_language", joinColumns = @JoinColumn(name = "idea_id", referencedColumnName = "id")) @Column(name = "language") @Enumerated(EnumType.STRING) private Set languages = EnumSet.noneOf(Language.class); @@ -170,7 +183,7 @@ public class Idea extends DomainObject { // from table idea_student @OneToMany(fetch = FetchType.LAZY, mappedBy = "idea", cascade = CascadeType.ALL, orphanRemoval = true) - @QueryInit({"user", "program"}) + @QueryInit({ "user", "program" }) private Set ideaParticipations = new HashSet<>(); // from table "idea_match" @@ -329,17 +342,14 @@ public class Idea extends DomainObject { public String getAuthorNames() { return getIdeaParticipations() - .stream() - .map(IdeaParticipation::getUser) - .map(User::getFullName) - .collect(Collectors.joining(", ")); + .stream() + .map(IdeaParticipation::getUser) + .map(User::getFullName) + .collect(Collectors.joining(", ")); } public String getKeywordNames() { - return getKeywords() - .stream() - .map(Keyword::getKeyword) - .collect(Collectors.joining(", ")); + return getKeywords().stream().map(Keyword::getKeyword).collect(Collectors.joining(", ")); } @Override @@ -400,9 +410,7 @@ public class Idea extends DomainObject { } public IdeaExport getExport() { - return exports.stream() - .max(Comparator.comparing(IdeaExport::getId)) - .orElse(null); + return exports.stream().max(Comparator.comparing(IdeaExport::getId)).orElse(null); } public boolean isInactive() { @@ -510,9 +518,7 @@ public class Idea extends DomainObject { if (o == this) return true; if (!(o instanceof Idea)) return false; final Idea other = (Idea) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -526,7 +532,19 @@ public class Idea extends DomainObject { @Override public String toString() { - return "Idea(id=" + this.getId() + ", title=" + this.getTitle() + ", match=" + this.getMatch() + ", export=" + this.getExport() + ", cachedStatus=" + this.cachedStatus + ")"; + return ( + "Idea(id=" + + this.getId() + + ", title=" + + this.getTitle() + + ", match=" + + this.getMatch() + + ", export=" + + this.getExport() + + ", cachedStatus=" + + this.cachedStatus + + ")" + ); } public enum Type { @@ -572,6 +590,6 @@ public class Idea extends DomainObject { public String toString() { return "Inactive"; } - } + }, } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaExport.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaExport.java index 321ccda22b..df0bf944ed 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaExport.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaExport.java @@ -10,16 +10,17 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - -import se.su.dsv.scipro.system.DomainObject; - import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Table(name = "idea_export") public class IdeaExport extends DomainObject { - public enum Result { FAIL, SUCCESS } + public enum Result { + FAIL, + SUCCESS, + } // ---------------------------------------------------------------------------------- // basic and embedded JPA-mappings @@ -89,11 +90,13 @@ public class IdeaExport extends DomainObject { if (o == this) return true; if (!(o instanceof IdeaExport)) return false; final IdeaExport other = (IdeaExport) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getResult(), other.getResult()) - && Objects.equals(this.getReason(), other.getReason()) - && Objects.equals(this.getIdea(), other.getIdea()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getResult(), other.getResult()) && + Objects.equals(this.getReason(), other.getReason()) && + Objects.equals(this.getIdea(), other.getIdea()) + ); } protected boolean canEqual(final Object other) { @@ -107,6 +110,8 @@ public class IdeaExport extends DomainObject { @Override public String toString() { - return "IdeaExport(id=" + this.getId() + ", result=" + this.getResult() + ", reason=" + this.getReason() + ")"; + return ( + "IdeaExport(id=" + this.getId() + ", result=" + this.getResult() + ", reason=" + this.getReason() + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaFacade.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaFacade.java index d3dc01f86a..7e42cba7a5 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaFacade.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaFacade.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class IdeaFacade implements Serializable { @@ -20,13 +19,20 @@ public class IdeaFacade implements Serializable { @Inject ApplicationPeriodService applicationPeriodService; - public Iterable findIdeasPossibleToMatch(ApplicationPeriod applicationPeriod, final User student, IdeaService.Filter params, Pageable pageable) { + public Iterable findIdeasPossibleToMatch( + ApplicationPeriod applicationPeriod, + final User student, + IdeaService.Filter params, + Pageable pageable + ) { params.setPublished(true); Iterable ideas = ideaService.findAll(params); List ideasWithinLimits = new ArrayList<>(); final List validTypes = applicationPeriodService.getTypesForStudent(applicationPeriod, student); for (Idea idea : ideas) { - if (targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType())) { + if ( + targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType()) + ) { if (validTypes.contains(idea.getProjectType())) { ideasWithinLimits.add(idea); } @@ -35,13 +41,19 @@ public class IdeaFacade implements Serializable { return ideaService.findAllInList(ideasWithinLimits, pageable); } - public int countIdeasPossibleToMatch(ApplicationPeriod applicationPeriod, final User student, IdeaService.Filter params) { + public int countIdeasPossibleToMatch( + ApplicationPeriod applicationPeriod, + final User student, + IdeaService.Filter params + ) { params.setPublished(true); Iterable ideas = ideaService.findAll(params); List ideasWithinLimits = new ArrayList<>(); final List validTypes = applicationPeriodService.getTypesForStudent(applicationPeriod, student); for (Idea idea : ideas) { - if (targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType())) { + if ( + targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType()) + ) { if (validTypes.contains(idea.getProjectType())) { ideasWithinLimits.add(idea); } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaParticipation.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaParticipation.java index 7bf357d62f..2e47db8666 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaParticipation.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaParticipation.java @@ -9,12 +9,11 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.Program; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.system.Program; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "idea_student") @@ -56,7 +55,7 @@ public class IdeaParticipation implements Serializable { // By creating a protected constructor, JPA/Hibernate still works as expected, but it // declares the intention that parameters need to be provided when new instances are // created. - protected IdeaParticipation() { } + protected IdeaParticipation() {} public IdeaParticipation(User student, Idea idea) { this.user = student; @@ -111,7 +110,19 @@ public class IdeaParticipation implements Serializable { // ---------------------------------------------------------------------------- @Override public String toString() { - return "IdeaParticipation(id=" + this.getId() + ", user=" + this.getUser() + ", idea=" + this.getIdea() + ", dateCreated=" + this.getDateCreated() + ", program=" + this.getProgram() + ")"; + return ( + "IdeaParticipation(id=" + + this.getId() + + ", user=" + + this.getUser() + + ", idea=" + + this.getIdea() + + ", dateCreated=" + + this.getDateCreated() + + ", program=" + + this.getProgram() + + ")" + ); } @Override @@ -119,9 +130,11 @@ public class IdeaParticipation implements Serializable { if (o == this) return true; if (!(o instanceof IdeaParticipation)) return false; final IdeaParticipation other = (IdeaParticipation) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getIdea(), other.getIdea()); + return ( + other.canEqual(this) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getIdea(), other.getIdea()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaRepository.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaRepository.java index a2a44d65e0..01bb1cd847 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaRepository.java @@ -1,10 +1,14 @@ package se.su.dsv.scipro.match; +import java.util.Set; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.Set; - public interface IdeaRepository { - long countIdeas(ApplicationPeriod applicationPeriod, User supervisor, ProjectType projectType, Set status); + long countIdeas( + ApplicationPeriod applicationPeriod, + User supervisor, + ProjectType projectType, + Set status + ); } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaRepositoryImpl.java index 82526a3af4..d35f7760fa 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaRepositoryImpl.java @@ -1,28 +1,33 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.AbstractRepository; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Set; +import se.su.dsv.scipro.system.AbstractRepository; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class IdeaRepositoryImpl extends AbstractRepository implements IdeaRepository { + @Inject public IdeaRepositoryImpl(final Provider em) { super(em); } @Override - public long countIdeas(final ApplicationPeriod applicationPeriod, final User supervisor, final ProjectType projectType, final Set status) { + public long countIdeas( + final ApplicationPeriod applicationPeriod, + final User supervisor, + final ProjectType projectType, + final Set status + ) { return from(QIdea.idea) - .select(QIdea.idea.count()) - .where(QIdea.idea.applicationPeriod.eq(applicationPeriod)) - .where(QIdea.idea.match.supervisor.eq(supervisor)) - .where(QIdea.idea.projectType.eq(projectType)) - .where(QIdea.idea.cachedStatus.in(status)) - .fetchFirst(); + .select(QIdea.idea.count()) + .where(QIdea.idea.applicationPeriod.eq(applicationPeriod)) + .where(QIdea.idea.match.supervisor.eq(supervisor)) + .where(QIdea.idea.projectType.eq(projectType)) + .where(QIdea.idea.cachedStatus.in(status)) + .fetchFirst(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaService.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaService.java index b45a921ea6..f0713990a3 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaService.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.match.Idea.Status; -import se.su.dsv.scipro.match.Idea.Type; -import se.su.dsv.scipro.system.*; -import se.su.dsv.scipro.util.Either; -import se.su.dsv.scipro.util.Pair; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; +import se.su.dsv.scipro.match.Idea.Status; +import se.su.dsv.scipro.match.Idea.Type; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.util.Either; +import se.su.dsv.scipro.util.Pair; public interface IdeaService extends GenericService, FilteredService { Idea savePartnerProgram(Idea idea, User student, Program program); @@ -24,13 +23,31 @@ public interface IdeaService extends GenericService, FilteredService Long countAuthorIdeas(User author); Long countAuthorsByApplicationPeriod(ApplicationPeriod ap, Filter params); Either supervisorAcceptIdea(Idea idea, User supervisor); - Pair validateStudentAcceptance(Idea idea, User creator, User coAuthor, final ApplicationPeriod applicationPeriod); + Pair validateStudentAcceptance( + Idea idea, + User creator, + User coAuthor, + final ApplicationPeriod applicationPeriod + ); Pair validateAdminAddAuthors(Idea idea, Set authors); Idea saveSupervisorIdea(Idea idea, User supervisor, List keywords, boolean isNewIdea); - Idea saveStudentIdea(Idea idea, User creator, Program creatorProgram, Set partners, List keywords, boolean isNewIdea); + Idea saveStudentIdea( + Idea idea, + User creator, + Program creatorProgram, + Set partners, + List keywords, + boolean isNewIdea + ); void adminUnmatchIdea(Idea idea, User admin); void deleteUnmatchedIdea(Idea idea); - Idea acceptIdea(Idea idea, User creator, Program accepteeProgram, User coAuthor, final ApplicationPeriod applicationPeriod); + Idea acceptIdea( + Idea idea, + User creator, + Program accepteeProgram, + User coAuthor, + final ApplicationPeriod applicationPeriod + ); void changeSupervisor(Idea idea, User newSelection, User creator); void setAuthors(Idea idea, Set authors, User creator); void studentUnselect(Idea idea, User student); @@ -39,12 +56,17 @@ public interface IdeaService extends GenericService, FilteredService boolean authorParticipatingOnOtherActiveIdea(User author, ApplicationPeriod ap, final Idea except); void inactivateIdea(Idea idea, boolean state, User creator); Long countByApplicationPeriodAndType(ApplicationPeriod applicationPeriod, Type type, Filter params); - Long countByApplicationPeriodAndProjectType(ApplicationPeriod applicationPeriod, ProjectType projectType, Filter params); + Long countByApplicationPeriodAndProjectType( + ApplicationPeriod applicationPeriod, + ProjectType projectType, + Filter params + ); Long countByApplicationPeriod(ApplicationPeriod applicationPeriod, Filter params); SelectionState getSelectionState(Idea idea); boolean canEdit(Idea idea, User student); class Filter implements Serializable { + private Collection levels; private Collection statuses; private Collection types; @@ -192,7 +214,41 @@ public interface IdeaService extends GenericService, FilteredService @Override public String toString() { - return "IdeaService.Filter(levels=" + this.getLevels() + ", statuses=" + this.getStatuses() + ", types=" + this.getTypes() + ", keywords=" + this.getKeywords() + ", supervisor=" + this.getSupervisor() + ", author=" + this.getAuthor() + ", researchArea=" + this.getResearchArea() + ", unit=" + this.getUnit() + ", createdAfter=" + this.getCreatedAfter() + ", createdBefore=" + this.getCreatedBefore() + ", noSupervisor=" + this.getNoSupervisor() + ", titleContains=" + this.getTitleContains() + ", program=" + this.getProgram() + ", applicationPeriod=" + this.getApplicationPeriod() + ", published=" + this.getPublished() + ", noFirstMeeting=" + this.getNoFirstMeeting() + ")"; + return ( + "IdeaService.Filter(levels=" + + this.getLevels() + + ", statuses=" + + this.getStatuses() + + ", types=" + + this.getTypes() + + ", keywords=" + + this.getKeywords() + + ", supervisor=" + + this.getSupervisor() + + ", author=" + + this.getAuthor() + + ", researchArea=" + + this.getResearchArea() + + ", unit=" + + this.getUnit() + + ", createdAfter=" + + this.getCreatedAfter() + + ", createdBefore=" + + this.getCreatedBefore() + + ", noSupervisor=" + + this.getNoSupervisor() + + ", titleContains=" + + this.getTitleContains() + + ", program=" + + this.getProgram() + + ", applicationPeriod=" + + this.getApplicationPeriod() + + ", published=" + + this.getPublished() + + ", noFirstMeeting=" + + this.getNoFirstMeeting() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/IdeaServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/IdeaServiceImpl.java index e6be18e1c3..08845a8a3f 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/IdeaServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/IdeaServiceImpl.java @@ -1,15 +1,26 @@ package se.su.dsv.scipro.match; -import jakarta.transaction.Transactional; +import static com.querydsl.core.types.dsl.Expressions.allOf; +import static com.querydsl.core.types.dsl.Expressions.anyOf; + import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.DateExpression; import com.querydsl.core.types.dsl.DateTimeExpression; import com.querydsl.jpa.JPAExpressions; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.text.MessageFormat; +import java.time.Clock; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; @@ -21,22 +32,10 @@ import se.su.dsv.scipro.notifications.dataobject.IdeaEvent; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.text.MessageFormat; -import java.time.Clock; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.*; -import java.util.stream.Collectors; - -import static com.querydsl.core.types.dsl.Expressions.allOf; -import static com.querydsl.core.types.dsl.Expressions.anyOf; - public class IdeaServiceImpl extends AbstractServiceImpl implements IdeaService { private static final Logger LOGGER = LoggerFactory.getLogger(IdeaServiceImpl.class); @@ -44,16 +43,22 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements public static final String VALIDATION_PASSED = "Validation passed"; public static final String NO_LONGER_AVAILABLE_ERROR = "Idea is no longer available"; public static final String ALREADY_PARTICIPATING_ERROR = "You are already participating in another idea"; - public static final String PARTNER_ALREADY_PARTICIPATING_ERROR = "Your partner is already participating in another idea"; - public static final String BACHELOR_NEED_PARTNER_ERROR = "You need to select a partner when the idea is on bachelor level"; + public static final String PARTNER_ALREADY_PARTICIPATING_ERROR = + "Your partner is already participating in another idea"; + public static final String BACHELOR_NEED_PARTNER_ERROR = + "You need to select a partner when the idea is on bachelor level"; public static final String ADD_SELF_AS_PARTNER_ERROR = "You may not add yourself as project partner"; - public static final String NO_AUTHORS_ERROR = "The idea is submitted by a student, number of students is not allowed"; + public static final String NO_AUTHORS_ERROR = + "The idea is submitted by a student, number of students is not allowed"; public static final int TITLE_LENGTH = 3; public static final long EMPTY = 0; - private static final String WRONG_LEVEL_FOR_YOUR_PARTNER = "The idea is the wrong level for your partner, please pick another one."; + private static final String WRONG_LEVEL_FOR_YOUR_PARTNER = + "The idea is the wrong level for your partner, please pick another one."; private static final String WRONG_LEVEL_FOR_YOU = "The idea is the wrong level for you, please pick another one."; - public static final String ALREADY_HAVE_AN_ACTIVE_PROJECT = "You already have an active project on this level. You have to contact {0} to have it cancelled before you can pick a new idea."; - public static final String PARTNER_ALREADY_HAS_ACTIVE_PROJECT = "Your partner has an active project on this level already. They have to contact {0} to cancel their previous project."; + public static final String ALREADY_HAVE_AN_ACTIVE_PROJECT = + "You already have an active project on this level. You have to contact {0} to have it cancelled before you can pick a new idea."; + public static final String PARTNER_ALREADY_HAS_ACTIVE_PROJECT = + "Your partner has an active project on this level already. They have to contact {0} to cancel their previous project."; private final ApplicationPeriodService applicationPeriodService; private final FirstMeetingRepository firstMeetingRepository; @@ -66,16 +71,16 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements @Inject public IdeaServiceImpl( - Provider em, - final ApplicationPeriodService applicationPeriodService, - final FirstMeetingRepository firstMeetingRepository, - final NotificationController notificationController, - final ProjectService projectService, - final GeneralSystemSettingsService generalSystemSettingsService, - final TargetRepository targetRepository, - final IdeaRepository ideaRepository, - final Clock clock) - { + Provider em, + final ApplicationPeriodService applicationPeriodService, + final FirstMeetingRepository firstMeetingRepository, + final NotificationController notificationController, + final ProjectService projectService, + final GeneralSystemSettingsService generalSystemSettingsService, + final TargetRepository targetRepository, + final IdeaRepository ideaRepository, + final Clock clock + ) { super(em, Idea.class, QIdea.idea); this.applicationPeriodService = applicationPeriodService; this.firstMeetingRepository = firstMeetingRepository; @@ -117,13 +122,16 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements DateExpression currentDate = DateExpression.currentDate(LocalDateTime.class); DateTimeExpression courseStartDate = QIdea.idea.applicationPeriod.courseStartDateTime; return findAll( - allOf( - QIdea.idea.cachedStatus.eq(Status.MATCHED), - anyOf( - courseStartDate.before(currentDate), - courseStartDate.dayOfYear().eq(currentDate.dayOfYear()).and(courseStartDate.year().eq(currentDate.year())) - ) + allOf( + QIdea.idea.cachedStatus.eq(Status.MATCHED), + anyOf( + courseStartDate.before(currentDate), + courseStartDate + .dayOfYear() + .eq(currentDate.dayOfYear()) + .and(courseStartDate.year().eq(currentDate.year())) ) + ) ); } @@ -148,12 +156,21 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements } QIdeaParticipation participation = QIdeaParticipation.ideaParticipation; return from(participation) - .select(participation.count()) - .where(allOf(participation.idea.applicationPeriod.eq(ap), participation.idea.cachedStatus.in(params.getStatuses()))) - .fetchFirst(); + .select(participation.count()) + .where( + allOf( + participation.idea.applicationPeriod.eq(ap), + participation.idea.cachedStatus.in(params.getStatuses()) + ) + ) + .fetchFirst(); } - private Either validateSupervisorAcceptance(Idea idea, boolean hasTargetsLeft, final User supervisor) { + private Either validateSupervisorAcceptance( + Idea idea, + boolean hasTargetsLeft, + final User supervisor + ) { if (!hasTargetsLeft) { return Either.left(SelectionError.TARGET_NUMBER_REACHED); } @@ -172,7 +189,8 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements @Transactional public Either supervisorAcceptIdea(Idea idea, User supervisor) { Target target = getTarget(idea.getApplicationPeriod(), supervisor, idea.getProjectType()); - boolean targetsLeft = target.getTarget() > countMatched(idea.getApplicationPeriod(), supervisor, idea.getProjectType()); + boolean targetsLeft = + target.getTarget() > countMatched(idea.getApplicationPeriod(), supervisor, idea.getProjectType()); return validateSupervisorAcceptance(idea, targetsLeft, supervisor); } @@ -183,29 +201,54 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements // TODO: Replace with a proper ADT describing the result instead of booleans and strings // TODO: Merge this validation with the #acceptIdea method so that validation is always done @Override - public Pair validateStudentAcceptance(Idea idea, User creator, User coAuthor, final ApplicationPeriod ap) { - final GeneralSystemSettings generalSystemSettingsInstance = generalSystemSettingsService.getGeneralSystemSettingsInstance(); + public Pair validateStudentAcceptance( + Idea idea, + User creator, + User coAuthor, + final ApplicationPeriod ap + ) { + final GeneralSystemSettings generalSystemSettingsInstance = + generalSystemSettingsService.getGeneralSystemSettingsInstance(); if (idea.getMatchStatus() != Status.UNMATCHED) { return new Pair<>(Boolean.FALSE, NO_LONGER_AVAILABLE_ERROR); } - if (idea.getProjectType().getProjectTypeSettings().getMinAuthors() > 1 && coAuthor == null && !applicationPeriodService.hasIdeaSizeExemption(creator, ap)) { + if ( + idea.getProjectType().getProjectTypeSettings().getMinAuthors() > 1 && + coAuthor == null && + !applicationPeriodService.hasIdeaSizeExemption(creator, ap) + ) { return new Pair<>(Boolean.FALSE, BACHELOR_NEED_PARTNER_ERROR); } if (!projectService.getActiveProjectsByUserAndProjectType(creator, idea.getProjectType()).isEmpty()) { - return new Pair<>(Boolean.FALSE, MessageFormat.format(ALREADY_HAVE_AN_ACTIVE_PROJECT, generalSystemSettingsInstance.getActiveProjectIdeaSupportMail())); + return new Pair<>( + Boolean.FALSE, + MessageFormat.format( + ALREADY_HAVE_AN_ACTIVE_PROJECT, + generalSystemSettingsInstance.getActiveProjectIdeaSupportMail() + ) + ); } - if (coAuthor != null) { + if (coAuthor != null) { if (coAuthor.equals(creator)) { return new Pair<>(Boolean.FALSE, ADD_SELF_AS_PARTNER_ERROR); } if (authorParticipatingOnActiveIdea(coAuthor, ap)) { return new Pair<>(Boolean.FALSE, PARTNER_ALREADY_PARTICIPATING_ERROR); } - if (coAuthor.getDegreeType() != ProjectType.UNKNOWN && coAuthor.getDegreeType() != idea.getProjectType().getDegreeType()) { + if ( + coAuthor.getDegreeType() != ProjectType.UNKNOWN && + coAuthor.getDegreeType() != idea.getProjectType().getDegreeType() + ) { return new Pair<>(Boolean.FALSE, WRONG_LEVEL_FOR_YOUR_PARTNER); } if (!projectService.getActiveProjectsByUserAndProjectType(coAuthor, idea.getProjectType()).isEmpty()) { - return new Pair<>(Boolean.FALSE, MessageFormat.format(PARTNER_ALREADY_HAS_ACTIVE_PROJECT, generalSystemSettingsInstance.getActiveProjectIdeaSupportMail())); + return new Pair<>( + Boolean.FALSE, + MessageFormat.format( + PARTNER_ALREADY_HAS_ACTIVE_PROJECT, + generalSystemSettingsInstance.getActiveProjectIdeaSupportMail() + ) + ); } } if (authorParticipatingOnActiveIdea(creator, ap)) { @@ -216,9 +259,13 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements return new Pair<>(Boolean.FALSE, WRONG_LEVEL_FOR_YOU); } - return new Pair<>(Boolean.TRUE, "You have successfully selected the supervisor idea " - + idea.getTitle() + ", in the application period " + ap.getName()); - + return new Pair<>( + Boolean.TRUE, + "You have successfully selected the supervisor idea " + + idea.getTitle() + + ", in the application period " + + ap.getName() + ); } // TODO: Merge this validation with the #adminSetAuthors method so that validation is always done @@ -230,15 +277,25 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements } } else { final ApplicationPeriod currentPeriod = applicationPeriodService.getCurrentPeriod(idea.getProjectType()); - final ApplicationPeriod previousPeriod = applicationPeriodService.getPreviousPeriodByProjectType(idea.getProjectType()); + final ApplicationPeriod previousPeriod = applicationPeriodService.getPreviousPeriodByProjectType( + idea.getProjectType() + ); if (currentPeriod == null && previousPeriod == null) { - return new Pair<>(Boolean.FALSE, "No application period is open and no previous application period is available. Students may not be added to the idea"); + return new Pair<>( + Boolean.FALSE, + "No application period is open and no previous application period is available. Students may not be added to the idea" + ); } - if ((authors.size() < idea.getMinAuthors() || authors.size() > idea.getMaxAuthors()) && - !authors.stream().allMatch(author -> applicationPeriodService.hasIdeaSizeExemption(author, idea.getApplicationPeriod()))) - { + if ( + (authors.size() < idea.getMinAuthors() || authors.size() > idea.getMaxAuthors()) && + !authors + .stream() + .allMatch(author -> + applicationPeriodService.hasIdeaSizeExemption(author, idea.getApplicationPeriod()) + ) + ) { return new Pair<>(Boolean.FALSE, "Selected number of authors is not allowed"); } @@ -278,16 +335,24 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements super.delete(entity); final NotificationSource source = new NotificationSource(); source.setMessage(entity.getTitle()); - final Set members = entity.getIdeaParticipations() - .stream() - .map(ip -> new Member(ip.getUser(), Member.Type.AUTHOR)) - .collect(Collectors.toSet()); + final Set members = entity + .getIdeaParticipations() + .stream() + .map(ip -> new Member(ip.getUser(), Member.Type.AUTHOR)) + .collect(Collectors.toSet()); notificationController.notifyCustom(CustomEvent.Event.IDEA_DELETED, source, members); } @Override @Transactional - public Idea saveStudentIdea(Idea idea, User creator, Program creatorProgram, Set partners, List keywords, boolean isNewIdea) { + public Idea saveStudentIdea( + Idea idea, + User creator, + Program creatorProgram, + Set partners, + List keywords, + boolean isNewIdea + ) { Idea theIdea = idea; final Set added = new HashSet<>(); final Set removed = new HashSet<>(); @@ -316,13 +381,24 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements NotificationSource source = new NotificationSource(); final HashSet recipients = new HashSet<>(); recipients.add(new Member(user, Member.Type.CO_AUTHOR)); - notificationController.notifyIdeaWithCustomRecipients(theIdea, IdeaEvent.Event.REMOVED_AS_PARTNER, source, recipients); + notificationController.notifyIdeaWithCustomRecipients( + theIdea, + IdeaEvent.Event.REMOVED_AS_PARTNER, + source, + recipients + ); source.setMessage(user.getFullName()); } return theIdea; } - private Idea saveStudentIdea0(Idea idea, User creator, Program creatorProgram, List keywords, boolean newIdea) { + private Idea saveStudentIdea0( + Idea idea, + User creator, + Program creatorProgram, + List keywords, + boolean newIdea + ) { Idea theIdea = idea; Set keywordSet = new HashSet<>(keywords); theIdea.setKeywords(keywordSet); @@ -358,8 +434,13 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements } } - private Idea acceptIdea0(Idea idea, User creator, Program accepteeProgram, User coAuthor, final ApplicationPeriod applicationPeriod) { - + private Idea acceptIdea0( + Idea idea, + User creator, + Program accepteeProgram, + User coAuthor, + final ApplicationPeriod applicationPeriod + ) { Idea localIdea = idea; localIdea.setApplicationPeriod(applicationPeriod); @@ -380,7 +461,13 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements @Override @Transactional - public Idea acceptIdea(Idea idea, User creator, Program accepteeProgram, User coAuthor, final ApplicationPeriod applicationPeriod) { + public Idea acceptIdea( + Idea idea, + User creator, + Program accepteeProgram, + User coAuthor, + final ApplicationPeriod applicationPeriod + ) { Idea theIdea = acceptIdea0(idea, creator, accepteeProgram, coAuthor, applicationPeriod); notificationController.notifyIdea(theIdea, IdeaEvent.Event.PARTNER_ACCEPT, new NotificationSource()); @@ -401,7 +488,9 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements Idea reloaded = findOne(idea.getId()); if (!authors.isEmpty()) { for (User s : authors) { - reloaded.getIdeaParticipations().removeIf(ideaParticipation -> !authors.contains(ideaParticipation.getUser())); + reloaded + .getIdeaParticipations() + .removeIf(ideaParticipation -> !authors.contains(ideaParticipation.getUser())); IdeaParticipation ip = new IdeaParticipation(s, reloaded); reloaded.addIdeaParticipation(ip); } @@ -419,7 +508,9 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements if (applicationPeriodService.getCurrentPeriod(reloaded.getProjectType()) != null) { reloaded.setApplicationPeriod(applicationPeriodService.getCurrentPeriod(idea.getProjectType())); } else { - reloaded.setApplicationPeriod(applicationPeriodService.getPreviousPeriodByProjectType(reloaded.getProjectType())); + reloaded.setApplicationPeriod( + applicationPeriodService.getPreviousPeriodByProjectType(reloaded.getProjectType()) + ); } } save(reloaded); @@ -522,7 +613,11 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements } @Override - public Long countByApplicationPeriodAndProjectType(ApplicationPeriod applicationPeriod, ProjectType projectType, Filter params) { + public Long countByApplicationPeriodAndProjectType( + ApplicationPeriod applicationPeriod, + ProjectType projectType, + Filter params + ) { return count(byPeriod(applicationPeriod).and(byLevel(projectType).and(fromParams(params)))); } @@ -553,25 +648,28 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements @Override public boolean canEdit(final Idea idea, final User student) { - boolean isAuthor = idea.getIdeaParticipations() - .stream() - .anyMatch(ip -> Objects.equals(student, ip.getUser())); + boolean isAuthor = idea.getIdeaParticipations().stream().anyMatch(ip -> Objects.equals(student, ip.getUser())); if (!isAuthor) { return false; } final ApplicationPeriod applicationPeriod = idea.getApplicationPeriod(); - return applicationPeriodService.isOpen(applicationPeriod) - || (idea.getType() == Type.STUDENT && applicationPeriodService.hasCurrentSubmitIdeaExemption(applicationPeriod, student)) - || (idea.getType() == Type.SUPERVISOR && applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption(applicationPeriod, student)); + return ( + applicationPeriodService.isOpen(applicationPeriod) || + (idea.getType() == Type.STUDENT && + applicationPeriodService.hasCurrentSubmitIdeaExemption(applicationPeriod, student)) || + (idea.getType() == Type.SUPERVISOR && + applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption(applicationPeriod, student)) + ); } private SelectionState isSelectable(final Idea idea) { - return applicationPeriodService.getCurrentPeriods() - .stream() - .filter(applicationPeriod -> applicationPeriod.getProjectTypes().contains(idea.getProjectType())) - .findAny() - .map(applicationPeriod -> isSelectableInBasedOnTarget(idea, applicationPeriod)) - .orElse(SelectionState.NO_APPLICATION_PERIOD); + return applicationPeriodService + .getCurrentPeriods() + .stream() + .filter(applicationPeriod -> applicationPeriod.getProjectTypes().contains(idea.getProjectType())) + .findAny() + .map(applicationPeriod -> isSelectableInBasedOnTarget(idea, applicationPeriod)) + .orElse(SelectionState.NO_APPLICATION_PERIOD); } private SelectionState isSelectableInBasedOnTarget(final Idea idea, final ApplicationPeriod applicationPeriod) { @@ -645,7 +743,9 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements } private Predicate noFirstMeetingFilter() { - return JPAExpressions.selectFrom(QFirstMeeting.firstMeeting).where(QFirstMeeting.firstMeeting.idea.eq(QIdea.idea)).notExists(); + return JPAExpressions.selectFrom(QFirstMeeting.firstMeeting) + .where(QFirstMeeting.firstMeeting.idea.eq(QIdea.idea)) + .notExists(); } private BooleanBuilder levelFilter(Collection levels) { @@ -756,5 +856,4 @@ public class IdeaServiceImpl extends AbstractServiceImpl implements Set status = EnumSet.of(Idea.Status.MATCHED, Idea.Status.COMPLETED); return ideaRepository.countIdeas(ap, supervisor, pc, status); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/match/Keyword.java b/core/src/main/java/se/su/dsv/scipro/match/Keyword.java index 060efc46b7..f55e2a731d 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/Keyword.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Keyword.java @@ -10,13 +10,11 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; - -import se.su.dsv.scipro.system.LazyDeletableDomainObject; -import se.su.dsv.scipro.system.ResearchArea; - import java.util.HashSet; import java.util.Objects; import java.util.Set; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; +import se.su.dsv.scipro.system.ResearchArea; @Entity @Table(name = "keyword") @@ -30,24 +28,25 @@ public class Keyword extends LazyDeletableDomainObject { private String keyword; @ManyToMany(fetch = FetchType.EAGER, targetEntity = ResearchArea.class) - @JoinTable(name="keyword_research_area", - joinColumns = @JoinColumn(name = "keyword_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "research_area_id", referencedColumnName = "id")) + @JoinTable( + name = "keyword_research_area", + joinColumns = @JoinColumn(name = "keyword_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "research_area_id", referencedColumnName = "id") + ) private Set researchAreas = new HashSet<>(); - public Keyword() { - } + public Keyword() {} public Keyword(String keyword) { this.keyword = keyword; } public void addResearchArea(ResearchArea area) { - this.researchAreas.add(area); + this.researchAreas.add(area); } public void removeResearchArea(ResearchArea area) { - this.researchAreas.remove(area); + this.researchAreas.remove(area); } @Override @@ -77,7 +76,15 @@ public class Keyword extends LazyDeletableDomainObject { @Override public String toString() { - return "Keyword(id=" + this.getId() + ", keyword=" + this.getKeyword() + ", researchAreas=" + this.getResearchAreas() + ")"; + return ( + "Keyword(id=" + + this.getId() + + ", keyword=" + + this.getKeyword() + + ", researchAreas=" + + this.getResearchAreas() + + ")" + ); } @Override @@ -85,9 +92,12 @@ public class Keyword extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof Keyword)) return false; final Keyword other = (Keyword) o; - return other.canEqual(this) && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getKeyword(), other.getKeyword()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getKeyword(), other.getKeyword()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/KeywordService.java b/core/src/main/java/se/su/dsv/scipro/match/KeywordService.java index 012726c891..106f2a6067 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/KeywordService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/KeywordService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.ResearchArea; - import java.util.List; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ResearchArea; public interface KeywordService extends GenericService { Iterable findByResearchArea(ResearchArea area, Pageable pageable); diff --git a/core/src/main/java/se/su/dsv/scipro/match/KeywordServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/KeywordServiceImpl.java index 9eb0a58232..f8003f7687 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/KeywordServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/KeywordServiceImpl.java @@ -1,71 +1,71 @@ package se.su.dsv.scipro.match; -import jakarta.transaction.Transactional; import com.querydsl.core.types.dsl.BooleanExpression; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.Sort; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.ResearchArea; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ResearchArea; +import se.su.dsv.scipro.system.Sort; -public class KeywordServiceImpl extends AbstractServiceImpl implements KeywordService { +public class KeywordServiceImpl extends AbstractServiceImpl implements KeywordService { private static final Logger LOGGER = LoggerFactory.getLogger(KeywordServiceImpl.class); @Inject - public KeywordServiceImpl(Provider em) { + public KeywordServiceImpl(Provider em) { super(em, Keyword.class, QKeyword.keyword1); - } + } private BooleanExpression byArea(ResearchArea area) { - return QKeyword.keyword1.researchAreas.any().eq(area); + return QKeyword.keyword1.researchAreas.any().eq(area); } - + private BooleanExpression nameContains(String input) { - return QKeyword.keyword1.keyword.containsIgnoreCase(input); + return QKeyword.keyword1.keyword.containsIgnoreCase(input); } @Override - @Transactional - public void deleteConnection(Keyword keyword, ResearchArea area) { - Keyword k = findOne(keyword.getId()); - k.removeResearchArea(area); - LOGGER.info("Removing relationship between Keyword: " + k.getKeyword() + " and Research area: " + area.getTitle()); - } - - @Override - @Transactional - public void addConnection(Keyword keyword, ResearchArea area) { - Keyword k = findOne(keyword.getId()); - k.addResearchArea(area); - LOGGER.info("Relationship added, Keyword: " + k.getKeyword() + ", Research area: " + area.getTitle()); - } - - @Override - public Iterable findByResearchArea(ResearchArea area, Pageable pageable) { - return findAll(byArea(area), pageable); - } + @Transactional + public void deleteConnection(Keyword keyword, ResearchArea area) { + Keyword k = findOne(keyword.getId()); + k.removeResearchArea(area); + LOGGER.info( + "Removing relationship between Keyword: " + k.getKeyword() + " and Research area: " + area.getTitle() + ); + } @Override - public List findByResearchArea(ResearchArea area) { - return findAll(byArea(area)); - } + @Transactional + public void addConnection(Keyword keyword, ResearchArea area) { + Keyword k = findOne(keyword.getId()); + k.addResearchArea(area); + LOGGER.info("Relationship added, Keyword: " + k.getKeyword() + ", Research area: " + area.getTitle()); + } - @Override - public List getAutoCompleteKeywords(String searchString, int limit) { + @Override + public Iterable findByResearchArea(ResearchArea area, Pageable pageable) { + return findAll(byArea(area), pageable); + } + + @Override + public List findByResearchArea(ResearchArea area) { + return findAll(byArea(area)); + } + + @Override + public List getAutoCompleteKeywords(String searchString, int limit) { return findAll(nameContains(searchString), new PageRequest(0, limit, new Sort(Sort.Direction.ASC, "keyword"))); - } - - @Override - public Long countByResearchArea(ResearchArea area) { - return count(byArea(area)); - } + } + @Override + public Long countByResearchArea(ResearchArea area) { + return count(byArea(area)); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/Match.java b/core/src/main/java/se/su/dsv/scipro/match/Match.java index 2408e5058f..666f765e9a 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/Match.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Match.java @@ -12,12 +12,10 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Objects; - @Entity @Table(name = "idea_match") @Cacheable(true) @@ -47,7 +45,7 @@ public class Match extends DomainObject { @ManyToOne @JoinColumn(name = "supervisor_user_id", referencedColumnName = "id") - @QueryInit({"unit"}) + @QueryInit({ "unit" }) private User supervisor; // ---------------------------------------------------------------------------------- @@ -102,12 +100,14 @@ public class Match extends DomainObject { if (o == this) return true; if (!(o instanceof Match)) return false; final Match other = (Match) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getIdea(), other.getIdea()) - && Objects.equals(this.getSupervisor(), other.getSupervisor()) - && Objects.equals(this.getStatus(), other.getStatus()) - && Objects.equals(this.getChangedBy(), other.getChangedBy()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getIdea(), other.getIdea()) && + Objects.equals(this.getSupervisor(), other.getSupervisor()) && + Objects.equals(this.getStatus(), other.getStatus()) && + Objects.equals(this.getChangedBy(), other.getChangedBy()) + ); } protected boolean canEqual(final Object other) { @@ -121,7 +121,16 @@ public class Match extends DomainObject { @Override public String toString() { - return "Match(id=" + this.getId() + ", supervisor=" + this.getSupervisor() + ", status=" + this.getStatus() + - ", changedBy=" + this.getChangedBy() + ")"; + return ( + "Match(id=" + + this.getId() + + ", supervisor=" + + this.getSupervisor() + + ", status=" + + this.getStatus() + + ", changedBy=" + + this.getChangedBy() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpService.java b/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpService.java index 93ab5c5a97..27edffcbd9 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.match; +import java.util.Set; import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.User; -import java.util.Set; - public interface MatchFollowUpService { long countUnmetTargets(ApplicationPeriod applicationPeriod); Iterable findUnmetTargets(ApplicationPeriod applicationPeriod, Pageable pageable); diff --git a/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpServiceImpl.java index 724cbefa0b..7e91a3cf45 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/MatchFollowUpServiceImpl.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import static com.querydsl.core.types.dsl.Expressions.anyOf; + import com.google.common.primitives.Ints; import com.querydsl.core.types.EntityPath; import com.querydsl.core.types.Projections; @@ -8,9 +10,6 @@ import com.querydsl.core.types.dsl.StringPath; import com.querydsl.jpa.JPAExpressions; import com.querydsl.jpa.JPQLQuery; import com.querydsl.jpa.impl.JPAQuery; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; @@ -18,8 +17,8 @@ import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; - -import static com.querydsl.core.types.dsl.Expressions.anyOf; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.User; public class MatchFollowUpServiceImpl implements MatchFollowUpService { @@ -35,16 +34,16 @@ public class MatchFollowUpServiceImpl implements MatchFollowUpService { } private JPQLQuery getQuery(ApplicationPeriod applicationPeriod) { - return JPAExpressions - .select(QIdea.idea.count()) - .from(QIdea.idea) - .where(QIdea.idea.published.eq(true), - QIdea.idea.projectType.id.eq(QTarget.target1.projectType.id)) - .where(QIdea.idea.match.supervisor.id.eq(QTarget.target1.user.id), - anyOf(QIdea.idea.applicationPeriod.id.eq(applicationPeriod.getId()), - QIdea.idea.cachedStatus.in(Idea.Status.UNMATCHED) - ) - ); + return JPAExpressions.select(QIdea.idea.count()) + .from(QIdea.idea) + .where(QIdea.idea.published.eq(true), QIdea.idea.projectType.id.eq(QTarget.target1.projectType.id)) + .where( + QIdea.idea.match.supervisor.id.eq(QTarget.target1.user.id), + anyOf( + QIdea.idea.applicationPeriod.id.eq(applicationPeriod.getId()), + QIdea.idea.cachedStatus.in(Idea.Status.UNMATCHED) + ) + ); } private static Predicate unmet() { @@ -54,54 +53,41 @@ public class MatchFollowUpServiceImpl implements MatchFollowUpService { @Override public long countUnmetTargets(final ApplicationPeriod applicationPeriod) { List list = from(QTarget.target1) - .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), - QTarget.target1.target.gt(0)) - .select(Projections.constructor(TargetResult.class, - QTarget.target1, - getQuery(applicationPeriod) - )) - .fetch(); + .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), QTarget.target1.target.gt(0)) + .select(Projections.constructor(TargetResult.class, QTarget.target1, getQuery(applicationPeriod))) + .fetch(); - - return list.stream() - .filter(unmet()) - .count(); + return list.stream().filter(unmet()).count(); } @Override public Iterable findUnmetTargets(final ApplicationPeriod applicationPeriod, final Pageable pageable) { StringPath sort = Expressions.stringPath(QTarget.target1, pageable.getSort().getProperty()); List targetResults = from(QTarget.target1) - .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), - QTarget.target1.target.gt(0)) - .orderBy(pageable.getSort().isAscending() ? sort.asc() : sort.desc()) - .select(Projections.constructor(TargetResult.class, - QTarget.target1, - getQuery(applicationPeriod) - )) - .fetch(); + .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), QTarget.target1.target.gt(0)) + .orderBy(pageable.getSort().isAscending() ? sort.asc() : sort.desc()) + .select(Projections.constructor(TargetResult.class, QTarget.target1, getQuery(applicationPeriod))) + .fetch(); - return targetResults.stream() - .filter(unmet()) - .skip(Ints.checkedCast(pageable.getOffset())) - .limit(Ints.checkedCast(pageable.getLimit())) - .toList(); + return targetResults + .stream() + .filter(unmet()) + .skip(Ints.checkedCast(pageable.getOffset())) + .limit(Ints.checkedCast(pageable.getLimit())) + .toList(); } @Override public Set findSupervisorsWithUnmetTargets(ApplicationPeriod applicationPeriod) { List targetResults = from(QTarget.target1) - .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), - QTarget.target1.target.gt(0)) - .select(Projections.constructor(TargetResult.class, - QTarget.target1, - getQuery(applicationPeriod) - )) - .fetch(); + .where(QTarget.target1.applicationPeriod.eq(applicationPeriod), QTarget.target1.target.gt(0)) + .select(Projections.constructor(TargetResult.class, QTarget.target1, getQuery(applicationPeriod))) + .fetch(); - return targetResults.stream() - .filter(unmet()) - .map(unmet -> unmet.getTarget().getUser()) - .collect(Collectors.toSet()); + return targetResults + .stream() + .filter(unmet()) + .map(unmet -> unmet.getTarget().getUser()) + .collect(Collectors.toSet()); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/MatchService.java b/core/src/main/java/se/su/dsv/scipro/match/MatchService.java index 8710682219..99a808a1a7 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/MatchService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/MatchService.java @@ -1,9 +1,9 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; public interface MatchService extends GenericService { - Iterable getMatchHistory(Idea idea, Pageable pageable); + Iterable getMatchHistory(Idea idea, Pageable pageable); Long countMatchHistory(Idea idea); } diff --git a/core/src/main/java/se/su/dsv/scipro/match/MatchServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/MatchServiceImpl.java index dcdb6cbcbd..202ce12255 100755 --- a/core/src/main/java/se/su/dsv/scipro/match/MatchServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/MatchServiceImpl.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; + +public class MatchServiceImpl extends AbstractServiceImpl implements MatchService { -public class MatchServiceImpl extends AbstractServiceImpl implements MatchService { @Inject public MatchServiceImpl(Provider em) { super(em, Match.class, QMatch.match); @@ -22,5 +22,4 @@ public class MatchServiceImpl extends AbstractServiceImpl implements public Long countMatchHistory(Idea idea) { return count(QMatch.match.idea.eq(idea)); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/match/OpenPeriod.java b/core/src/main/java/se/su/dsv/scipro/match/OpenPeriod.java index 80a8e8774f..ce99199f91 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/OpenPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/match/OpenPeriod.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Objects; public final class OpenPeriod extends StudentPeriod implements Serializable { + private final ApplicationPeriod applicationPeriod; private final List exemptions; @@ -30,7 +31,7 @@ public final class OpenPeriod extends StudentPeriod implements Serializable { @Override public String toString() { - return "OpenPeriod(applicationPeriod=" + this.getApplicationPeriod() + ")"; + return ("OpenPeriod(applicationPeriod=" + this.getApplicationPeriod() + ")"); } @Override @@ -38,8 +39,10 @@ public final class OpenPeriod extends StudentPeriod implements Serializable { if (o == this) return true; if (!(o instanceof OpenPeriod)) return false; final OpenPeriod other = (OpenPeriod) o; - return Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) - && Objects.equals(this.exemptions, other.exemptions); + return ( + Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) && + Objects.equals(this.exemptions, other.exemptions) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatch.java b/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatch.java index 4a2b0229ba..95fea899ad 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatch.java +++ b/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatch.java @@ -9,15 +9,14 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Objects; - @Entity @Table(name = "preliminary_match") public class PreliminaryMatch extends DomainObject { + // ---------------------------------------------------------------------------------- // basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -44,7 +43,7 @@ public class PreliminaryMatch extends DomainObject { // ---------------------------------------------------------------------------------- // constructors // ---------------------------------------------------------------------------------- - public PreliminaryMatch() { } + public PreliminaryMatch() {} public PreliminaryMatch(final Idea idea) { this.idea = idea; @@ -91,8 +90,17 @@ public class PreliminaryMatch extends DomainObject { // ---------------------------------------------------------------------------------- @Override public String toString() { - return "PreliminaryMatch(id=" + this.getId() + ", idea=" + this.getIdea() + ", supervisor=" + - this.getSupervisor() + ", comment=" + this.getComment() + ")"; + return ( + "PreliminaryMatch(id=" + + this.getId() + + ", idea=" + + this.getIdea() + + ", supervisor=" + + this.getSupervisor() + + ", comment=" + + this.getComment() + + ")" + ); } @Override @@ -100,12 +108,14 @@ public class PreliminaryMatch extends DomainObject { if (o == this) return true; if (!(o instanceof PreliminaryMatch)) return false; final PreliminaryMatch other = (PreliminaryMatch) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getIdea(), other.getIdea()) - && Objects.equals(this.getSupervisor(), other.getSupervisor()) - && Objects.equals(this.getComment(), other.getComment()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getIdea(), other.getIdea()) && + Objects.equals(this.getSupervisor(), other.getSupervisor()) && + Objects.equals(this.getComment(), other.getComment()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatchServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatchServiceImpl.java index bc762d2834..7a01279d29 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatchServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/PreliminaryMatchServiceImpl.java @@ -1,19 +1,18 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; + +public class PreliminaryMatchServiceImpl + extends AbstractServiceImpl + implements PreliminaryMatchService { -public class PreliminaryMatchServiceImpl extends AbstractServiceImpl implements PreliminaryMatchService { private final IdeaService ideaService; @Inject - public PreliminaryMatchServiceImpl( - final Provider em, - final IdeaService ideaService) - { + public PreliminaryMatchServiceImpl(final Provider em, final IdeaService ideaService) { super(em, PreliminaryMatch.class, QPreliminaryMatch.preliminaryMatch); this.ideaService = ideaService; } @@ -28,11 +27,12 @@ public class PreliminaryMatchServiceImpl extends AbstractServiceImpl ideas = ideaService.findAll(filter); for (Idea idea : ideas) { final PreliminaryMatch byIdea = findByIdea(idea); - if (byIdea != null - && byIdea.getSupervisor() != null - && idea.getMatch().getSupervisor() == null - && idea.getType() == Idea.Type.STUDENT) - { + if ( + byIdea != null && + byIdea.getSupervisor() != null && + idea.getMatch().getSupervisor() == null && + idea.getType() == Idea.Type.STUDENT + ) { ideaService.changeSupervisor(idea, byIdea.getSupervisor(), null); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/ProgramService.java b/core/src/main/java/se/su/dsv/scipro/match/ProgramService.java index 618d39b726..fb4d22c97c 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ProgramService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ProgramService.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.match; +import java.util.List; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.Program; -import java.util.List; - public interface ProgramService extends GenericService { Program updateExternalProgram(Integer id, String name, String nameEn, String code); List getAutoCompletePrograms(String searchString, int limit); -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ProgramServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/ProgramServiceImpl.java index 925831af46..926d7c6299 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ProgramServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ProgramServiceImpl.java @@ -1,19 +1,19 @@ package se.su.dsv.scipro.match; -import jakarta.transaction.Transactional; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.Program; -import se.su.dsv.scipro.system.QProgram; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.List; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Program; +import se.su.dsv.scipro.system.QProgram; +import se.su.dsv.scipro.system.Sort; + +public class ProgramServiceImpl extends AbstractServiceImpl implements ProgramService { -public class ProgramServiceImpl extends AbstractServiceImpl implements ProgramService { @Inject public ProgramServiceImpl(Provider em) { super(em, Program.class, QProgram.program); @@ -41,4 +41,4 @@ public class ProgramServiceImpl extends AbstractServiceImpl implem private BooleanExpression nameContains(String input) { return QProgram.program.name.contains(input).or(QProgram.program.code.contains(input)); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartDeniedEvent.java b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartDeniedEvent.java index 1143f200a0..b7837eee06 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartDeniedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartDeniedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.match; public class ProjectStartDeniedEvent { + private final Idea idea; public ProjectStartDeniedEvent(final Idea idea) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartNotifier.java b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartNotifier.java index b9a0dad6a8..98b563df31 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartNotifier.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartNotifier.java @@ -2,19 +2,18 @@ package se.su.dsv.scipro.match; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; import se.su.dsv.scipro.notifications.NotificationController; import se.su.dsv.scipro.notifications.dataobject.IdeaEvent; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import jakarta.inject.Inject; - public class ProjectStartNotifier { + private final NotificationController notificationController; @Inject - public ProjectStartNotifier(final EventBus eventBus, - final NotificationController notificationController) { + public ProjectStartNotifier(final EventBus eventBus, final NotificationController notificationController) { eventBus.register(this); this.notificationController = notificationController; } diff --git a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartedEvent.java b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartedEvent.java index a2e2c410eb..0b169e549e 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/ProjectStartedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/match/ProjectStartedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.match; public class ProjectStartedEvent { + private final Idea idea; public ProjectStartedEvent(final Idea idea) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/SelectionError.java b/core/src/main/java/se/su/dsv/scipro/match/SelectionError.java index f81e56e0dd..39e7cddea2 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/SelectionError.java +++ b/core/src/main/java/se/su/dsv/scipro/match/SelectionError.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; public enum SelectionError { - ALREADY_MATCHED, APPLICATION_PERIOD_NOT_OPEN, TARGET_NUMBER_REACHED + ALREADY_MATCHED, + APPLICATION_PERIOD_NOT_OPEN, + TARGET_NUMBER_REACHED, } diff --git a/core/src/main/java/se/su/dsv/scipro/match/StudentPeriod.java b/core/src/main/java/se/su/dsv/scipro/match/StudentPeriod.java index 8bc8d77588..bb49f06c09 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/StudentPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/match/StudentPeriod.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.match; public abstract class StudentPeriod { + StudentPeriod() {} public abstract ApplicationPeriod getApplicationPeriod(); diff --git a/core/src/main/java/se/su/dsv/scipro/match/Target.java b/core/src/main/java/se/su/dsv/scipro/match/Target.java index 79d88f4514..c5af601d7d 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/Target.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Target.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.*; import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "target") public class Target implements Serializable { + @EmbeddedId private TargetId targetId = new TargetId(); @@ -59,12 +59,14 @@ public class Target implements Serializable { if (o == this) return true; if (!(o instanceof Target)) return false; final Target other = (Target) o; - return other.canEqual(this) - && Objects.equals(this.targetId, other.targetId) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) - && Objects.equals(this.getProjectType(), other.getProjectType()) - && this.getTarget() == other.getTarget(); + return ( + other.canEqual(this) && + Objects.equals(this.targetId, other.targetId) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getApplicationPeriod(), other.getApplicationPeriod()) && + Objects.equals(this.getProjectType(), other.getProjectType()) && + this.getTarget() == other.getTarget() + ); } protected boolean canEqual(final Object other) { @@ -74,11 +76,12 @@ public class Target implements Serializable { @Override public int hashCode() { return Objects.hash( - this.targetId, - this.getUser(), - this.getApplicationPeriod(), - this.getProjectType(), - this.getTarget()); + this.targetId, + this.getUser(), + this.getApplicationPeriod(), + this.getProjectType(), + this.getTarget() + ); } public void setTarget(int target) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/TargetId.java b/core/src/main/java/se/su/dsv/scipro/match/TargetId.java index e3ce937060..9eb9e7085e 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TargetId.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TargetId.java @@ -5,9 +5,9 @@ import jakarta.persistence.Embeddable; import java.io.Serializable; import java.util.Objects; - @Embeddable class TargetId implements Serializable { + @Basic private Long userId; @@ -22,10 +22,12 @@ class TargetId implements Serializable { if (o == this) return true; if (!(o instanceof TargetId)) return false; final TargetId other = (TargetId) o; - return other.canEqual(this) - && Objects.equals(this.userId, other.userId) - && Objects.equals(this.applicationPeriodId, other.applicationPeriodId) - && Objects.equals(this.projectTypeId, other.projectTypeId); + return ( + other.canEqual(this) && + Objects.equals(this.userId, other.userId) && + Objects.equals(this.applicationPeriodId, other.applicationPeriodId) && + Objects.equals(this.projectTypeId, other.projectTypeId) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/match/TargetRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/match/TargetRepositoryImpl.java index 1aa069ac8e..bd2092a283 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TargetRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TargetRepositoryImpl.java @@ -1,27 +1,31 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.AbstractRepository; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractRepository; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class TargetRepositoryImpl extends AbstractRepository implements TargetRepository { + @Inject public TargetRepositoryImpl(final Provider em) { super(em); } @Override - public Target getTarget(final User supervisor, final ApplicationPeriod applicationPeriod, final ProjectType projectType) { + public Target getTarget( + final User supervisor, + final ApplicationPeriod applicationPeriod, + final ProjectType projectType + ) { QTarget qTarget = QTarget.target1; Target target = from(qTarget) - .where(qTarget.user.eq(supervisor)) - .where(qTarget.applicationPeriod.eq(applicationPeriod)) - .where(qTarget.projectType.eq(projectType)) - .fetchOne(); + .where(qTarget.user.eq(supervisor)) + .where(qTarget.applicationPeriod.eq(applicationPeriod)) + .where(qTarget.projectType.eq(projectType)) + .fetchOne(); if (target == null) { target = new Target(supervisor, applicationPeriod, projectType); } diff --git a/core/src/main/java/se/su/dsv/scipro/match/TargetResult.java b/core/src/main/java/se/su/dsv/scipro/match/TargetResult.java index 4f36deff56..95d4aff53f 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TargetResult.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TargetResult.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.match; import java.io.Serializable; public class TargetResult implements Serializable { + private final Target target; private final long submittedAndTaken; diff --git a/core/src/main/java/se/su/dsv/scipro/match/TargetService.java b/core/src/main/java/se/su/dsv/scipro/match/TargetService.java index 5ab70093c7..1363c904bc 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TargetService.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TargetService.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.match; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Set; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public interface TargetService extends GenericService { Target findOne(ApplicationPeriod applicationPeriod, User supervisor, ProjectType projectType); @@ -15,6 +14,7 @@ public interface TargetService extends GenericService { int ideasLeftToCreateToMeetTarget(ApplicationPeriod ap, User e, ProjectType pc); class FilterParams implements Serializable { + private User supervisor; private ApplicationPeriod applicationPeriod; @@ -34,4 +34,4 @@ public interface TargetService extends GenericService { this.applicationPeriod = applicationPeriod; } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/match/TargetServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/match/TargetServiceImpl.java index b70b638da3..68215400ad 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TargetServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TargetServiceImpl.java @@ -2,15 +2,14 @@ package se.su.dsv.scipro.match; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.reusable.SciProUtilities; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.reusable.SciProUtilities; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class TargetServiceImpl extends AbstractServiceImpl implements TargetService { @@ -24,7 +23,9 @@ public class TargetServiceImpl extends AbstractServiceImpl imp @Override public Target findOne(ApplicationPeriod applicationPeriod, User supervisor, ProjectType projectType) { - Target t = findOne(byApplicationPeriod(applicationPeriod).and(bySupervisor(supervisor)).and(byLevel(projectType))); + Target t = findOne( + byApplicationPeriod(applicationPeriod).and(bySupervisor(supervisor)).and(byLevel(projectType)) + ); if (t == null) { t = new Target(supervisor, applicationPeriod, projectType); } @@ -57,7 +58,9 @@ public class TargetServiceImpl extends AbstractServiceImpl imp @Override public boolean hasTargetsLeft(ApplicationPeriod applicationPeriod, User supervisor, ProjectType projectType) { Target t = findOne(applicationPeriod, supervisor, projectType); - return (t.getTarget() > 0 && t.getTarget() > ideaService.countMatched(applicationPeriod, supervisor, projectType)); + return ( + t.getTarget() > 0 && t.getTarget() > ideaService.countMatched(applicationPeriod, supervisor, projectType) + ); } @Override @@ -96,7 +99,8 @@ public class TargetServiceImpl extends AbstractServiceImpl imp int availableIdeas = SciProUtilities.safeLongToInt(ideaService.count(countParams)); int ideasLeftToCreate = findOne(ap, supervisor, pc).getTarget() - availableIdeas; - ideasLeftToCreate = ideasLeftToCreate - SciProUtilities.safeLongToInt(ideaService.countMatched(ap, supervisor, pc)); + ideasLeftToCreate = + ideasLeftToCreate - SciProUtilities.safeLongToInt(ideaService.countMatched(ap, supervisor, pc)); if (ideasLeftToCreate > 0) { return ideasLeftToCreate; diff --git a/core/src/main/java/se/su/dsv/scipro/match/TholanderBox.java b/core/src/main/java/se/su/dsv/scipro/match/TholanderBox.java index e07f650485..56256bbe78 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/TholanderBox.java +++ b/core/src/main/java/se/su/dsv/scipro/match/TholanderBox.java @@ -6,6 +6,7 @@ import java.util.Objects; @Embeddable public class TholanderBox implements Serializable { + public static final int MAX_CHARS = 30000; private String background; @@ -63,12 +64,14 @@ public class TholanderBox implements Serializable { if (o == this) return true; if (!(o instanceof TholanderBox)) return false; final TholanderBox other = (TholanderBox) o; - return other.canEqual(this) - && Objects.equals(this.getBackground(), other.getBackground()) - && Objects.equals(this.getLiterature(), other.getLiterature()) - && Objects.equals(this.getProblem(), other.getProblem()) - && Objects.equals(this.getMethod(), other.getMethod()) - && Objects.equals(this.getInterests(), other.getInterests()); + return ( + other.canEqual(this) && + Objects.equals(this.getBackground(), other.getBackground()) && + Objects.equals(this.getLiterature(), other.getLiterature()) && + Objects.equals(this.getProblem(), other.getProblem()) && + Objects.equals(this.getMethod(), other.getMethod()) && + Objects.equals(this.getInterests(), other.getInterests()) + ); } protected boolean canEqual(final Object other) { @@ -78,10 +81,11 @@ public class TholanderBox implements Serializable { @Override public int hashCode() { return Objects.hash( - this.getBackground(), - this.getLiterature(), - this.getProblem(), - this.getMethod(), - this.getInterests()); + this.getBackground(), + this.getLiterature(), + this.getProblem(), + this.getMethod(), + this.getInterests() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/match/Watson.java b/core/src/main/java/se/su/dsv/scipro/match/Watson.java index 667b4d42b5..83bfb25329 100644 --- a/core/src/main/java/se/su/dsv/scipro/match/Watson.java +++ b/core/src/main/java/se/su/dsv/scipro/match/Watson.java @@ -6,6 +6,7 @@ import java.util.Objects; @Embeddable public class Watson implements Serializable { + private String what; private String why; private String theoryHow; @@ -57,11 +58,13 @@ public class Watson implements Serializable { if (this == o) return true; if (!(o instanceof Watson)) return false; final Watson watson = (Watson) o; - return Objects.equals(what, watson.what) - && Objects.equals(why, watson.why) - && Objects.equals(theoryHow, watson.theoryHow) - && Objects.equals(practicalHow, watson.practicalHow) - && Objects.equals(literature, watson.literature); + return ( + Objects.equals(what, watson.what) && + Objects.equals(why, watson.why) && + Objects.equals(theoryHow, watson.theoryHow) && + Objects.equals(practicalHow, watson.practicalHow) && + Objects.equals(literature, watson.literature) + ); } @Override @@ -71,12 +74,24 @@ public class Watson implements Serializable { @Override public String toString() { - return "Watson{" + - "what='" + what + '\'' + - ", why='" + why + '\'' + - ", theoryHow='" + theoryHow + '\'' + - ", practicalHow='" + practicalHow + '\'' + - ", literature='" + literature + '\'' + - '}'; + return ( + "Watson{" + + "what='" + + what + + '\'' + + ", why='" + + why + + '\'' + + ", theoryHow='" + + theoryHow + + '\'' + + ", practicalHow='" + + practicalHow + + '\'' + + ", literature='" + + literature + + '\'' + + '}' + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/MilestoneActivityTemplateRepository.java b/core/src/main/java/se/su/dsv/scipro/milestones/MilestoneActivityTemplateRepository.java index 8d8aaaeb33..c0e6bb30f1 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/MilestoneActivityTemplateRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/MilestoneActivityTemplateRepository.java @@ -1,27 +1,41 @@ package se.su.dsv.scipro.milestones; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; -import se.su.dsv.scipro.system.ProjectType; - import java.time.LocalDate; import java.util.*; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; @Transactional -public interface MilestoneActivityTemplateRepository extends JpaRepository, QueryDslPredicateExecutor { +public interface MilestoneActivityTemplateRepository + extends JpaRepository, QueryDslPredicateExecutor { + List findActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ); - List findActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate); + List findAllActivitiesByProjectType( + MilestoneActivityTemplate.Type type, + Collection projectType + ); - List findAllActivitiesByProjectType(MilestoneActivityTemplate.Type type, Collection projectType); - - List findAllActivitiesInOrder(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate); + List findAllActivitiesInOrder( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ); List findByMilestonePhase(MilestonePhaseTemplate milestonePhaseTemplate); - List findActiveByPhase(MilestonePhaseTemplate milestonePhaseTemplate, ProjectType projectType, LocalDate projectStartDate); + List findActiveByPhase( + MilestonePhaseTemplate milestonePhaseTemplate, + ProjectType projectType, + LocalDate projectStartDate + ); long countByMilestonePhase(MilestonePhaseTemplate milestonePhaseTemplate); @@ -29,5 +43,8 @@ public interface MilestoneActivityTemplateRepository extends JpaRepository + implements MilestoneActivityTemplateRepository { -public class MilestoneActivityTemplateRepositoryImpl extends GenericRepo implements MilestoneActivityTemplateRepository { @Inject public MilestoneActivityTemplateRepositoryImpl(Provider em) { super(em, MilestoneActivityTemplate.class, QMilestoneActivityTemplate.milestoneActivityTemplate); } @Override - public List findActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate) { + public List findActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; - return createQuery().where(allOf( - activity.type.eq(type), - activity.projectTypes.any().eq(projectType), - activity.deleted.isFalse(), - activity.dateCreated.before(java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant())) - )).fetch(); + return createQuery() + .where( + allOf( + activity.type.eq(type), + activity.projectTypes.any().eq(projectType), + activity.deleted.isFalse(), + activity.dateCreated.before( + java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()) + ) + ) + ) + .fetch(); } @Override - public List findAllActivitiesByProjectType(MilestoneActivityTemplate.Type type, Collection projectTypes) { + public List findAllActivitiesByProjectType( + MilestoneActivityTemplate.Type type, + Collection projectTypes + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; if (projectTypes.isEmpty()) { return Collections.emptyList(); } - return createQuery().where(allOf( - activity.type.eq(type), - activity.projectTypes.any().in(projectTypes), - activity.deleted.isFalse() - )).orderBy(activity.milestonePhaseTemplate.sortOrder.asc(), activity.sortOrder.asc()).fetch(); + return createQuery() + .where( + allOf(activity.type.eq(type), activity.projectTypes.any().in(projectTypes), activity.deleted.isFalse()) + ) + .orderBy(activity.milestonePhaseTemplate.sortOrder.asc(), activity.sortOrder.asc()) + .fetch(); } @Override - public List findAllActivitiesInOrder(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate) { + public List findAllActivitiesInOrder( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; - return createQuery().where(allOf( - activity.type.eq(type), - activity.projectTypes.any().eq(projectType), - activity.deleted.isFalse(), - activity.dateCreated.before(java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant())) - )).orderBy(activity.milestonePhaseTemplate.sortOrder.asc(), activity.sortOrder.asc()).fetch(); + return createQuery() + .where( + allOf( + activity.type.eq(type), + activity.projectTypes.any().eq(projectType), + activity.deleted.isFalse(), + activity.dateCreated.before( + java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()) + ) + ) + ) + .orderBy(activity.milestonePhaseTemplate.sortOrder.asc(), activity.sortOrder.asc()) + .fetch(); } @Override public List findByMilestonePhase(MilestonePhaseTemplate milestonePhaseTemplate) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; - return createQuery().where(activity.milestonePhaseTemplate.eq(milestonePhaseTemplate)).orderBy(activity.sortOrder.asc()).fetch(); + return createQuery() + .where(activity.milestonePhaseTemplate.eq(milestonePhaseTemplate)) + .orderBy(activity.sortOrder.asc()) + .fetch(); } @Override - public List findActiveByPhase(MilestonePhaseTemplate milestonePhaseTemplate, ProjectType projectType, LocalDate projectStartDate) { + public List findActiveByPhase( + MilestonePhaseTemplate milestonePhaseTemplate, + ProjectType projectType, + LocalDate projectStartDate + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; - return createQuery().where(allOf( - activity.milestonePhaseTemplate.eq(milestonePhaseTemplate), - activity.deleted.isFalse(), - activity.dateCreated.before(java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant())), - activity.projectTypes.any().eq(projectType) - )).orderBy(activity.sortOrder.asc()).fetch(); + return createQuery() + .where( + allOf( + activity.milestonePhaseTemplate.eq(milestonePhaseTemplate), + activity.deleted.isFalse(), + activity.dateCreated.before( + java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()) + ), + activity.projectTypes.any().eq(projectType) + ) + ) + .orderBy(activity.sortOrder.asc()) + .fetch(); } @Override public long countByMilestonePhase(MilestonePhaseTemplate milestonePhaseTemplate) { return createQuery() - .select(QMilestoneActivityTemplate.milestoneActivityTemplate.count()) - .where(QMilestoneActivityTemplate.milestoneActivityTemplate.milestonePhaseTemplate.eq(milestonePhaseTemplate)) - .fetchFirst(); + .select(QMilestoneActivityTemplate.milestoneActivityTemplate.count()) + .where( + QMilestoneActivityTemplate.milestoneActivityTemplate.milestonePhaseTemplate.eq(milestonePhaseTemplate) + ) + .fetchFirst(); } @Override - public long countActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate) { + public long countActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; Date date = Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - return createQuery().where(allOf( - activity.type.eq(type), - activity.projectTypes.any().eq(projectType), - activity.deleted.isFalse(), - activity.dateCreated.before(date), - activity.milestonePhaseTemplate.dateCreated.before(date) - )).select(activity.count()).fetchFirst(); + return createQuery() + .where( + allOf( + activity.type.eq(type), + activity.projectTypes.any().eq(projectType), + activity.deleted.isFalse(), + activity.dateCreated.before(date), + activity.milestonePhaseTemplate.dateCreated.before(date) + ) + ) + .select(activity.count()) + .fetchFirst(); } @Override public long countActivities(ProjectType projectType, LocalDate projectStartDate) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; Date date = Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - return createQuery().where(allOf( - activity.projectTypes.any().eq(projectType), - activity.deleted.isFalse(), - activity.dateCreated.before(date), - activity.milestonePhaseTemplate.dateCreated.before(date) - )).select(activity.count()).fetchFirst(); + return createQuery() + .where( + allOf( + activity.projectTypes.any().eq(projectType), + activity.deleted.isFalse(), + activity.dateCreated.before(date), + activity.milestonePhaseTemplate.dateCreated.before(date) + ) + ) + .select(activity.count()) + .fetchFirst(); } @Override - public MilestoneActivityTemplate findBySortOrderAndMilestonePhaseTemplate(int sortOrder, MilestonePhaseTemplate milestonePhaseTemplate) { + public MilestoneActivityTemplate findBySortOrderAndMilestonePhaseTemplate( + int sortOrder, + MilestonePhaseTemplate milestonePhaseTemplate + ) { QMilestoneActivityTemplate activity = QMilestoneActivityTemplate.milestoneActivityTemplate; - return createQuery().where(allOf( - activity.sortOrder.eq(sortOrder), - activity.milestonePhaseTemplate.eq(milestonePhaseTemplate) - )).fetchOne(); + return createQuery() + .where(allOf(activity.sortOrder.eq(sortOrder), activity.milestonePhaseTemplate.eq(milestonePhaseTemplate))) + .fetchOne(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/Milestone.java b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/Milestone.java index f72cf1954f..13b08fc4f7 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/Milestone.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/Milestone.java @@ -9,17 +9,17 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import java.util.Collections; +import java.util.List; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Collections; -import java.util.List; - @Entity @Table(name = "milestone") public class Milestone extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -49,9 +49,7 @@ public class Milestone extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected Milestone() { - - } + protected Milestone() {} public Milestone(Project project, MilestoneActivityTemplate activity) { this.project = project; diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestoneActivityTemplate.java b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestoneActivityTemplate.java index 583c558278..d00861939a 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestoneActivityTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestoneActivityTemplate.java @@ -14,18 +14,18 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.Event; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; -import se.su.dsv.scipro.system.ProjectType; - import java.io.Serializable; import java.util.Comparator; import java.util.HashSet; import java.util.Set; +import se.su.dsv.scipro.system.Event; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; +import se.su.dsv.scipro.system.ProjectType; @Entity @Table(name = "milestone_activity_template") public class MilestoneActivityTemplate extends LazyDeletableDomainObject { + public static final String CREATE_SEMINAR = "CREATE_SEMINAR"; public static final String THESIS_UPLOADED = "THESIS_UPLOADED"; public static final String PEER_REVIEW_ONE = "PEER_REVIEW_ONE"; @@ -82,17 +82,16 @@ public class MilestoneActivityTemplate extends LazyDeletableDomainObject { // table "milestone_activity_template_project_type". @ManyToMany @JoinTable( - name = "milestone_activity_template_project_type", - joinColumns = @JoinColumn(name = "milestone_activity_template_id"), - inverseJoinColumns = @JoinColumn(name = "project_type_id") + name = "milestone_activity_template_project_type", + joinColumns = @JoinColumn(name = "milestone_activity_template_id"), + inverseJoinColumns = @JoinColumn(name = "project_type_id") ) private Set projectTypes = new HashSet<>(); // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public MilestoneActivityTemplate() { - } + public MilestoneActivityTemplate() {} public MilestoneActivityTemplate(Type type) { this.type = type; @@ -198,13 +197,13 @@ public class MilestoneActivityTemplate extends LazyDeletableDomainObject { // ---------------------------------------------------------------------------------- // Nested classes and types // ---------------------------------------------------------------------------------- - public static class BySortOrderComparator implements Comparator, - Serializable { + public static class BySortOrderComparator implements Comparator, Serializable { + @Override public int compare(MilestoneActivityTemplate o1, MilestoneActivityTemplate o2) { int sortOrderResult = o1.sortOrder - o2.sortOrder; - int phaseSortOrderResult = o1.milestonePhaseTemplate.getSortOrder() - - o2.getMilestonePhaseTemplate().getSortOrder(); + int phaseSortOrderResult = + o1.milestonePhaseTemplate.getSortOrder() - o2.getMilestonePhaseTemplate().getSortOrder(); if (phaseSortOrderResult == 0) { return sortOrderResult; @@ -214,7 +213,8 @@ public class MilestoneActivityTemplate extends LazyDeletableDomainObject { } public enum Type { - PROJECT("Project"), STUDENT("Individual"); + PROJECT("Project"), + STUDENT("Individual"); private String asString; diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestonePhaseTemplate.java b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestonePhaseTemplate.java index 34b29d2fe4..d9c978a532 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestonePhaseTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/dataobjects/MilestonePhaseTemplate.java @@ -7,13 +7,13 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.LazyDeletableDomainObject; - import java.util.Objects; +import se.su.dsv.scipro.system.LazyDeletableDomainObject; @Entity @Table(name = "milestone_phase_template") public class MilestonePhaseTemplate extends LazyDeletableDomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -36,9 +36,7 @@ public class MilestonePhaseTemplate extends LazyDeletableDomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public MilestonePhaseTemplate() { - - } + public MilestonePhaseTemplate() {} public MilestonePhaseTemplate(String title, String description) { this.title = title; @@ -99,11 +97,13 @@ public class MilestonePhaseTemplate extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof MilestonePhaseTemplate)) return false; final MilestonePhaseTemplate other = (MilestonePhaseTemplate) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getTitle(), other.getTitle()) - && Objects.equals(this.getDescription(), other.getDescription()) - && this.getSortOrder() == other.getSortOrder(); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getTitle(), other.getTitle()) && + Objects.equals(this.getDescription(), other.getDescription()) && + this.getSortOrder() == other.getSortOrder() + ); } @Override @@ -113,6 +113,16 @@ public class MilestonePhaseTemplate extends LazyDeletableDomainObject { @Override public String toString() { - return "MilestonePhaseTemplate(id=" + this.getId() + ", title=" + this.getTitle() + ", description=" + this.getDescription() + ", sortOrder=" + this.getSortOrder() + ")"; + return ( + "MilestonePhaseTemplate(id=" + + this.getId() + + ", title=" + + this.getTitle() + + ", description=" + + this.getDescription() + + ", sortOrder=" + + this.getSortOrder() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/ActivateCompletedMilestonesOnNewProjects.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/ActivateCompletedMilestonesOnNewProjects.java index f952be4182..6607f9f701 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/ActivateCompletedMilestonesOnNewProjects.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/ActivateCompletedMilestonesOnNewProjects.java @@ -2,6 +2,8 @@ package se.su.dsv.scipro.milestones.service; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import java.util.*; import se.su.dsv.scipro.finalseminar.FinalSeminarActiveParticipation; import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; import se.su.dsv.scipro.finalseminar.FinalSeminarService; @@ -12,10 +14,8 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectCreatedEvent; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class ActivateCompletedMilestonesOnNewProjects { + private final FinalSeminarService finalSeminarService; private final PeerReviewService peerReviewService; private final MileStoneService mileStoneService; @@ -23,12 +23,12 @@ public class ActivateCompletedMilestonesOnNewProjects { @Inject public ActivateCompletedMilestonesOnNewProjects( - PeerReviewService peerReviewService, - MilestoneActivityTemplateService milestoneActivityTemplateService, - MileStoneService mileStoneService, - EventBus eventBus, - FinalSeminarService finalSeminarService) - { + PeerReviewService peerReviewService, + MilestoneActivityTemplateService milestoneActivityTemplateService, + MileStoneService mileStoneService, + EventBus eventBus, + FinalSeminarService finalSeminarService + ) { this.milestoneActivityTemplateService = milestoneActivityTemplateService; this.mileStoneService = mileStoneService; this.finalSeminarService = finalSeminarService; @@ -51,7 +51,10 @@ public class ActivateCompletedMilestonesOnNewProjects { } private void activateOppositionMilestone(Project project, User author) { - List opposing = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), author); + List opposing = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType( + project.getProjectType(), + author + ); for (FinalSeminarOpposition finalSeminarOpposition : opposing) { if (finalSeminarOpposition.isApproved()) { confirmMilestoneByEvent(project, author, "OppositionGradingEvent"); @@ -60,7 +63,10 @@ public class ActivateCompletedMilestonesOnNewProjects { } private void activateParticipationMilestone(Project project, User author) { - List participating = finalSeminarService.findUserParticipating(project, author); + List participating = finalSeminarService.findUserParticipating( + project, + author + ); for (FinalSeminarActiveParticipation participation : participating) { if (participation.isApproved()) { confirmMilestoneByEvent(project, author, "ParticipationGradingEvent"); @@ -76,10 +82,11 @@ public class ActivateCompletedMilestonesOnNewProjects { } private void activatePeerMilestones(Project project, User author) { - final long completedReviews = peerReviewService.findNonExpiredReviewsByProjectAuthor(author, project) - .stream() - .filter(PeerReview::isCompleted) - .count(); + final long completedReviews = peerReviewService + .findNonExpiredReviewsByProjectAuthor(author, project) + .stream() + .filter(PeerReview::isCompleted) + .count(); if (completedReviews >= 1) { confirmMilestoneByEvent(project, author, "FirstPeerReviewCompleted"); } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/MileStoneService.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/MileStoneService.java index 3765b1e798..41d5477742 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/MileStoneService.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/MileStoneService.java @@ -1,21 +1,19 @@ package se.su.dsv.scipro.milestones.service; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.milestones.dataobjects.Milestone; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Date; +import se.su.dsv.scipro.milestones.dataobjects.Milestone; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public interface MileStoneService extends GenericService { - long countProjectMilestones(Project project, boolean confirmed); long countMileStones(Project project, User student, boolean confirmed); @@ -37,6 +35,7 @@ public interface MileStoneService extends GenericService { Iterable findCompletedMilestones(MilestoneActivityTemplate activity, Filter filter, Pageable pageable); class Filter implements Serializable { + private Collection projectTypes = new ArrayList<>(); private Date projectStartedAfter; private Date projectStartedBefore; diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivator.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivator.java index e70062e7b1..145ee9d096 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivator.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivator.java @@ -2,6 +2,11 @@ package se.su.dsv.scipro.milestones.service; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Stream; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.finalseminar.*; import se.su.dsv.scipro.finalthesis.FinalThesisApprovedEvent; @@ -20,13 +25,8 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalApprovedEvent; import se.su.dsv.scipro.reviewing.RoughDraftApprovalRequestedEvent; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Stream; - public class MilestoneActivator { + private final MilestoneActivityTemplateService milestoneActivityTemplateService; private final MileStoneService mileStoneService; private final FinalSeminarService finalSeminarService; @@ -34,12 +34,12 @@ public class MilestoneActivator { @Inject public MilestoneActivator( - MilestoneActivityTemplateService milestoneActivityTemplateService, - MileStoneService mileStoneService, - EventBus eventBus, - FinalSeminarService finalSeminarService, - NotificationController notificationController) - { + MilestoneActivityTemplateService milestoneActivityTemplateService, + MileStoneService mileStoneService, + EventBus eventBus, + FinalSeminarService finalSeminarService, + NotificationController notificationController + ) { this.milestoneActivityTemplateService = milestoneActivityTemplateService; this.mileStoneService = mileStoneService; this.finalSeminarService = finalSeminarService; @@ -54,23 +54,35 @@ public class MilestoneActivator { @Subscribe public void participationApproved(ParticipationApprovedEvent event) { - List activeParticipations = finalSeminarService.findUserParticipating(event.getProject(), event.getStudent()); - long completedParticipations = activeParticipations.stream() - .filter(FinalSeminarParticipation::isApproved) - .count(); - int minimumActiveParticipationsToBeGraded = event.getProject() - .getProjectType() - .getProjectTypeSettings() - .getMinActiveParticipationsToBeGraded(); + List activeParticipations = finalSeminarService.findUserParticipating( + event.getProject(), + event.getStudent() + ); + long completedParticipations = activeParticipations + .stream() + .filter(FinalSeminarParticipation::isApproved) + .count(); + int minimumActiveParticipationsToBeGraded = event + .getProject() + .getProjectType() + .getProjectTypeSettings() + .getMinActiveParticipationsToBeGraded(); if (completedParticipations >= minimumActiveParticipationsToBeGraded) { activateIndividualMilestone(Set.of("ParticipationGradingEvent"), event.getProject(), event.getStudent()); } else { NotificationSource notificationSource = new NotificationSource(); notificationSource.setMessage(event.getFinalSeminar().getProjectTitle()); - notificationSource.setAdditionalMessage(Long.toString(minimumActiveParticipationsToBeGraded - completedParticipations)); + notificationSource.setAdditionalMessage( + Long.toString(minimumActiveParticipationsToBeGraded - completedParticipations) + ); Member recipient = new Member(event.getStudent(), Member.Type.AUTHOR); Set recipients = Set.of(recipient); - notificationController.notifyCustomProject(event.getProject(), ProjectEvent.Event.PARTICIPATION_APPROVED, notificationSource, recipients); + notificationController.notifyCustomProject( + event.getProject(), + ProjectEvent.Event.PARTICIPATION_APPROVED, + notificationSource, + recipients + ); } } @@ -158,9 +170,9 @@ public class MilestoneActivator { } private void setIndividualMilestone(Set eventNames, Project project, User student, boolean confirmed) { - getMilestoneActivities(eventNames) - .forEach(milestoneActivity -> - mileStoneService.setConfirmed(project, student, milestoneActivity, confirmed)); + getMilestoneActivities(eventNames).forEach(milestoneActivity -> + mileStoneService.setConfirmed(project, student, milestoneActivity, confirmed) + ); } private void activateProjectMilestone(Set eventNames, Project project) { @@ -172,14 +184,12 @@ public class MilestoneActivator { } private void setProjectMilestone(Set eventNames, Project project, boolean confirmed) { - getMilestoneActivities(eventNames) - .forEach(milestoneActivity -> - mileStoneService.setConfirmed(project, milestoneActivity, confirmed)); + getMilestoneActivities(eventNames).forEach(milestoneActivity -> + mileStoneService.setConfirmed(project, milestoneActivity, confirmed) + ); } private Stream getMilestoneActivities(Set eventNames) { - return eventNames.stream() - .map(milestoneActivityTemplateService::findByEvent) - .filter(Objects::nonNull); + return eventNames.stream().map(milestoneActivityTemplateService::findByEvent).filter(Objects::nonNull); } } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivityTemplateService.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivityTemplateService.java index 564bbc1e04..4563ef46ac 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivityTemplateService.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneActivityTemplateService.java @@ -1,22 +1,26 @@ package se.su.dsv.scipro.milestones.service; - +import java.time.LocalDate; +import java.util.*; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.springdata.SortOrderService; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.*; - public interface MilestoneActivityTemplateService extends SortOrderService { - List findAll(); - List getActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate); + List getActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ); - List getAllActivities(MilestoneActivityTemplate.Type type, Collection projectTypes); + List getAllActivities( + MilestoneActivityTemplate.Type type, + Collection projectTypes + ); List findByMileStonePhase(MilestonePhaseTemplate milestonePhaseTemplate); @@ -26,7 +30,6 @@ public interface MilestoneActivityTemplateService extends SortOrderService { - List findAll(Sort sort); List findAllActive(LocalDate projectStartDate); S save(S phase); - } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneStatisticsService.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneStatisticsService.java index abc4841d51..a67117d477 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneStatisticsService.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/MilestoneStatisticsService.java @@ -1,27 +1,31 @@ package se.su.dsv.scipro.milestones.service; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public interface MilestoneStatisticsService { Long median(Filter filter); Long countCompletedBoth(Filter filter); Long countNotCompletedBoth(Filter filter); - List getProgressedProjects(MilestoneActivityTemplate completed, MilestoneActivityTemplate notCompleted, Pageable pageRequest); + List getProgressedProjects( + MilestoneActivityTemplate completed, + MilestoneActivityTemplate notCompleted, + Pageable pageRequest + ); long countProgressedProjects(MilestoneActivityTemplate completed, MilestoneActivityTemplate notCompleted); class Filter implements Serializable { + private Date createdAfter; private Date createdBefore; private Collection projectTypes; @@ -91,14 +95,16 @@ public interface MilestoneStatisticsService { if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getCreatedAfter(), other.getCreatedAfter()) - && Objects.equals(this.getCreatedBefore(), other.getCreatedBefore()) - && Objects.equals(this.getProjectTypes(), other.getProjectTypes()) - && Objects.equals(this.getStatuses(), other.getStatuses()) - && Objects.equals(this.getHeadSupervisor(), other.getHeadSupervisor()) - && Objects.equals(this.getFirstMilestone(), other.getFirstMilestone()) - && Objects.equals(this.getSecondMilestone(), other.getSecondMilestone()); + return ( + other.canEqual(this) && + Objects.equals(this.getCreatedAfter(), other.getCreatedAfter()) && + Objects.equals(this.getCreatedBefore(), other.getCreatedBefore()) && + Objects.equals(this.getProjectTypes(), other.getProjectTypes()) && + Objects.equals(this.getStatuses(), other.getStatuses()) && + Objects.equals(this.getHeadSupervisor(), other.getHeadSupervisor()) && + Objects.equals(this.getFirstMilestone(), other.getFirstMilestone()) && + Objects.equals(this.getSecondMilestone(), other.getSecondMilestone()) + ); } protected boolean canEqual(final Object other) { @@ -108,18 +114,35 @@ public interface MilestoneStatisticsService { @Override public int hashCode() { return Objects.hash( - this.getCreatedAfter(), - this.getCreatedBefore(), - this.getProjectTypes(), - this.getStatuses(), - this.getHeadSupervisor(), - this.getFirstMilestone(), - this.getSecondMilestone()); + this.getCreatedAfter(), + this.getCreatedBefore(), + this.getProjectTypes(), + this.getStatuses(), + this.getHeadSupervisor(), + this.getFirstMilestone(), + this.getSecondMilestone() + ); } @Override public String toString() { - return "MilestoneStatisticsService.Filter(createdAfter=" + this.getCreatedAfter() + ", createdBefore=" + this.getCreatedBefore() + ", projectTypes=" + this.getProjectTypes() + ", statuses=" + this.getStatuses() + ", headSupervisor=" + this.getHeadSupervisor() + ", firstMilestone=" + this.getFirstMilestone() + ", secondMilestone=" + this.getSecondMilestone() + ")"; + return ( + "MilestoneStatisticsService.Filter(createdAfter=" + + this.getCreatedAfter() + + ", createdBefore=" + + this.getCreatedBefore() + + ", projectTypes=" + + this.getProjectTypes() + + ", statuses=" + + this.getStatuses() + + ", headSupervisor=" + + this.getHeadSupervisor() + + ", firstMilestone=" + + this.getFirstMilestone() + + ", secondMilestone=" + + this.getSecondMilestone() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImpl.java index f3727f39fe..868ffb8829 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImpl.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.milestones.service.impl; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; import se.su.dsv.scipro.milestones.MilestoneActivityTemplateRepository; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; @@ -9,16 +12,14 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.reusable.SciProUtilities; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTemplateService { private final MilestoneActivityTemplateRepository milestoneActivityTemplateRepository; @Inject - public MilestoneActivityTemplateServiceImpl(final MilestoneActivityTemplateRepository milestoneActivityTemplateRepository) { + public MilestoneActivityTemplateServiceImpl( + final MilestoneActivityTemplateRepository milestoneActivityTemplateRepository + ) { this.milestoneActivityTemplateRepository = milestoneActivityTemplateRepository; } @@ -28,12 +29,19 @@ public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTe } @Override - public List getActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate) { + public List getActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ) { return milestoneActivityTemplateRepository.findActivities(type, projectType, projectStartDate); } @Override - public List getAllActivities(MilestoneActivityTemplate.Type type, Collection projectTypes) { + public List getAllActivities( + MilestoneActivityTemplate.Type type, + Collection projectTypes + ) { return milestoneActivityTemplateRepository.findAllActivitiesByProjectType(type, projectTypes); } @@ -43,24 +51,49 @@ public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTe } @Override - public List findActiveByPhase(MilestonePhaseTemplate milestonePhaseTemplate, Project project) { - return milestoneActivityTemplateRepository.findActiveByPhase(milestonePhaseTemplate, project.getProjectType(), project.getStartDate()); + public List findActiveByPhase( + MilestonePhaseTemplate milestonePhaseTemplate, + Project project + ) { + return milestoneActivityTemplateRepository.findActiveByPhase( + milestonePhaseTemplate, + project.getProjectType(), + project.getStartDate() + ); } @Override public List getActivitiesInOrder(MilestoneActivityTemplate.Type type, Project project) { - return milestoneActivityTemplateRepository.findAllActivitiesInOrder(type, project.getProjectType(), project.getStartDate()); + return milestoneActivityTemplateRepository.findAllActivitiesInOrder( + type, + project.getProjectType(), + project.getStartDate() + ); } @Override - public Long countActivities(MilestoneActivityTemplate.Type type, ProjectType projectType, LocalDate projectStartDate) { + public Long countActivities( + MilestoneActivityTemplate.Type type, + ProjectType projectType, + LocalDate projectStartDate + ) { return milestoneActivityTemplateRepository.countActivities(type, projectType, projectStartDate); } @Override - public MilestoneActivityTemplate save(MilestoneActivityTemplate activity, MilestonePhaseTemplate milestonePhaseTemplate) { - if ((activity.getId() == null || activity.getId() == 0) || !activity.getMilestonePhaseTemplate().equals(milestonePhaseTemplate)) { - activity.setSortOrder(SciProUtilities.safeLongToInt(milestoneActivityTemplateRepository.countByMilestonePhase(activity.getMilestonePhaseTemplate()))); + public MilestoneActivityTemplate save( + MilestoneActivityTemplate activity, + MilestonePhaseTemplate milestonePhaseTemplate + ) { + if ( + (activity.getId() == null || activity.getId() == 0) || + !activity.getMilestonePhaseTemplate().equals(milestonePhaseTemplate) + ) { + activity.setSortOrder( + SciProUtilities.safeLongToInt( + milestoneActivityTemplateRepository.countByMilestonePhase(activity.getMilestonePhaseTemplate()) + ) + ); } return milestoneActivityTemplateRepository.save(activity); } @@ -72,13 +105,19 @@ public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTe @Override public MilestoneActivityTemplate findByEvent(String eventName) { - return milestoneActivityTemplateRepository.findOne(QMilestoneActivityTemplate.milestoneActivityTemplate.activatedBy.name.eq(eventName)); + return milestoneActivityTemplateRepository.findOne( + QMilestoneActivityTemplate.milestoneActivityTemplate.activatedBy.name.eq(eventName) + ); } @Override public void moveUp(MilestoneActivityTemplate activity) { int current = activity.getSortOrder(); - MilestoneActivityTemplate downActivity = milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(current - 1, activity.getMilestonePhaseTemplate()); + MilestoneActivityTemplate downActivity = + milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate( + current - 1, + activity.getMilestonePhaseTemplate() + ); if (downActivity != null) { downActivity.setSortOrder(current); activity.setSortOrder(current - 1); @@ -90,7 +129,11 @@ public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTe @Override public void moveDown(MilestoneActivityTemplate activity) { int current = activity.getSortOrder(); - MilestoneActivityTemplate upActivity = milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(current + 1, activity.getMilestonePhaseTemplate()); + MilestoneActivityTemplate upActivity = + milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate( + current + 1, + activity.getMilestonePhaseTemplate() + ); if (upActivity != null) { upActivity.setSortOrder(current); activity.setSortOrder(current + 1); @@ -98,5 +141,4 @@ public class MilestoneActivityTemplateServiceImpl implements MilestoneActivityTe milestoneActivityTemplateRepository.save(upActivity); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImpl.java index 197e947bda..5121d50522 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImpl.java @@ -1,23 +1,24 @@ package se.su.dsv.scipro.milestones.service.impl; +import static com.querydsl.core.types.dsl.Expressions.allOf; + +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.Sort; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.*; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.milestones.dataobjects.QMilestonePhaseTemplate; import se.su.dsv.scipro.milestones.service.MilestonePhaseTemplateService; import se.su.dsv.scipro.reusable.SciProUtilities; import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Sort; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.*; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - -public class MilestonePhaseTemplateServiceImpl extends AbstractServiceImpl implements MilestonePhaseTemplateService { +public class MilestonePhaseTemplateServiceImpl + extends AbstractServiceImpl + implements MilestonePhaseTemplateService { @Inject public MilestonePhaseTemplateServiceImpl(Provider em) { @@ -33,9 +34,16 @@ public class MilestonePhaseTemplateServiceImpl extends AbstractServiceImpl findAllActive(LocalDate projectStartDate) { QMilestonePhaseTemplate template = QMilestonePhaseTemplate.milestonePhaseTemplate; return from(template) - .where(allOf(template.deleted.isFalse(), template.dateCreated.lt(java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant())))) - .orderBy(template.sortOrder.asc()) - .fetch(); + .where( + allOf( + template.deleted.isFalse(), + template.dateCreated.lt( + java.util.Date.from(projectStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()) + ) + ) + ) + .orderBy(template.sortOrder.asc()) + .fetch(); } @Override @@ -51,7 +59,9 @@ public class MilestonePhaseTemplateServiceImpl extends AbstractServiceImpl implements MileStoneService { private final NotificationController notificationController; @Inject - public MilestoneServiceImpl(final NotificationController notificationController, - Provider em) { + public MilestoneServiceImpl(final NotificationController notificationController, Provider em) { super(em, Milestone.class, QMilestone.milestone); this.notificationController = notificationController; } @@ -45,66 +43,94 @@ public class MilestoneServiceImpl extends AbstractServiceImpl i @Override public long countProjectMilestones(Project project, boolean confirmed) { QMilestone milestone = QMilestone.milestone; - return count(allOf(milestone.project.eq(project), milestone.confirmed.eq(confirmed), milestone.user.isNull(), milestone.activity.deleted.isFalse())); + return count( + allOf( + milestone.project.eq(project), + milestone.confirmed.eq(confirmed), + milestone.user.isNull(), + milestone.activity.deleted.isFalse() + ) + ); } @Override public long countMileStones(Project project, User student, boolean confirmed) { QMilestone milestone = QMilestone.milestone; - return count(allOf(milestone.project.eq(project), milestone.confirmed.eq(confirmed), milestone.user.eq(student))); + return count( + allOf(milestone.project.eq(project), milestone.confirmed.eq(confirmed), milestone.user.eq(student)) + ); } @Override @Transactional public void setConfirmed(Project project, MilestoneActivityTemplate activity, boolean confirmed) { if (confirmed) { - for (MilestoneActivityTemplate earlierActivity : getEarlierIncompleteProjectMilestoneActivities(project, activity)) { + for (MilestoneActivityTemplate earlierActivity : getEarlierIncompleteProjectMilestoneActivities( + project, + activity + )) { setConfirmed(project, null, earlierActivity, true); } } setConfirmed(project, null, activity, confirmed); } - private Iterable getEarlierIncompleteProjectMilestoneActivities(final Project project, final MilestoneActivityTemplate activity) { + private Iterable getEarlierIncompleteProjectMilestoneActivities( + final Project project, + final MilestoneActivityTemplate activity + ) { QMilestoneActivityTemplate q = QMilestoneActivityTemplate.milestoneActivityTemplate; QMilestone milestone = QMilestone.milestone; - return from(q).where( + return from(q) + .where( q.deleted.isFalse(), q.milestonePhaseTemplate.deleted.isFalse(), q.type.eq(MilestoneActivityTemplate.Type.PROJECT), q.projectTypes.any().eq(project.getProjectType()), anyOf( - allOf(q.sortOrder.lt(activity.getSortOrder()), q.milestonePhaseTemplate.eq(activity.getMilestonePhaseTemplate())), - q.milestonePhaseTemplate.sortOrder.lt(activity.getMilestonePhaseTemplate().getSortOrder()) - + allOf( + q.sortOrder.lt(activity.getSortOrder()), + q.milestonePhaseTemplate.eq(activity.getMilestonePhaseTemplate()) + ), + q.milestonePhaseTemplate.sortOrder.lt(activity.getMilestonePhaseTemplate().getSortOrder()) ), - new JPAQuery().from(milestone) - .where(milestone.activity.eq(q), milestone.confirmed.isTrue(), milestone.project.eq(project)) - .notExists()) - .orderBy(q.milestonePhaseTemplate.sortOrder.asc(), q.sortOrder.asc()) - .fetch(); + new JPAQuery() + .from(milestone) + .where(milestone.activity.eq(q), milestone.confirmed.isTrue(), milestone.project.eq(project)) + .notExists() + ) + .orderBy(q.milestonePhaseTemplate.sortOrder.asc(), q.sortOrder.asc()) + .fetch(); } @Override @Transactional public void setConfirmed(Project project, User student, MilestoneActivityTemplate activity, boolean confirmed) { - if (!project.hasModule(ProjectModule.MILESTONES)) { return; } - Milestone milestone = student == null ? getMileStone(project, activity) : getMileStone(project, student, activity); + Milestone milestone = student == null + ? getMileStone(project, activity) + : getMileStone(project, student, activity); milestone.setConfirmed(confirmed); milestone = save(milestone); NotificationSource source = new NotificationSource(); source.setMessage(activity.getTitle()); if (student == null) { - notificationController.notifyProject(project, confirmed ? ProjectEvent.Event.MILESTONE_CONFIRMED : ProjectEvent.Event.MILESTONE_REVOKED, source); + notificationController.notifyProject( + project, + confirmed ? ProjectEvent.Event.MILESTONE_CONFIRMED : ProjectEvent.Event.MILESTONE_REVOKED, + source + ); } else { - notificationController.notifyMileStone(milestone, confirmed ? MileStoneEvent.Event.MILESTONE_CONFIRMED : MileStoneEvent.Event.MILESTONE_REVOKED, source); + notificationController.notifyMileStone( + milestone, + confirmed ? MileStoneEvent.Event.MILESTONE_CONFIRMED : MileStoneEvent.Event.MILESTONE_REVOKED, + source + ); } - } @Override @@ -120,7 +146,9 @@ public class MilestoneServiceImpl extends AbstractServiceImpl i @Override public Milestone getMileStone(Project project, MilestoneActivityTemplate activity) { QMilestone qMilestone = QMilestone.milestone; - Milestone milestone = findOne(allOf(qMilestone.project.eq(project), qMilestone.activity.eq(activity), qMilestone.user.isNull())); + Milestone milestone = findOne( + allOf(qMilestone.project.eq(project), qMilestone.activity.eq(activity), qMilestone.user.isNull()) + ); if (milestone == null) { milestone = new Milestone(project, activity); } @@ -130,7 +158,9 @@ public class MilestoneServiceImpl extends AbstractServiceImpl i @Override public Milestone getMileStone(Project project, User student, MilestoneActivityTemplate activity) { QMilestone qMilestone = QMilestone.milestone; - Milestone milestone = findOne(allOf(qMilestone.project.eq(project), qMilestone.activity.eq(activity), qMilestone.user.eq(student))); + Milestone milestone = findOne( + allOf(qMilestone.project.eq(project), qMilestone.activity.eq(activity), qMilestone.user.eq(student)) + ); if (milestone == null) { milestone = new Milestone(project, student, activity); } @@ -143,17 +173,20 @@ public class MilestoneServiceImpl extends AbstractServiceImpl i return 0; } QMilestone mileStone = QMilestone.milestone; - return count( - mileStone.activity.eq(activity) - .and(mileStone.confirmed.isTrue() - .and(toPredicate(filter)))); + return count(mileStone.activity.eq(activity).and(mileStone.confirmed.isTrue().and(toPredicate(filter)))); } @Override - public List findCompletedMilestones(MilestoneActivityTemplate activity, Filter filter, Pageable pageable) { + public List findCompletedMilestones( + MilestoneActivityTemplate activity, + Filter filter, + Pageable pageable + ) { QMilestone mileStone = QMilestone.milestone; - return findAll(mileStone.activity.eq(activity).and(mileStone.confirmed.isTrue() - .and(toPredicate(filter))), pageable); + return findAll( + mileStone.activity.eq(activity).and(mileStone.confirmed.isTrue().and(toPredicate(filter))), + pageable + ); } private static Predicate toPredicate(Filter filter) { diff --git a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImpl.java index 93a1815dce..a1f8847676 100644 --- a/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImpl.java @@ -8,8 +8,10 @@ import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.StringPath; import com.querydsl.jpa.impl.JPAQuery; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.Sort; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.util.*; import se.su.dsv.scipro.milestones.dataobjects.Milestone; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.QMilestone; @@ -17,14 +19,11 @@ import se.su.dsv.scipro.milestones.service.MilestoneStatisticsService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.QProject; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.*; - public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsService { private final Provider entityManagerProvider; @@ -95,10 +94,11 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic } @Override - public long countProgressedProjects(final MilestoneActivityTemplate completed, final MilestoneActivityTemplate notCompleted) { - return progressedProjects(completed, notCompleted) - .select(QProject.project.count()) - .fetchFirst(); + public long countProgressedProjects( + final MilestoneActivityTemplate completed, + final MilestoneActivityTemplate notCompleted + ) { + return progressedProjects(completed, notCompleted).select(QProject.project.count()).fetchFirst(); } @Override @@ -106,14 +106,11 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic if (filter.getFirstMilestone() == null || filter.getSecondMilestone() == null) { return null; } - return notCompletedBothQuery(filter) - .select(QProject.project.count()) - .fetchFirst(); + return notCompletedBothQuery(filter).select(QProject.project.count()).fetchFirst(); } @Override public Long median(Filter filter) { - if (filter.getFirstMilestone() == null || filter.getSecondMilestone() == null) { return null; } @@ -122,10 +119,8 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic QMilestone secondMilestone = new QMilestone("secondMilestone"); List dates = completedBothQuery(filter, firstMilestone, secondMilestone) - .select(Projections.constructor(MyClass.class, - firstMilestone.lastModified, - secondMilestone.lastModified)) - .fetch(); + .select(Projections.constructor(MyClass.class, firstMilestone.lastModified, secondMilestone.lastModified)) + .fetch(); List differences = new ArrayList<>(); @@ -157,11 +152,12 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic return null; } return completedBothQuery(filter, new QMilestone("firstMilestone"), new QMilestone("secondMilestone")) - .select(QProject.project.count()) - .fetchFirst(); + .select(QProject.project.count()) + .fetchFirst(); } public static class MyClass { + private Date firstDate; private Date secondDate; @@ -181,12 +177,13 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic @Override public boolean equals(final Object o) { if (o == this) return true; - if (!(o instanceof MyClass)) - return false; + if (!(o instanceof MyClass)) return false; final MyClass other = (MyClass) o; - return other.canEqual(this) - && Objects.equals(this.getFirstDate(), other.getFirstDate()) - && Objects.equals(this.getSecondDate(), other.getSecondDate()); + return ( + other.canEqual(this) && + Objects.equals(this.getFirstDate(), other.getFirstDate()) && + Objects.equals(this.getSecondDate(), other.getSecondDate()) + ); } protected boolean canEqual(final Object other) { @@ -200,38 +197,54 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic @Override public String toString() { - return "MilestoneStatisticsServiceImpl.MyClass(firstDate=" + this.getFirstDate() + ", secondDate=" + this.getSecondDate() + ")"; + return ( + "MilestoneStatisticsServiceImpl.MyClass(firstDate=" + + this.getFirstDate() + + ", secondDate=" + + this.getSecondDate() + + ")" + ); } } - private JPAQuery completedBothQuery(Filter filter, - QMilestone firstMilestone, - QMilestone secondMilestone) { + private JPAQuery completedBothQuery(Filter filter, QMilestone firstMilestone, QMilestone secondMilestone) { return new JPAQuery<>(entityManagerProvider.get()) - .from(QProject.project, firstMilestone, secondMilestone) - .where(toPredicate(filter)) - .where(firstMilestone.project.eq(QProject.project), - firstMilestone.activity.eq(filter.getFirstMilestone()), - firstMilestone.confirmed.eq(true)) - .where(secondMilestone.project.eq(QProject.project), - secondMilestone.activity.eq(filter.getSecondMilestone()), - secondMilestone.confirmed.eq(true)); + .from(QProject.project, firstMilestone, secondMilestone) + .where(toPredicate(filter)) + .where( + firstMilestone.project.eq(QProject.project), + firstMilestone.activity.eq(filter.getFirstMilestone()), + firstMilestone.confirmed.eq(true) + ) + .where( + secondMilestone.project.eq(QProject.project), + secondMilestone.activity.eq(filter.getSecondMilestone()), + secondMilestone.confirmed.eq(true) + ); } private JPAQuery notCompletedBothQuery(Filter filter) { return new JPAQuery(entityManagerProvider.get()) - .from(QProject.project) - .where(toPredicate(filter)) - .where((milestoneIsComplete(filter.getFirstMilestone()).notExists()).or(milestoneIsComplete(filter.getSecondMilestone()).notExists())); + .from(QProject.project) + .where(toPredicate(filter)) + .where( + (milestoneIsComplete(filter.getFirstMilestone()).notExists()).or( + milestoneIsComplete(filter.getSecondMilestone()).notExists() + ) + ); } @Override - public List getProgressedProjects(final MilestoneActivityTemplate completed, final MilestoneActivityTemplate notCompleted, final Pageable pageable) { + public List getProgressedProjects( + final MilestoneActivityTemplate completed, + final MilestoneActivityTemplate notCompleted, + final Pageable pageable + ) { return progressedProjects(completed, notCompleted) - .offset(pageable.getOffset()) - .limit(pageable.getLimit()) - .orderBy(fromSort(pageable.getSort())) - .fetch(); + .offset(pageable.getOffset()) + .limit(pageable.getLimit()) + .orderBy(fromSort(pageable.getSort())) + .fetch(); } private OrderSpecifier fromSort(final Sort sort) { @@ -242,21 +255,23 @@ public class MilestoneStatisticsServiceImpl implements MilestoneStatisticsServic return sort.isAscending() ? path.asc() : path.desc(); } - private JPAQuery progressedProjects(final MilestoneActivityTemplate completed, final MilestoneActivityTemplate notCompleted) { + private JPAQuery progressedProjects( + final MilestoneActivityTemplate completed, + final MilestoneActivityTemplate notCompleted + ) { return new JPAQuery(entityManagerProvider.get()) - .from(QProject.project) - .where(milestoneIsComplete(completed).exists(), - milestoneIsComplete(notCompleted).notExists()); + .from(QProject.project) + .where(milestoneIsComplete(completed).exists(), milestoneIsComplete(notCompleted).notExists()); } private JPAQuery milestoneIsComplete(final MilestoneActivityTemplate completed) { final QMilestone milestone = QMilestone.milestone; return new JPAQuery() - .from(milestone) - .where( - milestone.project.eq(QProject.project), - milestone.activity.eq(completed), - milestone.confirmed.isTrue() - ); + .from(milestone) + .where( + milestone.project.eq(QProject.project), + milestone.activity.eq(completed), + milestone.confirmed.isTrue() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/misc/DaysServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/misc/DaysServiceImpl.java index 8d4c45cac4..1890dbde43 100644 --- a/core/src/main/java/se/su/dsv/scipro/misc/DaysServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/misc/DaysServiceImpl.java @@ -1,7 +1,5 @@ package se.su.dsv.scipro.misc; -import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriodService; - import jakarta.inject.Inject; import java.time.DayOfWeek; import java.time.Duration; @@ -9,6 +7,7 @@ import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; +import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriodService; public class DaysServiceImpl implements DaysService { @@ -51,9 +50,7 @@ public class DaysServiceImpl implements DaysService { public int workDaysBetween(final Date startDate, final Date endDate) { final java.time.LocalDate start = java.time.LocalDate.ofInstant(startDate.toInstant(), ZoneId.systemDefault()); final java.time.LocalDate end = java.time.LocalDate.ofInstant(endDate.toInstant(), ZoneId.systemDefault()); - return (int) start.datesUntil(end) - .filter(this::isWorkDay) - .count(); + return (int) start.datesUntil(end).filter(this::isWorkDay).count(); } @Override @@ -64,13 +61,11 @@ public class DaysServiceImpl implements DaysService { private LocalDate moveWorkDays(LocalDate date, int days, int delta) { if (days == 0) { return date; - } - else { + } else { final LocalDate dayBefore = date.plusDays(delta); if (isWorkDay(dayBefore)) { return moveWorkDays(dayBefore, days - 1, delta); - } - else { + } else { return moveWorkDays(dayBefore, days, delta); } } diff --git a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriod.java b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriod.java index 639da2f1f5..b0507b2664 100755 --- a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriod.java @@ -7,15 +7,15 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.DomainObject; - import java.time.LocalDate; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Cacheable(true) @Table(name = "non_work_day_period") public class NonWorkDayPeriod extends DomainObject { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -63,7 +63,17 @@ public class NonWorkDayPeriod extends DomainObject { @Override public String toString() { - return "NonWorkDayPeriod(id=" + this.getId() + ", startDate=" + this.getStartDate() + ", endDate=" + this.getEndDate() + ", comment=" + this.getComment() + ")"; + return ( + "NonWorkDayPeriod(id=" + + this.getId() + + ", startDate=" + + this.getStartDate() + + ", endDate=" + + this.getEndDate() + + ", comment=" + + this.getComment() + + ")" + ); } @Override @@ -71,12 +81,14 @@ public class NonWorkDayPeriod extends DomainObject { if (o == this) return true; if (!(o instanceof NonWorkDayPeriod)) return false; final NonWorkDayPeriod other = (NonWorkDayPeriod) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getStartDate(), other.getStartDate()) - && Objects.equals(this.getEndDate(), other.getEndDate()) - && Objects.equals(this.getComment(), other.getComment()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getStartDate(), other.getStartDate()) && + Objects.equals(this.getEndDate(), other.getEndDate()) && + Objects.equals(this.getComment(), other.getComment()) + ); } protected boolean canEqual(final Object other) { @@ -87,4 +99,4 @@ public class NonWorkDayPeriod extends DomainObject { public int hashCode() { return Objects.hash(this.getId(), this.getStartDate(), this.getEndDate(), this.getComment()); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodService.java b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodService.java index 88188b9379..79c1ea61cb 100755 --- a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodService.java +++ b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodService.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.nonworkperiod; -import se.su.dsv.scipro.system.GenericService; - import java.time.LocalDate; import java.util.Date; +import se.su.dsv.scipro.system.GenericService; public interface NonWorkDayPeriodService extends GenericService { boolean isNonWorkDay(Date date); diff --git a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImpl.java index 46eab7680c..7cd1d6d05c 100755 --- a/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImpl.java @@ -2,16 +2,18 @@ package se.su.dsv.scipro.nonworkperiod; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; +import se.su.dsv.scipro.system.AbstractServiceImpl; + +public class NonWorkDayPeriodServiceImpl + extends AbstractServiceImpl + implements NonWorkDayPeriodService { -public class NonWorkDayPeriodServiceImpl extends AbstractServiceImpl implements NonWorkDayPeriodService { @Inject public NonWorkDayPeriodServiceImpl(Provider em) { super(em, NonWorkDayPeriod.class, QNonWorkDayPeriod.nonWorkDayPeriod); @@ -19,19 +21,16 @@ public class NonWorkDayPeriodServiceImpl extends AbstractServiceImpl 0; } diff --git a/core/src/main/java/se/su/dsv/scipro/notes/Note.java b/core/src/main/java/se/su/dsv/scipro/notes/Note.java index 2133ef64e7..de63976084 100644 --- a/core/src/main/java/se/su/dsv/scipro/notes/Note.java +++ b/core/src/main/java/se/su/dsv/scipro/notes/Note.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.notes; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.*; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "note") @@ -49,7 +48,7 @@ public class Note extends DomainObject { @Override public String toString() { - return "Note(id=" + this.getId() + ", user=" + this.getUser() + ", content=" + this.getContent() + ")"; + return ("Note(id=" + this.getId() + ", user=" + this.getUser() + ", content=" + this.getContent() + ")"); } @Override @@ -57,8 +56,7 @@ public class Note extends DomainObject { if (o == this) return true; if (!(o instanceof Note)) return false; final Note other = (Note) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/notes/NoteService.java b/core/src/main/java/se/su/dsv/scipro/notes/NoteService.java index c99d6f3630..82012a624f 100755 --- a/core/src/main/java/se/su/dsv/scipro/notes/NoteService.java +++ b/core/src/main/java/se/su/dsv/scipro/notes/NoteService.java @@ -4,7 +4,5 @@ import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; public interface NoteService extends GenericService { - Note getNote(final User user); - } diff --git a/core/src/main/java/se/su/dsv/scipro/notes/NoteServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/notes/NoteServiceImpl.java index 58cb33dbc1..23d6e0a795 100755 --- a/core/src/main/java/se/su/dsv/scipro/notes/NoteServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notes/NoteServiceImpl.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.notes; import com.querydsl.core.types.dsl.BooleanExpression; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.User; public class NoteServiceImpl extends AbstractServiceImpl implements NoteService { @@ -24,11 +23,11 @@ public class NoteServiceImpl extends AbstractServiceImpl implements @Transactional public Note getNote(User user) { Note note = findOne(hasUser(user)); - if (note == null){ + if (note == null) { note = new Note(); note.setUser(user); return save(note); } return note; } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationController.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationController.java index efdf5425da..6b6e6ce0f9 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationController.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationController.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.notifications; +import java.util.Set; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.finalseminar.FinalSeminar; import se.su.dsv.scipro.group.Group; @@ -11,23 +12,44 @@ import se.su.dsv.scipro.peer.PeerReview; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.Set; - public interface NotificationController { - - Set notifyGroup(final Group group, final GroupEvent.Event event, final NotificationSource source, User user); + Set notifyGroup( + final Group group, + final GroupEvent.Event event, + final NotificationSource source, + User user + ); void notifyProject(final Project project, final ProjectEvent.Event event, final NotificationSource source); - void notifyCustomProject(final Project project, final ProjectEvent.Event event, final NotificationSource source, Set recipients); + void notifyCustomProject( + final Project project, + final ProjectEvent.Event event, + final NotificationSource source, + Set recipients + ); - Set notifyProjectForum(final ProjectForumEvent.Event event, final NotificationSource source, Project project); + Set notifyProjectForum( + final ProjectForumEvent.Event event, + final NotificationSource source, + Project project + ); - Set notifyProjectForum(final ProjectForumEvent.Event event, final NotificationSource source, Project project, User user); + Set notifyProjectForum( + final ProjectForumEvent.Event event, + final NotificationSource source, + Project project, + User user + ); void notifySeminar(final FinalSeminar seminar, final SeminarEvent.Event event, final NotificationSource source); - void notifyCustomSeminar(final FinalSeminar seminar, final SeminarEvent.Event event, final NotificationSource source, Set recipients); + void notifyCustomSeminar( + final FinalSeminar seminar, + final SeminarEvent.Event event, + final NotificationSource source, + Set recipients + ); void notifyPeer(final PeerReview review, final PeerEvent.Event event, final NotificationSource source); @@ -35,11 +57,14 @@ public interface NotificationController { void notifyIdea(final Idea idea, final IdeaEvent.Event event, final NotificationSource source); - void notifyIdeaWithCustomRecipients(Idea idea, IdeaEvent.Event event, NotificationSource source, final Set recipients); + void notifyIdeaWithCustomRecipients( + Idea idea, + IdeaEvent.Event event, + NotificationSource source, + final Set recipients + ); void notifyMileStone(final Milestone milestone, MileStoneEvent.Event event, final NotificationSource source); void notifyCustom(CustomEvent.Event event, NotificationSource source, Set recipients); } - - diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationControllerImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationControllerImpl.java index 0a4a6e08f4..80b62008fb 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationControllerImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationControllerImpl.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.notifications; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.finalseminar.FinalSeminar; import se.su.dsv.scipro.group.Group; @@ -18,14 +25,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.CurrentUser; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - public class NotificationControllerImpl implements NotificationController { private final NotificationService notificationService; @@ -37,11 +36,13 @@ public class NotificationControllerImpl implements NotificationController { @Inject public NotificationControllerImpl( - NotificationService notificationService, - NotificationMailFormatter notificationMailFormatter, - MailEventService mailEventService, - ReceiverConfigurationService receiverConfiguration, - DeliveryConfigurationService deliveryConfiguration, final Provider currentUserProvider) { + NotificationService notificationService, + NotificationMailFormatter notificationMailFormatter, + MailEventService mailEventService, + ReceiverConfigurationService receiverConfiguration, + DeliveryConfigurationService deliveryConfiguration, + final Provider currentUserProvider + ) { this.notificationService = notificationService; this.notificationMailFormatter = notificationMailFormatter; this.mailEventService = mailEventService; @@ -52,7 +53,7 @@ public class NotificationControllerImpl implements NotificationController { private Set notify(Set recipients, NotificationEvent data) { Set notifications = new HashSet<>(); - if (data.getCausedBy() == null){ + if (data.getCausedBy() == null) { data.setCausedBy(getUser()); } for (final Member member : recipients) { @@ -66,9 +67,21 @@ public class NotificationControllerImpl implements NotificationController { notification.setUser(user); notification.setNotificationEvent(data); - final Optional oUser = member.getType() == Member.Type.SUPERVISOR ? Optional.of(user) : Optional.empty(); - boolean mailDelivery = deliveryConfiguration.isDelivery(data.getType(), data.getEvent(), DeliveryMethod.MAIL, oUser); - boolean webDelivery = deliveryConfiguration.isDelivery(data.getType(), data.getEvent(), DeliveryMethod.WEB, oUser); + final Optional oUser = member.getType() == Member.Type.SUPERVISOR + ? Optional.of(user) + : Optional.empty(); + boolean mailDelivery = deliveryConfiguration.isDelivery( + data.getType(), + data.getEvent(), + DeliveryMethod.MAIL, + oUser + ); + boolean webDelivery = deliveryConfiguration.isDelivery( + data.getType(), + data.getEvent(), + DeliveryMethod.WEB, + oUser + ); if (webDelivery) { notificationService.save(notification); @@ -92,8 +105,7 @@ public class NotificationControllerImpl implements NotificationController { private User getUser() { try { return currentUserProvider.get().get(); - } - catch (RuntimeException ignored) { + } catch (RuntimeException ignored) { return null; } } @@ -112,7 +124,12 @@ public class NotificationControllerImpl implements NotificationController { } @Override - public void notifyIdeaWithCustomRecipients(Idea idea, IdeaEvent.Event event, NotificationSource source, final Set recipients) { + public void notifyIdeaWithCustomRecipients( + Idea idea, + IdeaEvent.Event event, + NotificationSource source, + final Set recipients + ) { IdeaEvent data = new IdeaEvent(); data.setIdea(idea); data.setEvent(event); @@ -120,9 +137,10 @@ public class NotificationControllerImpl implements NotificationController { data.setAdditionalSource(source.getAdditionalMessage()); // Have to make sure the custom set participants are actually set to receive - final Set filteredRecipients = recipients.stream() - .filter(m -> receiverConfiguration.isReceiving(Notification.Type.IDEA, event, m.getType())) - .collect(Collectors.toSet()); + final Set filteredRecipients = recipients + .stream() + .filter(m -> receiverConfiguration.isReceiving(Notification.Type.IDEA, event, m.getType())) + .collect(Collectors.toSet()); notify(filteredRecipients, data); } @@ -159,7 +177,12 @@ public class NotificationControllerImpl implements NotificationController { } @Override - public void notifyCustomProject(Project project, ProjectEvent.Event event, NotificationSource source, Set recipients) { + public void notifyCustomProject( + Project project, + ProjectEvent.Event event, + NotificationSource source, + Set recipients + ) { ProjectEvent data = new ProjectEvent(); data.setProject(project); data.setEvent(event); @@ -170,12 +193,21 @@ public class NotificationControllerImpl implements NotificationController { } @Override - public Set notifyProjectForum(ProjectForumEvent.Event event, NotificationSource source, Project project) { + public Set notifyProjectForum( + ProjectForumEvent.Event event, + NotificationSource source, + Project project + ) { return notifyProjectForum(event, source, project, null); } @Override - public Set notifyProjectForum(ProjectForumEvent.Event event, NotificationSource source, Project project, User user) { + public Set notifyProjectForum( + ProjectForumEvent.Event event, + NotificationSource source, + Project project, + User user + ) { ProjectForumEvent data = new ProjectForumEvent(); data.setProject(project); data.setEvent(event); @@ -188,15 +220,19 @@ public class NotificationControllerImpl implements NotificationController { @Override public void notifySeminar(FinalSeminar seminar, SeminarEvent.Event event, NotificationSource source) { - Set recipients; - recipients = getRecipients(Notification.Type.FINAL_SEMINAR, event, seminar.getMembers(), source); - notifyCustomSeminar(seminar, event, source, recipients); + recipients = getRecipients(Notification.Type.FINAL_SEMINAR, event, seminar.getMembers(), source); + notifyCustomSeminar(seminar, event, source, recipients); } @Override - public void notifyCustomSeminar(FinalSeminar seminar, SeminarEvent.Event event, NotificationSource source, Set recipients) { + public void notifyCustomSeminar( + FinalSeminar seminar, + SeminarEvent.Event event, + NotificationSource source, + Set recipients + ) { SeminarEvent data = new SeminarEvent(); data.setSeminar(seminar); data.setEvent(event); @@ -239,7 +275,12 @@ public class NotificationControllerImpl implements NotificationController { notify(recipients, data); } - private Set getRecipients(Notification.Type group, Enum event, List members, NotificationSource source) { + private Set getRecipients( + Notification.Type group, + Enum event, + List members, + NotificationSource source + ) { Set recipients = new HashSet<>(); for (Member member : members) { if (receiverConfiguration.isReceiving(group, event, member.getType())) { diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepository.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepository.java index ff8007c304..9144192b84 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepository.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.notifications; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; - import java.util.Optional; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; public interface NotificationEventRepository { Optional findOne(long id); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepositoryImpl.java index b6ea677fc6..033db0d0e4 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventRepositoryImpl.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.notifications; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; public class NotificationEventRepositoryImpl implements NotificationEventRepository { @@ -20,5 +19,4 @@ public class NotificationEventRepositoryImpl implements NotificationEventReposit public Optional findOne(final long id) { return Optional.ofNullable(entityManager.get().find(NotificationEvent.class, id)); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventService.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventService.java index 4045fa7222..61e4581d17 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventService.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.notifications; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; - import java.util.Optional; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; public interface NotificationEventService { Optional findOne(long id); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventServiceImpl.java index ba417323ac..544ac8a59a 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationEventServiceImpl.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.notifications; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; - import jakarta.inject.Inject; import java.util.Optional; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; public class NotificationEventServiceImpl implements NotificationEventService { + private final NotificationEventRepository notificationEventRepository; @Inject diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationService.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationService.java index 3bd0945418..9b8d5b16ec 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationService.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationService.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.notifications; +import java.io.Serializable; +import java.util.Collection; +import java.util.List; +import java.util.Objects; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; import se.su.dsv.scipro.project.Project; @@ -7,13 +11,8 @@ import se.su.dsv.scipro.system.FilteredService; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; -import java.io.Serializable; -import java.util.Collection; -import java.util.List; -import java.util.Objects; - -public interface NotificationService extends GenericService, FilteredService { - +public interface NotificationService + extends GenericService, FilteredService { long countUnread(User user); void markRead(User user); void setRead(User user, NotificationEvent notificationEvent, boolean read); @@ -21,6 +20,7 @@ public interface NotificationService extends GenericService, Collection findUnreadByUsers(List users); class Filter implements Serializable { + private User currentUser; private User fromUser; @@ -45,9 +45,11 @@ public interface NotificationService extends GenericService, if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getCurrentUser(), other.getCurrentUser()) - && Objects.equals(this.getFromUser(), other.getFromUser()); + return ( + other.canEqual(this) && + Objects.equals(this.getCurrentUser(), other.getCurrentUser()) && + Objects.equals(this.getFromUser(), other.getFromUser()) + ); } protected boolean canEqual(final Object other) { @@ -61,7 +63,13 @@ public interface NotificationService extends GenericService, @Override public String toString() { - return "NotificationService.Filter(currentUser=" + this.getCurrentUser() + ", fromUser=" + this.getFromUser() + ")"; + return ( + "NotificationService.Filter(currentUser=" + + this.getCurrentUser() + + ", fromUser=" + + this.getFromUser() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationServiceImpl.java index 5bbe68093e..a675451301 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/NotificationServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/NotificationServiceImpl.java @@ -1,32 +1,30 @@ package se.su.dsv.scipro.notifications; -import jakarta.transaction.Transactional; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; -import se.su.dsv.scipro.system.Pageable; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; import se.su.dsv.scipro.notifications.dataobject.QNotification; import se.su.dsv.scipro.notifications.dataobject.QProjectEvent; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class NotificationServiceImpl extends AbstractServiceImpl implements NotificationService { +public class NotificationServiceImpl extends AbstractServiceImpl implements NotificationService { public static final int EMPTY = 0; @Inject public NotificationServiceImpl(Provider em) { super(em, Notification.class, QNotification.notification); - } @Override @@ -41,7 +39,8 @@ public class NotificationServiceImpl extends AbstractServiceImpl unreadNotifications = findAll( - QNotification.notification.unread.isTrue().and(QNotification.notification.user.eq(user))); + QNotification.notification.unread.isTrue().and(QNotification.notification.user.eq(user)) + ); for (Notification unreadNotification : unreadNotifications) { unreadNotification.setUnread(false); @@ -53,8 +52,10 @@ public class NotificationServiceImpl extends AbstractServiceImpl notifications = findAll( - QNotification.notification.notificationEvent.eq(notificationEvent) - .and(QNotification.notification.user.eq(user))); + QNotification.notification.notificationEvent + .eq(notificationEvent) + .and(QNotification.notification.user.eq(user)) + ); for (Notification notification : notifications) { notification.setUnread(!read); @@ -69,9 +70,9 @@ public class NotificationServiceImpl extends AbstractServiceImpl) notificationsList) { notification.setUnread(!read); @@ -81,7 +82,7 @@ public class NotificationServiceImpl extends AbstractServiceImpl findUnreadByUsers(List users) { - if(users.isEmpty()) { + if (users.isEmpty()) { return new ArrayList<>(); } return findAll(QNotification.notification.unread.isTrue().and(QNotification.notification.user.in(users))); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/Notifications.java b/core/src/main/java/se/su/dsv/scipro/notifications/Notifications.java index 2f887614c9..00cbe6b0da 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/Notifications.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/Notifications.java @@ -2,6 +2,9 @@ package se.su.dsv.scipro.notifications; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.Set; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.finalseminar.FinalSeminarCancelledEvent; import se.su.dsv.scipro.finalseminar.FinalSeminarCreatedEvent; @@ -21,21 +24,18 @@ import se.su.dsv.scipro.project.ProjectCompletedEvent; import se.su.dsv.scipro.project.ProjectDeactivatedEvent; import se.su.dsv.scipro.project.ReviewerAssignedEvent; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import java.util.Set; - @Singleton public class Notifications { + private final NotificationController notificationController; private final NotificationService notificationService; @Inject public Notifications( - NotificationController notificationController, - NotificationService notificationService, - EventBus eventBus) - { + NotificationController notificationController, + NotificationService notificationService, + EventBus eventBus + ) { this(notificationController, notificationService); eventBus.register(this); } @@ -47,12 +47,20 @@ public class Notifications { @Subscribe public void finalSeminarThesisDeleted(FinalSeminarThesisDeletedEvent event) { - notificationController.notifySeminar(event.getFinalSeminar(), SeminarEvent.Event.THESIS_DELETED, new NotificationSource()); + notificationController.notifySeminar( + event.getFinalSeminar(), + SeminarEvent.Event.THESIS_DELETED, + new NotificationSource() + ); } @Subscribe public void finalSeminarScheduled(FinalSeminarCreatedEvent event) { - notificationController.notifySeminar(event.getFinalSeminar(), SeminarEvent.Event.CREATED, new NotificationSource()); + notificationController.notifySeminar( + event.getFinalSeminar(), + SeminarEvent.Event.CREATED, + new NotificationSource() + ); } @Subscribe @@ -71,36 +79,64 @@ public class Notifications { @Subscribe public void finalSeminarThesisUploaded(FinalSeminarThesisUploadedEvent event) { - notificationController.notifySeminar(event.getFinalSeminar(), SeminarEvent.Event.THESIS_UPLOADED, new NotificationSource()); + notificationController.notifySeminar( + event.getFinalSeminar(), + SeminarEvent.Event.THESIS_UPLOADED, + new NotificationSource() + ); - notificationController.notifySeminar(event.getFinalSeminar(), SeminarEvent.Event.THESIS_UPLOADED_OPPONENT, new NotificationSource()); + notificationController.notifySeminar( + event.getFinalSeminar(), + SeminarEvent.Event.THESIS_UPLOADED_OPPONENT, + new NotificationSource() + ); } @Subscribe public void peerRequestCancelled(PeerRequestCancelledEvent event) { - notificationController.notifyPeer(event.getPeerRequest(), PeerEvent.Event.REQUEST_DELETED, new NotificationSource()); + notificationController.notifyPeer( + event.getPeerRequest(), + PeerEvent.Event.REQUEST_DELETED, + new NotificationSource() + ); } @Subscribe public void peerRequestExpired(PeerRequestExpiredEvent event) { - notificationController.notifyPeer(event.getPeerRequest(), PeerEvent.Event.REQUEST_EXPIRED, new NotificationSource()); + notificationController.notifyPeer( + event.getPeerRequest(), + PeerEvent.Event.REQUEST_EXPIRED, + new NotificationSource() + ); } @Subscribe public void projectActivated(ProjectActivatedEvent event) { - notificationController.notifyProject(event.getProject(), ProjectEvent.Event.PROJECT_ACTIVATED, new NotificationSource()); + notificationController.notifyProject( + event.getProject(), + ProjectEvent.Event.PROJECT_ACTIVATED, + new NotificationSource() + ); } @Subscribe public void projectDeactivated(ProjectDeactivatedEvent event) { notificationService.setRead(event.getProject(), true); - notificationController.notifyProject(event.getProject(), ProjectEvent.Event.PROJECT_DEACTIVATED, new NotificationSource()); + notificationController.notifyProject( + event.getProject(), + ProjectEvent.Event.PROJECT_DEACTIVATED, + new NotificationSource() + ); } @Subscribe public void projectCompleted(ProjectCompletedEvent event) { notificationService.setRead(event.getProject(), true); - notificationController.notifyProject(event.getProject(), ProjectEvent.Event.COMPLETED, new NotificationSource()); + notificationController.notifyProject( + event.getProject(), + ProjectEvent.Event.COMPLETED, + new NotificationSource() + ); } @Subscribe @@ -110,7 +146,12 @@ public class Notifications { NotificationSource source = new NotificationSource(); source.setMessage(event.getFinalSeminar().getProjectTitle()); source.setAdditionalMessage(event.getOpposition().getFeedback()); - notificationController.notifyCustomProject(event.getProject(), ProjectEvent.Event.OPPOSITION_FAILED, source, recipients); + notificationController.notifyCustomProject( + event.getProject(), + ProjectEvent.Event.OPPOSITION_FAILED, + source, + recipients + ); } @Subscribe @@ -119,11 +160,20 @@ public class Notifications { Set recipients = Set.of(recipient); NotificationSource source = new NotificationSource(); source.setMessage(event.getFinalSeminar().getProjectTitle()); - notificationController.notifyCustomProject(event.getProject(), ProjectEvent.Event.PARTICIPATION_FAILED, source, recipients); + notificationController.notifyCustomProject( + event.getProject(), + ProjectEvent.Event.PARTICIPATION_FAILED, + source, + recipients + ); } @Subscribe public void reviewersChanged(ReviewerAssignedEvent event) { - notificationController.notifyProject(event.getProject(), ProjectEvent.Event.REVIEWERS_CHANGED, new NotificationSource()); + notificationController.notifyProject( + event.getProject(), + ProjectEvent.Event.REVIEWERS_CHANGED, + new NotificationSource() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/CustomEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/CustomEvent.java index f738fbf6c8..2f4180cbd1 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/CustomEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/CustomEvent.java @@ -2,17 +2,16 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import se.su.dsv.scipro.system.DomainObject; @Entity public class CustomEvent extends NotificationEvent { public enum Event { - IDEA_DELETED + IDEA_DELETED, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/GroupEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/GroupEvent.java index 079c0cb09a..196a105e15 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/GroupEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/GroupEvent.java @@ -1,65 +1,65 @@ -package se.su.dsv.scipro.notifications.dataobject; - -import jakarta.persistence.Basic; -import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.group.Group; -import se.su.dsv.scipro.system.DomainObject; - -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.ManyToOne; - -@Entity -public class GroupEvent extends NotificationEvent { - - public enum Event { - MESSAGE_THREAD_CREATED, MESSAGE_THREAD_REPLY - } - - @Basic - @Column(name = "event") - @Enumerated(EnumType.STRING) - private Event event; - - @ManyToOne - @JoinColumn(name = "project_group_id", referencedColumnName = "id") - private Group group; - - public GroupEvent() { - super(Notification.Type.GROUP); - } - - @Override - public Enum getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - - public Group getGroup() { - return group; - } - - public void setGroup(Group group) { - this.group = group; - } - - @Override - protected String getEntityTitle() { - return group.getTitle(); - } - - @Override - public boolean hasEntity() { - return group != null; - } - - @Override - public DomainObject getEntity() { - return group; - } -} +package se.su.dsv.scipro.notifications.dataobject; + +import jakarta.persistence.Basic; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.group.Group; +import se.su.dsv.scipro.system.DomainObject; + +@Entity +public class GroupEvent extends NotificationEvent { + + public enum Event { + MESSAGE_THREAD_CREATED, + MESSAGE_THREAD_REPLY, + } + + @Basic + @Column(name = "event") + @Enumerated(EnumType.STRING) + private Event event; + + @ManyToOne + @JoinColumn(name = "project_group_id", referencedColumnName = "id") + private Group group; + + public GroupEvent() { + super(Notification.Type.GROUP); + } + + @Override + public Enum getEvent() { + return event; + } + + public void setEvent(Event event) { + this.event = event; + } + + public Group getGroup() { + return group; + } + + public void setGroup(Group group) { + this.group = group; + } + + @Override + protected String getEntityTitle() { + return group.getTitle(); + } + + @Override + public boolean hasEntity() { + return group != null; + } + + @Override + public DomainObject getEntity() { + return group; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/IdeaEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/IdeaEvent.java index 54df3b315e..c199311202 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/IdeaEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/IdeaEvent.java @@ -2,21 +2,24 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.match.Idea; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.match.Idea; +import se.su.dsv.scipro.system.DomainObject; @Entity public class IdeaEvent extends NotificationEvent { public enum Event { - STATUS_CHANGE, PARTNER_ACCEPT, - ADDED_AS_PARTNER, FIRST_MEETING, REMOVED_AS_PARTNER, EXPORTED_FAIL + STATUS_CHANGE, + PARTNER_ACCEPT, + ADDED_AS_PARTNER, + FIRST_MEETING, + REMOVED_AS_PARTNER, + EXPORTED_FAIL, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/MileStoneEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/MileStoneEvent.java index f84a47be57..97bfc74146 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/MileStoneEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/MileStoneEvent.java @@ -1,97 +1,99 @@ -package se.su.dsv.scipro.notifications.dataobject; - -import jakarta.persistence.Basic; -import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.milestones.dataobjects.Milestone; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.ManyToOne; -import java.util.Objects; - -@Entity -public class MileStoneEvent extends NotificationEvent { - - public enum Event { - MILESTONE_CONFIRMED, MILESTONE_REVOKED - } - - @Basic - @Column(name = "event") - @Enumerated(EnumType.STRING) - private Event event; - - @ManyToOne - @JoinColumn(name = "milestone_id", referencedColumnName = "id") - private Milestone milestone; - - public MileStoneEvent() { - super(Notification.Type.MILESTONE); - } - - @Override - public Enum getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - - public Milestone getMilestone() { - return this.milestone; - } - - public void setMilestone(Milestone milestone) { - this.milestone = milestone; - } - - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof MileStoneEvent)) return false; - final MileStoneEvent other = (MileStoneEvent) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getMilestone(), other.getMilestone()) - && Objects.equals(this.getEvent(), other.getEvent()); - } - - @Override - public int hashCode() { - return Objects.hash(this.getMilestone(), this.getEvent()); - } - - @Override - public String toString() { - return "MileStoneEvent(milestone=" + this.getMilestone() + ", event=" + this.getEvent() + ")"; - } - - protected boolean canEqual(final Object other) { - return other instanceof MileStoneEvent; - } - - @Override - public Project getProject() { - return milestone.getProject(); - } - - @Override - protected String getEntityTitle() { - return milestone.getProject().getTitle(); - } - - @Override - public boolean hasEntity() { - return milestone != null; - } - - @Override - public DomainObject getEntity() { - return milestone; - } -} +package se.su.dsv.scipro.notifications.dataobject; + +import jakarta.persistence.Basic; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import java.util.Objects; +import se.su.dsv.scipro.milestones.dataobjects.Milestone; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; + +@Entity +public class MileStoneEvent extends NotificationEvent { + + public enum Event { + MILESTONE_CONFIRMED, + MILESTONE_REVOKED, + } + + @Basic + @Column(name = "event") + @Enumerated(EnumType.STRING) + private Event event; + + @ManyToOne + @JoinColumn(name = "milestone_id", referencedColumnName = "id") + private Milestone milestone; + + public MileStoneEvent() { + super(Notification.Type.MILESTONE); + } + + @Override + public Enum getEvent() { + return event; + } + + public void setEvent(Event event) { + this.event = event; + } + + public Milestone getMilestone() { + return this.milestone; + } + + public void setMilestone(Milestone milestone) { + this.milestone = milestone; + } + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof MileStoneEvent)) return false; + final MileStoneEvent other = (MileStoneEvent) o; + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getMilestone(), other.getMilestone()) && + Objects.equals(this.getEvent(), other.getEvent()) + ); + } + + @Override + public int hashCode() { + return Objects.hash(this.getMilestone(), this.getEvent()); + } + + @Override + public String toString() { + return ("MileStoneEvent(milestone=" + this.getMilestone() + ", event=" + this.getEvent() + ")"); + } + + protected boolean canEqual(final Object other) { + return other instanceof MileStoneEvent; + } + + @Override + public Project getProject() { + return milestone.getProject(); + } + + @Override + protected String getEntityTitle() { + return milestone.getProject().getTitle(); + } + + @Override + public boolean hasEntity() { + return milestone != null; + } + + @Override + public DomainObject getEntity() { + return milestone; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/Notification.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/Notification.java index 5102db88cd..e67925c2d5 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/Notification.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/Notification.java @@ -48,8 +48,7 @@ public class Notification extends DomainObject { // ---------------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------------- - public Notification() { - } + public Notification() {} // ---------------------------------------------------------------------------------- // Properties (Getters and Setters) @@ -134,7 +133,13 @@ public class Notification extends DomainObject { // Nested type // ---------------------------------------------------------------------------------- public enum Type { - PROJECT, IDEA, FINAL_SEMINAR, PEER, MILESTONE, - GROUP, FORUM, CUSTOM + PROJECT, + IDEA, + FINAL_SEMINAR, + PEER, + MILESTONE, + GROUP, + FORUM, + CUSTOM, } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationEvent.java index 6eb2f15ef4..5f5edf3e8a 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationEvent.java @@ -16,12 +16,11 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import java.util.Collection; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Collection; - @Entity @Table(name = "notification_data") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @@ -65,9 +64,7 @@ public abstract class NotificationEvent extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected NotificationEvent() { - - } + protected NotificationEvent() {} protected NotificationEvent(Notification.Type type) { this.type = type; diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationMail.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationMail.java index d040ea6ae0..d0c9744301 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationMail.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationMail.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.notifications.dataobject; public class NotificationMail { + private String subject; private String content; @@ -19,6 +20,6 @@ public class NotificationMail { @Override public String toString() { - return "NotificationMail[subject=" + subject + ", content=" + content + "]"; + return ("NotificationMail[subject=" + subject + ", content=" + content + "]"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationSource.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationSource.java index 96067bd553..2ede701ad5 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationSource.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/NotificationSource.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.notifications.dataobject; -import se.su.dsv.scipro.data.dataobjects.Member; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.data.dataobjects.Member; public class NotificationSource { @@ -11,9 +10,7 @@ public class NotificationSource { private String additionalMessage; private List additionalRecipients = new ArrayList<>(); - public NotificationSource() { - - } + public NotificationSource() {} /** * A message related to this source. Used to give more specific information @@ -39,5 +36,4 @@ public class NotificationSource { public List getAdditionalRecipients() { return additionalRecipients; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerEvent.java index 8ca7f15e9e..039ffe0b5e 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerEvent.java @@ -2,22 +2,24 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.peer.PeerReview; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.peer.PeerReview; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity public class PeerEvent extends NotificationEvent { public enum Event { - REVIEW_COMPLETED, REVIEW_COMMENT, REVIEW_ACCEPTED, REQUEST_DELETED, - REQUEST_EXPIRED + REVIEW_COMPLETED, + REVIEW_COMMENT, + REVIEW_ACCEPTED, + REQUEST_DELETED, + REQUEST_EXPIRED, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerRequestEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerRequestEvent.java index 72f6dac062..9e8873a315 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerRequestEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/PeerRequestEvent.java @@ -2,15 +2,14 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.peer.PeerRequest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.peer.PeerRequest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity public class PeerRequestEvent extends NotificationEvent { diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectEvent.java index ae72d48f16..99fa21978a 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectEvent.java @@ -2,29 +2,55 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity public class ProjectEvent extends NotificationEvent { public enum Event { - CREATED, AUTHORS_CHANGED, HEAD_SUPERVISOR_CHANGED, REVIEWERS_CHANGED, CO_SUPERVISOR_CHANGED, - STATE_CHANGED, ACTIVITY_ADDED, ACTIVITY_REMOVED, ACTIVITY_EDITED, FILE_UPLOADED, CHECKLIST_ANSWERED, - CHECKLIST_ADDED, MILESTONE_CONFIRMED, MILESTONE_REVOKED, FINAL_THESIS_APPROVED, FILE_SIZE_TOO_BIG, - FINAL_THESIS_UPLOADED, PROJECT_ACTIVATED, PROJECT_DEACTIVATED, FINAL_SEMINAR_APPROVAL_REQUESTED, - FINAL_SEMINAR_APPROVAL_APPROVED, FINAL_SEMINAR_APPROVAL_REJECTED, ROUGH_DRAFT_APPROVAL_REQUESTED, - ROUGH_DRAFT_APPROVAL_APPROVED, ROUGH_DRAFT_APPROVAL_REJECTED, REVIEWER_GRADING_REPORT_SUBMITTED, - ONE_YEAR_PASSED_FROM_LATEST_ANNUAL_REVIEW, SUPERVISOR_GRADING_INITIAL_ASSESSMENT_DONE, - EXPORTED_SUCCESS, REVIEWER_GRADING_INITIAL_ASSESSMENT_DONE, FIRST_MEETING, OPPOSITION_FAILED, - PARTICIPATION_APPROVED, COMPLETED, PARTICIPATION_FAILED, REFLECTION_IMPROVEMENTS_REQUESTED, - REFLECTION_IMPROVEMENTS_SUBMITTED + CREATED, + AUTHORS_CHANGED, + HEAD_SUPERVISOR_CHANGED, + REVIEWERS_CHANGED, + CO_SUPERVISOR_CHANGED, + STATE_CHANGED, + ACTIVITY_ADDED, + ACTIVITY_REMOVED, + ACTIVITY_EDITED, + FILE_UPLOADED, + CHECKLIST_ANSWERED, + CHECKLIST_ADDED, + MILESTONE_CONFIRMED, + MILESTONE_REVOKED, + FINAL_THESIS_APPROVED, + FILE_SIZE_TOO_BIG, + FINAL_THESIS_UPLOADED, + PROJECT_ACTIVATED, + PROJECT_DEACTIVATED, + FINAL_SEMINAR_APPROVAL_REQUESTED, + FINAL_SEMINAR_APPROVAL_APPROVED, + FINAL_SEMINAR_APPROVAL_REJECTED, + ROUGH_DRAFT_APPROVAL_REQUESTED, + ROUGH_DRAFT_APPROVAL_APPROVED, + ROUGH_DRAFT_APPROVAL_REJECTED, + REVIEWER_GRADING_REPORT_SUBMITTED, + ONE_YEAR_PASSED_FROM_LATEST_ANNUAL_REVIEW, + SUPERVISOR_GRADING_INITIAL_ASSESSMENT_DONE, + EXPORTED_SUCCESS, + REVIEWER_GRADING_INITIAL_ASSESSMENT_DONE, + FIRST_MEETING, + OPPOSITION_FAILED, + PARTICIPATION_APPROVED, + COMPLETED, + PARTICIPATION_FAILED, + REFLECTION_IMPROVEMENTS_REQUESTED, + REFLECTION_IMPROVEMENTS_SUBMITTED, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectForumEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectForumEvent.java index c95ec8bf05..ffe5aa8f44 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectForumEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/ProjectForumEvent.java @@ -2,20 +2,21 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; -import jakarta.persistence.JoinColumn; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; @Entity public class ProjectForumEvent extends NotificationEvent { public enum Event { - NEW_FORUM_POST, NEW_FORUM_POST_COMMENT, NEW_REVIEWER_INTERACTION + NEW_FORUM_POST, + NEW_FORUM_POST_COMMENT, + NEW_REVIEWER_INTERACTION, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/SeminarEvent.java b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/SeminarEvent.java index dedad4ca0a..e2a6484ed6 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/SeminarEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/dataobject/SeminarEvent.java @@ -2,22 +2,30 @@ package se.su.dsv.scipro.notifications.dataobject; import jakarta.persistence.Basic; import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; import se.su.dsv.scipro.finalseminar.FinalSeminar; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DomainObject; -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.ManyToOne; - @Entity public class SeminarEvent extends NotificationEvent { - public enum Event { CREATED, ROOM_CHANGED, DATE_CHANGED, OPPOSITION_CHANGED, - PARTICIPATION_CHANGED, THESIS_UPLOADED, THESIS_UPLOADED_OPPONENT, - OPPOSITION_REPORT_UPLOADED, THESIS_DELETED, THESIS_UPLOAD_REMIND, CANCELLED + public enum Event { + CREATED, + ROOM_CHANGED, + DATE_CHANGED, + OPPOSITION_CHANGED, + PARTICIPATION_CHANGED, + THESIS_UPLOADED, + THESIS_UPLOADED_OPPONENT, + OPPOSITION_REPORT_UPLOADED, + THESIS_DELETED, + THESIS_UPLOAD_REMIND, + CANCELLED, } @Basic diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/NotificationMailFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/NotificationMailFormatter.java index 6cb749236c..71b4aed57a 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/NotificationMailFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/NotificationMailFormatter.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.notifications.interfaces; +import java.util.Collection; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.NotificationMail; -import java.util.Collection; - public interface NotificationMailFormatter { NotificationMail format(Notification notification); NotificationMail compile(Collection notifications); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/AbstractEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/AbstractEventFormatter.java index 059a8be8a2..c62428f278 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/AbstractEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/AbstractEventFormatter.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.notifications.interfaces.impl; -import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; -import se.su.dsv.scipro.system.User; - import java.text.MessageFormat; import java.util.Collection; import java.util.Iterator; import java.util.function.Function; +import se.su.dsv.scipro.notifications.dataobject.NotificationEvent; +import se.su.dsv.scipro.system.User; abstract class AbstractEventFormatter implements EventFormatter { @@ -17,12 +16,17 @@ abstract class AbstractEventFormatter implements Ev } protected String formatUser(User user) { - return MessageFormat.format(getProperty("user"), user.getFirstName(), user.getLastName(), user.getEmailAddress()); + return MessageFormat.format( + getProperty("user"), + user.getFirstName(), + user.getLastName(), + user.getEmailAddress() + ); } protected String formatUserList(Collection objects, Function converter) { StringBuilder sb = new StringBuilder(); - for (Iterator iterator = objects.iterator(); iterator.hasNext(); ) { + for (Iterator iterator = objects.iterator(); iterator.hasNext();) { User user = converter.apply(iterator.next()); sb.append(formatUser(user)); if (iterator.hasNext()) { diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/GroupEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/GroupEventFormatter.java index b782ae8db0..a0f19c795d 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/GroupEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/GroupEventFormatter.java @@ -1,25 +1,23 @@ -package se.su.dsv.scipro.notifications.interfaces.impl; - -import se.su.dsv.scipro.notifications.dataobject.GroupEvent; -import se.su.dsv.scipro.project.Project; - -import java.text.MessageFormat; -import java.util.Set; -import java.util.stream.Collectors; - -public class GroupEventFormatter extends AbstractEventFormatter { - - GroupEventFormatter(NotificationMailFormatterImpl formatter) { - super(formatter); - } - - @Override - public String format(GroupEvent event) { - String title = event.getGroup().getTitle(); - Set projects = event.getGroup().getProjects(); - String projectTitles = projects.stream().map(Project::getTitle) - .collect(Collectors.joining(", ")); - String format = getProperty(event.getType().name()); - return MessageFormat.format(format, title, projectTitles); - } -} +package se.su.dsv.scipro.notifications.interfaces.impl; + +import java.text.MessageFormat; +import java.util.Set; +import java.util.stream.Collectors; +import se.su.dsv.scipro.notifications.dataobject.GroupEvent; +import se.su.dsv.scipro.project.Project; + +public class GroupEventFormatter extends AbstractEventFormatter { + + GroupEventFormatter(NotificationMailFormatterImpl formatter) { + super(formatter); + } + + @Override + public String format(GroupEvent event) { + String title = event.getGroup().getTitle(); + Set projects = event.getGroup().getProjects(); + String projectTitles = projects.stream().map(Project::getTitle).collect(Collectors.joining(", ")); + String format = getProperty(event.getType().name()); + return MessageFormat.format(format, title, projectTitles); + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/IdeaEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/IdeaEventFormatter.java index 930ee3b9c5..3f2b03b1ed 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/IdeaEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/IdeaEventFormatter.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import java.text.MessageFormat; import se.su.dsv.scipro.match.Idea; import se.su.dsv.scipro.match.IdeaParticipation; import se.su.dsv.scipro.notifications.dataobject.IdeaEvent; import se.su.dsv.scipro.system.User; -import java.text.MessageFormat; - public class IdeaEventFormatter extends AbstractEventFormatter { IdeaEventFormatter(NotificationMailFormatterImpl formatter) { @@ -26,11 +25,6 @@ public class IdeaEventFormatter extends AbstractEventFormatter { String supervisor = supervisorEmployee != null ? formatUser(supervisorEmployee) : ""; String format = getProperty(event.getType().name()); - return MessageFormat.format(format, - title, - level, - authors, - status, - supervisor); + return MessageFormat.format(format, title, level, authors, status, supervisor); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/MileStoneEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/MileStoneEventFormatter.java index 186b72bb20..1e820a2c17 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/MileStoneEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/MileStoneEventFormatter.java @@ -1,15 +1,15 @@ -package se.su.dsv.scipro.notifications.interfaces.impl; - -import se.su.dsv.scipro.notifications.dataobject.MileStoneEvent; - -public class MileStoneEventFormatter extends AbstractEventFormatter { - - MileStoneEventFormatter(NotificationMailFormatterImpl formatter) { - super(formatter); - } - - @Override - public String format(MileStoneEvent event) { - return ""; - } -} +package se.su.dsv.scipro.notifications.interfaces.impl; + +import se.su.dsv.scipro.notifications.dataobject.MileStoneEvent; + +public class MileStoneEventFormatter extends AbstractEventFormatter { + + MileStoneEventFormatter(NotificationMailFormatterImpl formatter) { + super(formatter); + } + + @Override + public String format(MileStoneEvent event) { + return ""; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImpl.java index b8aeadcb99..78d2591ea4 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImpl.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.*; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.data.enums.DateStyle; @@ -13,13 +19,6 @@ import se.su.dsv.scipro.notifications.interfaces.NotificationMailFormatter; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.util.PropsUtils; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.*; -import java.util.stream.Collectors; - public class NotificationMailFormatterImpl implements NotificationMailFormatter { private static final int TITLE_TRUNCATION_LENGTH = 25; @@ -27,6 +26,7 @@ public class NotificationMailFormatterImpl implements NotificationMailFormatter @Inject GeneralSystemSettingsService systemSettingsService; + @Inject DateService dateService; @@ -58,7 +58,7 @@ public class NotificationMailFormatterImpl implements NotificationMailFormatter } private Map, EventFormatter> formatters = - new HashMap<>(); + new HashMap<>(); private Properties properties; @@ -103,17 +103,29 @@ public class NotificationMailFormatterImpl implements NotificationMailFormatter } String subjectProperty = makeProperty(notification.getType().name(), notification.getEvent().name(), "title"); - String subject = MessageFormat.format(getProperty(subjectProperty), title, notification.getSource(), notification.getAdditionalSource()); + String subject = MessageFormat.format( + getProperty(subjectProperty), + title, + notification.getSource(), + notification.getAdditionalSource() + ); String bodyProperty = makeProperty(notification.getType().name(), notification.getEvent().name(), "body"); - String body = MessageFormat.format(getProperty(bodyProperty), notification.getSource(), getAbsoluteURL(notification), notification.getAdditionalSource()); + String body = MessageFormat.format( + getProperty(bodyProperty), + notification.getSource(), + getAbsoluteURL(notification), + notification.getAdditionalSource() + ); String details = ""; if (notification.getNotificationEvent().hasEntity()) { try { Class eventClass = notification.getNotificationEvent().getClass(); @SuppressWarnings("unchecked") - EventFormatter formatter = (EventFormatter) formatters.get(eventClass); + EventFormatter formatter = (EventFormatter) formatters.get( + eventClass + ); details = formatter.format(notification.getNotificationEvent()); } catch (Exception ex) { @@ -142,11 +154,23 @@ public class NotificationMailFormatterImpl implements NotificationMailFormatter for (Notification notification : notifications) { String titleProperty = makeProperty(notification.getType(), notification.getEvent(), "title"); String suffixProperty = makeProperty(notification.getType(), "compilationSuffix"); - String causedByName = notification.getCausedBy() != null ? "by " + notification.getCausedBy().getFullName() : ""; - contents.append(format.format(new Object[]{ - MessageFormat.format(getProperty(titleProperty), notification.getTitle(), notification.getSource(), notification.getAdditionalSource()), - causedByName, MessageFormat.format(getProperty(suffixProperty), notification.getTitle()) - })); + String causedByName = notification.getCausedBy() != null + ? "by " + notification.getCausedBy().getFullName() + : ""; + contents.append( + format.format( + new Object[] { + MessageFormat.format( + getProperty(titleProperty), + notification.getTitle(), + notification.getSource(), + notification.getAdditionalSource() + ), + causedByName, + MessageFormat.format(getProperty(suffixProperty), notification.getTitle()), + } + ) + ); } contents.append(getProperty("compilation.list.end")); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerEventFormatter.java index 035583a246..5c9302fab6 100755 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerEventFormatter.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import java.text.MessageFormat; import se.su.dsv.scipro.notifications.dataobject.PeerEvent; import se.su.dsv.scipro.peer.PeerRequest; import se.su.dsv.scipro.peer.PeerReview; import se.su.dsv.scipro.project.Project; -import java.text.MessageFormat; - public class PeerEventFormatter extends AbstractEventFormatter { PeerEventFormatter(NotificationMailFormatterImpl formatter) { @@ -27,12 +26,6 @@ public class PeerEventFormatter extends AbstractEventFormatter { String supervisor = formatUser(project.getHeadSupervisor()); String format = getProperty(event.getType().name()); - return MessageFormat.format(format, - date, - requester, - reviewer, - title, - level, - supervisor); + return MessageFormat.format(format, date, requester, reviewer, title, level, supervisor); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerRequestFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerRequestFormatter.java index 68e7d58c2a..df55825378 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerRequestFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/PeerRequestFormatter.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import java.text.MessageFormat; import se.su.dsv.scipro.notifications.dataobject.PeerRequestEvent; import se.su.dsv.scipro.peer.PeerRequest; -import java.text.MessageFormat; - public class PeerRequestFormatter extends AbstractEventFormatter { PeerRequestFormatter(NotificationMailFormatterImpl formatter) { @@ -23,11 +22,6 @@ public class PeerRequestFormatter extends AbstractEventFormatter { @@ -28,12 +27,6 @@ class ProjectEventFormatter extends AbstractEventFormatter { String reviewers = formatUserList(project.getReviewers(), Function.identity()); String format = getProperty(event.getType().name()); - return MessageFormat.format(format, - title, - level, - authors, - supervisor, - coSupervisors, - reviewers); + return MessageFormat.format(format, title, level, authors, supervisor, coSupervisors, reviewers); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/ProjectForumEventFormatter.java b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/ProjectForumEventFormatter.java index 82a48878fd..f941040a7b 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/ProjectForumEventFormatter.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/interfaces/impl/ProjectForumEventFormatter.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import java.text.MessageFormat; import se.su.dsv.scipro.notifications.dataobject.ProjectForumEvent; import se.su.dsv.scipro.project.Project; -import java.text.MessageFormat; - public class ProjectForumEventFormatter extends AbstractEventFormatter { public ProjectForumEventFormatter(NotificationMailFormatterImpl formatter) { @@ -21,7 +20,6 @@ public class ProjectForumEventFormatter extends AbstractEventFormatter { SeminarEventFormatter(NotificationMailFormatterImpl formatter) { @@ -32,18 +31,20 @@ public class SeminarEventFormatter extends AbstractEventFormatter String oppositions = formatUserList(seminar.getOppositions(), FinalSeminarParticipation::getUser); String format = getProperty(event.getType().name()); - return MessageFormat.format(format, - date, - room, - title, - level, - authors, - supervisor, - coSupervisors, - reviewers, - participants, - oppositions, - formatter.getFinalSeminarDeadline(seminar), - formatter.getFinalSeminarUploadedOnString(seminar)); + return MessageFormat.format( + format, + date, + room, + title, + level, + authors, + supervisor, + coSupervisors, + reviewers, + participants, + oppositions, + formatter.getFinalSeminarDeadline(seminar), + formatter.getFinalSeminarUploadedOnString(seminar) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/Configuration.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/Configuration.java index 0f7dfa9f07..c064bcb5f9 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/Configuration.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/Configuration.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.notifications.settings.entities; +import jakarta.persistence.*; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.system.DomainObject; -import jakarta.persistence.*; - @MappedSuperclass public class Configuration extends DomainObject { @@ -19,9 +18,7 @@ public class Configuration extends DomainObject { @Column(name = "event", nullable = false) private String event; - protected Configuration() { - - } + protected Configuration() {} public Configuration(final Notification.Type type, final String event) { this.type = type; diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryConfiguration.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryConfiguration.java index 7e20fa7ffb..6831759f79 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryConfiguration.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryConfiguration.java @@ -8,15 +8,16 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.system.User; @Entity -@Table(name = "notification_delivery_configuration", - uniqueConstraints = { - @UniqueConstraint(name = "uk_one_setting_per_user", columnNames = {"type", "event", "method", "user_id"}) - }) +@Table( + name = "notification_delivery_configuration", + uniqueConstraints = { + @UniqueConstraint(name = "uk_one_setting_per_user", columnNames = { "type", "event", "method", "user_id" }), + } +) public class DeliveryConfiguration extends Configuration { @Column(name = "method", nullable = false) @@ -30,8 +31,7 @@ public class DeliveryConfiguration extends Configuration { @JoinColumn(nullable = true, name = "user_id") private User user; - public DeliveryConfiguration() { - } + public DeliveryConfiguration() {} public DeliveryConfiguration(Notification.Type type, String event, DeliveryMethod method, User user) { super(type, event); @@ -62,5 +62,4 @@ public class DeliveryConfiguration extends Configuration { public void setUser(User user) { this.user = user; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryMethod.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryMethod.java index 17aa7155f8..48e832b941 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryMethod.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/DeliveryMethod.java @@ -2,5 +2,5 @@ package se.su.dsv.scipro.notifications.settings.entities; public enum DeliveryMethod { WEB, - MAIL + MAIL, } diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/ReceiverConfiguration.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/ReceiverConfiguration.java index 645b2a3e94..1c0227972d 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/ReceiverConfiguration.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/entities/ReceiverConfiguration.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.notifications.settings.entities; +import jakarta.persistence.*; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.dataobject.Notification; -import jakarta.persistence.*; - @Entity -@Table(name = "notification_receiver_configuration", - uniqueConstraints = { - @UniqueConstraint(name = "one_setting_per_role", columnNames = {"type", "event", "member"}) - } +@Table( + name = "notification_receiver_configuration", + uniqueConstraints = { + @UniqueConstraint(name = "one_setting_per_role", columnNames = { "type", "event", "member" }), + } ) public class ReceiverConfiguration extends Configuration { @@ -20,9 +20,7 @@ public class ReceiverConfiguration extends Configuration { @Column(name = "enabled", nullable = false) private boolean enabled = false; - public ReceiverConfiguration() { - - } + public ReceiverConfiguration() {} public ReceiverConfiguration(Notification.Type group, Enum event, Member.Type member) { super(group, event.name()); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationService.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationService.java index f00561414c..061b4a2bc0 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationService.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationService.java @@ -1,13 +1,18 @@ package se.su.dsv.scipro.notifications.settings.service; +import java.util.Optional; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.settings.entities.DeliveryMethod; import se.su.dsv.scipro.system.User; -import java.util.Optional; - public interface DeliveryConfigurationService { - boolean setDelivery(Notification.Type type, Enum event, DeliveryMethod method, boolean enabled, Optional user); + boolean setDelivery( + Notification.Type type, + Enum event, + DeliveryMethod method, + boolean enabled, + Optional user + ); boolean isDelivery(Notification.Type type, Enum event, DeliveryMethod method, Optional user); diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImpl.java index 75f7624ac6..63c8a2e277 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImpl.java @@ -1,6 +1,12 @@ package se.su.dsv.scipro.notifications.settings.service; +import static com.querydsl.core.types.dsl.Expressions.allOf; + +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; +import java.util.Optional; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.Notification.Type; import se.su.dsv.scipro.notifications.settings.entities.DeliveryConfiguration; @@ -10,14 +16,9 @@ import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.AbstractServiceImpl; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.Optional; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - -public class DeliveryConfigurationServiceImpl extends AbstractServiceImpl implements DeliveryConfigurationService { +public class DeliveryConfigurationServiceImpl + extends AbstractServiceImpl + implements DeliveryConfigurationService { private final UserProfileService profileService; @@ -29,18 +30,31 @@ public class DeliveryConfigurationServiceImpl extends AbstractServiceImpl user) { - DeliveryConfiguration configuration = user.map(user_ -> + public boolean setDelivery( + final Notification.Type type, + final Enum event, + final DeliveryMethod method, + final boolean enabled, + final Optional user + ) { + DeliveryConfiguration configuration = user + .map(user_ -> getUserConfiguration(type, event, method, user_).orElseGet(() -> - createBasedOnSystemConfiguration(type, event, method, user_) + createBasedOnSystemConfiguration(type, event, method, user_) ) - ).orElseGet(() -> getSystemConfiguration(type, event, method)); + ) + .orElseGet(() -> getSystemConfiguration(type, event, method)); configuration.setEnabled(enabled); configuration = save(configuration); return configuration.isEnabled(); } - private DeliveryConfiguration createBasedOnSystemConfiguration(final Notification.Type type, final Enum event, final DeliveryMethod method, final User user) { + private DeliveryConfiguration createBasedOnSystemConfiguration( + final Notification.Type type, + final Enum event, + final DeliveryMethod method, + final User user + ) { final DeliveryConfiguration systemConfiguration = getSystemConfiguration(type, event, method); final DeliveryConfiguration userConfiguration = new DeliveryConfiguration(type, event.name(), method, user); userConfiguration.setEnabled(systemConfiguration.isEnabled()); @@ -48,11 +62,16 @@ public class DeliveryConfigurationServiceImpl extends AbstractServiceImpl user) { + public boolean isDelivery( + final Notification.Type type, + final Enum event, + final DeliveryMethod method, + final Optional user + ) { return user - .flatMap(v1 -> getUserConfiguration(type, event, method, v1)) - .orElseGet(() -> getSystemConfiguration(type, event, method)) - .isEnabled(); + .flatMap(v1 -> getUserConfiguration(type, event, method, v1)) + .orElseGet(() -> getSystemConfiguration(type, event, method)) + .isEnabled(); } @Override @@ -60,15 +79,27 @@ public class DeliveryConfigurationServiceImpl extends AbstractServiceImpl getUserConfiguration(final Type type, final Enum event, final DeliveryMethod method, final User user) { + private Optional getUserConfiguration( + final Type type, + final Enum event, + final DeliveryMethod method, + final User user + ) { QDeliveryConfiguration q = QDeliveryConfiguration.deliveryConfiguration; - return Optional.ofNullable(findOne(allOf(q.type.eq(type), q.event.eq(event.name()), q.method.eq(method), q.user.eq(user)))); + return Optional.ofNullable( + findOne(allOf(q.type.eq(type), q.event.eq(event.name()), q.method.eq(method), q.user.eq(user))) + ); } - private DeliveryConfiguration getSystemConfiguration(final Notification.Type type, final Enum event, final DeliveryMethod method) { + private DeliveryConfiguration getSystemConfiguration( + final Notification.Type type, + final Enum event, + final DeliveryMethod method + ) { QDeliveryConfiguration q = QDeliveryConfiguration.deliveryConfiguration; - DeliveryConfiguration configuration = - findOne(allOf(q.type.eq(type), q.event.eq(event.name()), q.method.eq(method), q.user.isNull())); + DeliveryConfiguration configuration = findOne( + allOf(q.type.eq(type), q.event.eq(event.name()), q.method.eq(method), q.user.isNull()) + ); if (configuration == null) { configuration = new DeliveryConfiguration(type, event.name(), method, null); // Still null, create new setting diff --git a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImpl.java index 596c2e3821..24b86eff29 100644 --- a/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImpl.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.notifications.settings.service; +import static com.querydsl.core.types.dsl.Expressions.allOf; + +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.dataobject.Notification; @@ -7,13 +12,9 @@ import se.su.dsv.scipro.notifications.settings.entities.QReceiverConfiguration; import se.su.dsv.scipro.notifications.settings.entities.ReceiverConfiguration; import se.su.dsv.scipro.system.AbstractServiceImpl; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - -public class ReceiverConfigurationServiceImpl extends AbstractServiceImpl implements ReceiverConfigurationService { +public class ReceiverConfigurationServiceImpl + extends AbstractServiceImpl + implements ReceiverConfigurationService { @Inject public ReceiverConfigurationServiceImpl(Provider em) { @@ -37,7 +38,9 @@ public class ReceiverConfigurationServiceImpl extends AbstractServiceImpl scopes) { final StringBuilder authorizationUri = new StringBuilder() - .append(settings.uri()) - .append("/authorize") - .append("?response_type=").append("code") - .append("&client_id=").append(settings.clientId()) - .append("&redirect_uri=").append(settings.redirectUri()) - .append("&scope=").append(String.join(" ", scopes)); + .append(settings.uri()) + .append("/authorize") + .append("?response_type=") + .append("code") + .append("&client_id=") + .append(settings.clientId()) + .append("&redirect_uri=") + .append(settings.redirectUri()) + .append("&scope=") + .append(String.join(" ", scopes)); if (state != null) { authorizationUri.append("&state=").append(state); } @@ -47,31 +49,31 @@ public class OAuthServiceImpl implements OAuthService { form.param("code", code); form.param("redirect_uri", settings.redirectUri()); - final Response response = client.target(settings.uri()) - .register(HttpAuthenticationFeature.basic(settings.clientId(), settings.clientSecret())) - .path("exchange") - .request(MediaType.APPLICATION_JSON_TYPE) - .post(Entity.form(form)); + final Response response = client + .target(settings.uri()) + .register(HttpAuthenticationFeature.basic(settings.clientId(), settings.clientSecret())) + .path("exchange") + .request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.form(form)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(TokenResponse.class); - } - else { + } else { return null; } } @Override public Optional verifyToken(final String token) { - final Response response = client.target(settings.uri()) - .path("verify") - .request(MediaType.APPLICATION_JSON_TYPE) - .post(Entity.text(token)); + final Response response = client + .target(settings.uri()) + .path("verify") + .request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.text(token)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return Optional.of(response.readEntity(Payload.class)); - } - else { + } else { return Optional.empty(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/oauth/OAuthSettings.java b/core/src/main/java/se/su/dsv/scipro/oauth/OAuthSettings.java index 2a20bcf204..8a5ed5916b 100644 --- a/core/src/main/java/se/su/dsv/scipro/oauth/OAuthSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/oauth/OAuthSettings.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.oauth; -public record OAuthSettings(String uri, String redirectUri, String clientId, String clientSecret) { -} +public record OAuthSettings(String uri, String redirectUri, String clientId, String clientSecret) {} diff --git a/core/src/main/java/se/su/dsv/scipro/oauth/Payload.java b/core/src/main/java/se/su/dsv/scipro/oauth/Payload.java index 6695a3324a..f329497d58 100644 --- a/core/src/main/java/se/su/dsv/scipro/oauth/Payload.java +++ b/core/src/main/java/se/su/dsv/scipro/oauth/Payload.java @@ -1,11 +1,9 @@ package se.su.dsv.scipro.oauth; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.*; public record Payload( - @JsonProperty("principal") String principal, - @JsonProperty("entitlements") Set entitlements) -{ -} + @JsonProperty("principal") String principal, + @JsonProperty("entitlements") Set entitlements +) {} diff --git a/core/src/main/java/se/su/dsv/scipro/oauth/TokenResponse.java b/core/src/main/java/se/su/dsv/scipro/oauth/TokenResponse.java index 1fa9680bca..4da7df50f5 100644 --- a/core/src/main/java/se/su/dsv/scipro/oauth/TokenResponse.java +++ b/core/src/main/java/se/su/dsv/scipro/oauth/TokenResponse.java @@ -3,8 +3,7 @@ package se.su.dsv.scipro.oauth; import com.fasterxml.jackson.annotation.JsonProperty; public record TokenResponse( - @JsonProperty("access_token") String accessToken, - @JsonProperty("token_type") String tokenType, - @JsonProperty("expires_in") int expiresIn) -{ -} + @JsonProperty("access_token") String accessToken, + @JsonProperty("token_type") String tokenType, + @JsonProperty("expires_in") int expiresIn +) {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/Answer.java b/core/src/main/java/se/su/dsv/scipro/peer/Answer.java index bf40f7d72e..6937e9aac5 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/Answer.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/Answer.java @@ -13,120 +13,128 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import java.util.Objects; import se.su.dsv.scipro.checklist.ChecklistAnswerEnum; import se.su.dsv.scipro.system.DomainObject; -import java.util.Objects; - @Entity -@Table(name="answer") +@Table(name = "answer") @Cacheable(true) public class Answer extends DomainObject { - // ---------------------------------------------------------------------------------- - // basic JPA-mappings - // ---------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------- + // basic JPA-mappings + // ---------------------------------------------------------------------------------- @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Basic(optional = false) - @Column(name = "question") - private String question; + @Basic(optional = false) + @Column(name = "question") + private String question; - @Enumerated(EnumType.STRING) - @Column(name = "answer", nullable=false) - private ChecklistAnswerEnum answer = ChecklistAnswerEnum.NO_ANSWER; + @Enumerated(EnumType.STRING) + @Column(name = "answer", nullable = false) + private ChecklistAnswerEnum answer = ChecklistAnswerEnum.NO_ANSWER; - @Basic(optional=true) - @Lob - @Column(name = "motivation") - private String motivation; + @Basic(optional = true) + @Lob + @Column(name = "motivation") + private String motivation; - // ---------------------------------------------------------------------------------- - // JPA-mappings of foreign keys in this table (answer) referencing other tables. - // ---------------------------------------------------------------------------------- - @ManyToOne(optional=false) - @JoinColumn(name = "peer_review_id", referencedColumnName = "id") - private PeerReview peerReview; + // ---------------------------------------------------------------------------------- + // JPA-mappings of foreign keys in this table (answer) referencing other tables. + // ---------------------------------------------------------------------------------- + @ManyToOne(optional = false) + @JoinColumn(name = "peer_review_id", referencedColumnName = "id") + private PeerReview peerReview; - // ---------------------------------------------------------------------------------- - // constructors - // ---------------------------------------------------------------------------------- - public Answer() {} + // ---------------------------------------------------------------------------------- + // constructors + // ---------------------------------------------------------------------------------- + public Answer() {} - public Answer(PeerReview peerReview, String question){ - this.peerReview = peerReview; - this.question = question; - } + public Answer(PeerReview peerReview, String question) { + this.peerReview = peerReview; + this.question = question; + } - // ---------------------------------------------------------------------------------- - // getters and setters - // ---------------------------------------------------------------------------------- - @Override - public Long getId() { - return this.id; - } + // ---------------------------------------------------------------------------------- + // getters and setters + // ---------------------------------------------------------------------------------- + @Override + public Long getId() { + return this.id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getQuestion() { - return this.question; - } + public String getQuestion() { + return this.question; + } - public void setQuestion(String question) { - this.question = question; - } + public void setQuestion(String question) { + this.question = question; + } - public ChecklistAnswerEnum getAnswer() { - return this.answer; - } + public ChecklistAnswerEnum getAnswer() { + return this.answer; + } - public void setAnswer(ChecklistAnswerEnum answer) { - this.answer = answer; - } + public void setAnswer(ChecklistAnswerEnum answer) { + this.answer = answer; + } - public String getMotivation() { - return this.motivation; - } + public String getMotivation() { + return this.motivation; + } - public void setMotivation(String motivation) { - this.motivation = motivation; - } + public void setMotivation(String motivation) { + this.motivation = motivation; + } - public PeerReview getPeerReview() { - return this.peerReview; - } + public PeerReview getPeerReview() { + return this.peerReview; + } - public void setPeerReview(PeerReview peerReview) { - this.peerReview = peerReview; - } + public void setPeerReview(PeerReview peerReview) { + this.peerReview = peerReview; + } - // ---------------------------------------------------------------------------------- - // other methods - // ---------------------------------------------------------------------------------- - protected boolean canEqual(final Object other) { - return other instanceof Answer; - } + // ---------------------------------------------------------------------------------- + // other methods + // ---------------------------------------------------------------------------------- + protected boolean canEqual(final Object other) { + return other instanceof Answer; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof Answer)) return false; - final Answer other = (Answer) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); - } + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof Answer)) return false; + final Answer other = (Answer) o; + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); + } - @Override - public int hashCode() { - return Objects.hashCode(this.getId()); - } + @Override + public int hashCode() { + return Objects.hashCode(this.getId()); + } - @Override - public String toString() { - return "Answer(id=" + this.getId() + ", question=" + this.getQuestion() + ", motivation=" + - this.getMotivation() + ", answer=" + this.getAnswer() + ")"; - } + @Override + public String toString() { + return ( + "Answer(id=" + + this.getId() + + ", question=" + + this.getQuestion() + + ", motivation=" + + this.getMotivation() + + ", answer=" + + this.getAnswer() + + ")" + ); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/Comment.java b/core/src/main/java/se/su/dsv/scipro/peer/Comment.java index bb5c68db96..637fae5ab1 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/Comment.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/Comment.java @@ -11,16 +11,16 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Comparator; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "comment") @Cacheable(true) public class Comment extends DomainObject { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -38,8 +38,7 @@ public class Comment extends DomainObject { @JoinColumn(name = "comment_thread_id", referencedColumnName = "id") private CommentThread commentThread; - protected Comment() { - } + protected Comment() {} public Comment(final User creator, final CommentThread commentThread) { this.creator = creator; @@ -77,10 +76,13 @@ public class Comment extends DomainObject { @Override public String toString() { - return "Comment(id=" + this.getId() + ", creator=" + this.getCreator() + ", comment=" + this.getComment() + ")"; + return ( + "Comment(id=" + this.getId() + ", creator=" + this.getCreator() + ", comment=" + this.getComment() + ")" + ); } public static class ByDateCreatedComparator implements Comparator, Serializable { + @Override public int compare(Comment o1, Comment o2) { return o1.getDateCreated().compareTo(o2.getDateCreated()); diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentService.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentService.java index a71d04ef1d..f62000c85d 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentService.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentService.java @@ -1,10 +1,8 @@ package se.su.dsv.scipro.peer; +import java.util.List; import se.su.dsv.scipro.system.GenericService; -import java.util.List; - public interface CommentService extends GenericService { - List findByCommentThread(CommentThread commentThread); } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentServiceImpl.java index 63723ecf16..fc07b334d6 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentServiceImpl.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.system.AbstractServiceImpl; public class CommentServiceImpl extends AbstractServiceImpl implements CommentService { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentThread.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentThread.java index 803fb375af..7e44829aae 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentThread.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentThread.java @@ -1,16 +1,18 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.*; import java.util.Objects; import java.util.Set; import java.util.TreeSet; +import se.su.dsv.scipro.system.DomainObject; @Entity -@Table(name = "comment_thread", - uniqueConstraints = {@UniqueConstraint(name = "uk_comment_thread_id_key", - columnNames = {"commentable_key", "commentable_id"})}) +@Table( + name = "comment_thread", + uniqueConstraints = { + @UniqueConstraint(name = "uk_comment_thread_id_key", columnNames = { "commentable_key", "commentable_id" }), + } +) @Cacheable(true) public class CommentThread extends DomainObject { @@ -24,14 +26,18 @@ public class CommentThread extends DomainObject { @Column(name = "commentable_id", nullable = false) private Long commentableId; - @OneToMany(mappedBy = "commentThread", orphanRemoval = true, cascade = CascadeType.ALL, targetEntity = Comment.class) + @OneToMany( + mappedBy = "commentThread", + orphanRemoval = true, + cascade = CascadeType.ALL, + targetEntity = Comment.class + ) private Set comments = new TreeSet<>(new Comment.ByDateCreatedComparator()); - protected CommentThread() { - } + protected CommentThread() {} public CommentThread(Commentable commentable) { - this.commentableKey = commentable.getCommentKey(); + this.commentableKey = commentable.getCommentKey(); this.commentableId = commentable.getId(); } @@ -66,7 +72,17 @@ public class CommentThread extends DomainObject { @Override public String toString() { - return "CommentThread(id=" + this.getId() + ", commentableKey=" + this.getCommentableKey() + ", commentableId=" + this.getCommentableId() + ", comments=" + this.getComments() + ")"; + return ( + "CommentThread(id=" + + this.getId() + + ", commentableKey=" + + this.getCommentableKey() + + ", commentableId=" + + this.getCommentableId() + + ", comments=" + + this.getComments() + + ")" + ); } @Override @@ -74,8 +90,7 @@ public class CommentThread extends DomainObject { if (o == this) return true; if (!(o instanceof CommentThread)) return false; final CommentThread other = (CommentThread) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepo.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepo.java index 8210abd3c5..ebf5cb9a22 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepo.java @@ -4,8 +4,8 @@ import jakarta.transaction.Transactional; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; - @Transactional -public interface CommentThreadRepo extends JpaRepository, QueryDslPredicateExecutor { +public interface CommentThreadRepo + extends JpaRepository, QueryDslPredicateExecutor { CommentThread getCommentThread(String commentableKey, long commentableId); } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepoImpl.java index 6bda7bdc3a..9f59b20459 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadRepoImpl.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.GenericRepo; +import static com.querydsl.core.types.dsl.Expressions.allOf; import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; - -import static com.querydsl.core.types.dsl.Expressions.allOf; +import se.su.dsv.scipro.system.GenericRepo; public class CommentThreadRepoImpl extends GenericRepo implements CommentThreadRepo { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadServiceImpl.java index 604e36b9a5..84384be94c 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/CommentThreadServiceImpl.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.peer; -import jakarta.transaction.Transactional; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; public class CommentThreadServiceImpl implements CommentThreadService { @@ -21,7 +20,10 @@ public class CommentThreadServiceImpl implements CommentThreadService { @Override @Transactional public CommentThread getCommentThread(Commentable commentable) { - final CommentThread commentThread = commentThreadRepo.getCommentThread(commentable.getCommentKey(), commentable.getId()); + final CommentThread commentThread = commentThreadRepo.getCommentThread( + commentable.getCommentKey(), + commentable.getId() + ); if (commentThread != null) { return commentThread; } else { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/Commentable.java b/core/src/main/java/se/su/dsv/scipro/peer/Commentable.java index 0b4d6ed29b..897b6888ec 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/Commentable.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/Commentable.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.peer; public interface Commentable { - /** - * Method should return a uniquely identifying string representing it's class and all it's subclasses - * Suggested implementation is X.class.getCanonicalName().toString() where X is NOT this.getClass() - * (because this will return the subclasses class) it should be the actual, literal superclass. - */ - String getCommentKey(); - /** - * Normal Id from DomainObjects - */ - Long getId(); + /** + * Method should return a uniquely identifying string representing it's class and all it's subclasses + * Suggested implementation is X.class.getCanonicalName().toString() where X is NOT this.getClass() + * (because this will return the subclasses class) it should be the actual, literal superclass. + */ + String getCommentKey(); + /** + * Normal Id from DomainObjects + */ + Long getId(); } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/ExpiredRequestWorker.java b/core/src/main/java/se/su/dsv/scipro/peer/ExpiredRequestWorker.java index bb15047813..1eb0f8193e 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/ExpiredRequestWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/ExpiredRequestWorker.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.peer; import com.google.common.eventbus.EventBus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.ProjectTypeSettings; -import se.su.dsv.scipro.workerthreads.AbstractWorker; - import jakarta.inject.Inject; import java.time.Duration; import java.time.Instant; import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import se.su.dsv.scipro.system.ProjectTypeSettings; +import se.su.dsv.scipro.workerthreads.AbstractWorker; public class ExpiredRequestWorker extends AbstractWorker { @@ -17,6 +16,7 @@ public class ExpiredRequestWorker extends AbstractWorker { @Inject PeerRequestService peerRequestService; + @Inject EventBus eventBus; @@ -28,21 +28,25 @@ public class ExpiredRequestWorker extends AbstractWorker { final Instant now = Instant.now(); for (PeerRequest request : requests) { - ProjectTypeSettings settings = request.getProject().getProjectType().getProjectTypeSettings(); - Date expirationDate = Date.from(now.minus(Duration.ofDays(settings.getNumDaysBeforePeerGetsCancelled()))); + Date expirationDate = Date.from( + now.minus(Duration.ofDays(settings.getNumDaysBeforePeerGetsCancelled())) + ); if (request.getDateCreated().compareTo(expirationDate) < 0) { - LOGGER.info("Peer Request: " + request + " has now been waiting for " + settings.getNumDaysBeforePeerGetsCancelled() + " days and has been removed."); - - + LOGGER.info( + "Peer Request: " + + request + + " has now been waiting for " + + settings.getNumDaysBeforePeerGetsCancelled() + + " days and has been removed." + ); request.setStatus(RequestStatus.CANCELED); peerRequestService.save(request); eventBus.post(new PeerRequestExpiredEvent(request)); } - } commitTransaction(); } catch (Exception e) { @@ -51,5 +55,4 @@ public class ExpiredRequestWorker extends AbstractWorker { throw new RuntimeException(e); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/ExpiredReviewResetWorker.java b/core/src/main/java/se/su/dsv/scipro/peer/ExpiredReviewResetWorker.java index f7c0a6725e..013daf7462 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/ExpiredReviewResetWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/ExpiredReviewResetWorker.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.peer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.workerthreads.AbstractWorker; - import jakarta.inject.Inject; import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import se.su.dsv.scipro.workerthreads.AbstractWorker; public class ExpiredReviewResetWorker extends AbstractWorker { @@ -13,6 +12,7 @@ public class ExpiredReviewResetWorker extends AbstractWorker { @Inject private PeerRequestService peerRequestService; + @Inject private PeerReviewService peerReviewService; @@ -26,7 +26,13 @@ public class ExpiredReviewResetWorker extends AbstractWorker { PeerRequest peerRequest = peerReview.getPeerRequest(); if (peerReview.isLate()) { - LOGGER.info("Expiring peerReview: " + peerReview + " and making " + peerRequest + " available for review again"); + LOGGER.info( + "Expiring peerReview: " + + peerReview + + " and making " + + peerRequest + + " available for review again" + ); peerReview.expire(); peerReviewService.save(peerReview); @@ -34,7 +40,6 @@ public class ExpiredReviewResetWorker extends AbstractWorker { peerRequest.setStatus(RequestStatus.WAITING); peerRequestService.save(peerRequest); } - } commitTransaction(); } catch (Exception e) { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/FirstPeerReviewCompletedEvent.java b/core/src/main/java/se/su/dsv/scipro/peer/FirstPeerReviewCompletedEvent.java index 003ce276e0..31ffb15212 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/FirstPeerReviewCompletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/FirstPeerReviewCompletedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.peer; public class FirstPeerReviewCompletedEvent extends PeerReviewEvent { + public FirstPeerReviewCompletedEvent(PeerReview peerReview) { super(peerReview); } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/MissingAnswerException.java b/core/src/main/java/se/su/dsv/scipro/peer/MissingAnswerException.java index d4124ad19a..b2c87fef35 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/MissingAnswerException.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/MissingAnswerException.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.peer; -public class MissingAnswerException extends RuntimeException { -} +public class MissingAnswerException extends RuntimeException {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PartOfProjectException.java b/core/src/main/java/se/su/dsv/scipro/peer/PartOfProjectException.java index 564ebc3d6c..68eaa4e3d1 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PartOfProjectException.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PartOfProjectException.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.peer; - -public class PartOfProjectException extends RuntimeException { -} +package se.su.dsv.scipro.peer; + +public class PartOfProjectException extends RuntimeException {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerPortal.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerPortal.java index c6ae39bc21..a67a33515d 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerPortal.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerPortal.java @@ -5,7 +5,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; public interface PeerPortal { - PeerReview acceptReview(PeerRequest request, User student, Project project); PeerRequest storePeerRequest(FileUpload upload, PeerRequest request); diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerPortalImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerPortalImpl.java index aa6b178072..17b8612a80 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerPortalImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerPortalImpl.java @@ -1,7 +1,15 @@ package se.su.dsv.scipro.peer; +import static com.querydsl.core.types.dsl.Expressions.allOf; + import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.*; +import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.file.FileReference; @@ -14,15 +22,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.*; -import java.util.function.Consumer; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - public class PeerPortalImpl implements PeerPortal, PerformReviewService { private static final Logger LOGGER = LoggerFactory.getLogger(PeerPortalImpl.class); @@ -36,14 +35,15 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { private final Clock clock; @Inject - public PeerPortalImpl(FileService fileDescriptionService, - PeerReviewRepository peerReviewRepository, - PeerRequestRepository peerRequestRepository, - EventBus eventBus, - final ProjectFileService projectFileService, - final DaysService daysService, - Clock clock) - { + public PeerPortalImpl( + FileService fileDescriptionService, + PeerReviewRepository peerReviewRepository, + PeerRequestRepository peerRequestRepository, + EventBus eventBus, + final ProjectFileService projectFileService, + final DaysService daysService, + Clock clock + ) { this.fileDescriptionService = fileDescriptionService; this.peerReviewRepository = peerReviewRepository; this.peerRequestRepository = peerRequestRepository; @@ -56,10 +56,10 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { @Override @Transactional public PeerReview acceptReview(PeerRequest peerRequest, User student, Project project) { - if(peerRequest.getProject().isParticipant(student)) { + if (peerRequest.getProject().isParticipant(student)) { throw new PartOfProjectException(); } - if(recentlyReviewedProject(peerRequest.getProject(), student, project)) { + if (recentlyReviewedProject(peerRequest.getProject(), student, project)) { throw new RecentlyReviewedException(); } if (peerRequest.getStatus() != RequestStatus.WAITING) { @@ -77,10 +77,11 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { review.setPeerRequest(peerRequest); review.setProject(project); review.setReviewer(student); - final int numDaysToSubmitPeerReview = peerRequest.getProject() - .getProjectType() - .getProjectTypeSettings() - .getNumDaysToSubmitPeerReview(); + final int numDaysToSubmitPeerReview = peerRequest + .getProject() + .getProjectType() + .getProjectTypeSettings() + .getNumDaysToSubmitPeerReview(); final Date deadline = daysService.workDaysAfter(new Date(), numDaysToSubmitPeerReview); review.setDeadline(deadline); review = peerReviewRepository.save(review); @@ -107,18 +108,22 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { ProjectTypeSettings settings = requestingProject.getProjectType().getProjectTypeSettings(); int daysBetweenReviewsOnSameProject = settings.getNumDaysBetweenPeerReviewsOnSameProject(); - Instant earliestPermissibleDateSinceReview = clock.instant() - .minus(Duration.ofDays(daysBetweenReviewsOnSameProject)); + Instant earliestPermissibleDateSinceReview = clock + .instant() + .minus(Duration.ofDays(daysBetweenReviewsOnSameProject)); QPeerReview qReview = QPeerReview.peerReview; Iterable performedReviews = peerReviewRepository.findAll( - qReview.reviewer.eq(student) - .and(qReview.project.eq(activeProject) - .and(qReview.status.eq(PeerReview.ReviewStatus.EXPIRED).not()))); + qReview.reviewer + .eq(student) + .and(qReview.project.eq(activeProject).and(qReview.status.eq(PeerReview.ReviewStatus.EXPIRED).not())) + ); for (PeerReview pr : performedReviews) { boolean sameProject = pr.getPeerRequest().getProject().equals(requestingProject); if (sameProject) { - boolean reviewPerformedBeforeLimit = pr.getLastModified().after(Date.from(earliestPermissibleDateSinceReview)); + boolean reviewPerformedBeforeLimit = pr + .getLastModified() + .after(Date.from(earliestPermissibleDateSinceReview)); if (reviewPerformedBeforeLimit) { return true; } @@ -127,7 +132,6 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { return false; } - @Override @Transactional public PeerRequest storePeerRequest(FileUpload fileUpload, PeerRequest request) { @@ -139,10 +143,9 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { @Override public PeerReview getInProgressReview(User peerReviewer, Project project) { QPeerReview q = QPeerReview.peerReview; - return peerReviewRepository.findOne(allOf( - q.reviewer.eq(peerReviewer), - q.status.eq(PeerReview.ReviewStatus.IN_PROGRESS), - q.project.eq(project))); + return peerReviewRepository.findOne( + allOf(q.reviewer.eq(peerReviewer), q.status.eq(PeerReview.ReviewStatus.IN_PROGRESS), q.project.eq(project)) + ); } @Override @@ -152,7 +155,7 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { } @Override - @Transactional(dontRollbackOn = {TooShortCommentException.class, MissingAnswerException.class}) + @Transactional(dontRollbackOn = { TooShortCommentException.class, MissingAnswerException.class }) public void submit(PeerReview review, Optional upload) { review.submit(); final Optional fileDescription = storePeerReviewFileUpload(upload); @@ -174,15 +177,17 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { } private void postCompletionEvent(PeerReview peerReview) { - long completed = peerReviewRepository.count(allOf( + long completed = peerReviewRepository.count( + allOf( QPeerReview.peerReview.reviewer.eq(peerReview.getReviewer()), QPeerReview.peerReview.status.eq(PeerReview.ReviewStatus.COMPLETED), - QPeerReview.peerReview.project.eq(peerReview.getProject()))); + QPeerReview.peerReview.project.eq(peerReview.getProject()) + ) + ); if (completed == 1) { eventBus.post(new FirstPeerReviewCompletedEvent(peerReview)); - } - else if (completed == 2) { + } else if (completed == 2) { eventBus.post(new SecondPeerReviewCompletedEvent(peerReview)); } } @@ -190,5 +195,4 @@ public class PeerPortalImpl implements PeerPortal, PerformReviewService { private Optional storePeerReviewFileUpload(Optional fileUpload) { return fileUpload.map(fileDescriptionService::storeFile); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequest.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequest.java index addf9fff54..37353ad555 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequest.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequest.java @@ -15,6 +15,9 @@ import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; import se.su.dsv.scipro.checklist.ChecklistTemplate; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.file.FileReference; @@ -23,14 +26,11 @@ import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.User; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - @Entity @Table(name = "peer_request") @Cacheable(true) public class PeerRequest extends DomainObject { + // ---------------------------------------------------------------------------------- // basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -63,7 +63,7 @@ public class PeerRequest extends DomainObject { @ManyToOne(optional = false) @JoinColumn(name = "project_id", referencedColumnName = "id") - @QueryInit({"headSupervisor", "projectType"}) + @QueryInit({ "headSupervisor", "projectType" }) private Project project; @ManyToOne(optional = false) @@ -158,8 +158,7 @@ public class PeerRequest extends DomainObject { public List getMembers() { List members = project.getMembers(); - members.removeIf(member -> member.getType() == Member.Type.AUTHOR && - member.getUser().equals(requester)); + members.removeIf(member -> member.getType() == Member.Type.AUTHOR && member.getUser().equals(requester)); members.add(new Member(requester, Member.Type.PEER_REQUESTER)); return members; @@ -183,8 +182,7 @@ public class PeerRequest extends DomainObject { if (o == this) return true; if (!(o instanceof PeerRequest)) return false; final PeerRequest other = (PeerRequest) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -194,9 +192,24 @@ public class PeerRequest extends DomainObject { @Override public String toString() { - return "PeerRequest(id=" + this.getId() + ", comment=" + this.getComment() + ", project=" + - this.getProject() + ", requester=" + this.getRequester() + ", file=" + this.getFile() + - ", checklistTemplate=" + this.getChecklistTemplate() + ", language=" + this.getLanguage() + - ", status=" + this.getStatus() + ")"; + return ( + "PeerRequest(id=" + + this.getId() + + ", comment=" + + this.getComment() + + ", project=" + + this.getProject() + + ", requester=" + + this.getRequester() + + ", file=" + + this.getFile() + + ", checklistTemplate=" + + this.getChecklistTemplate() + + ", language=" + + this.getLanguage() + + ", status=" + + this.getStatus() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestCancelledEvent.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestCancelledEvent.java index 4d0aa01aa2..fc00e95224 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestCancelledEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestCancelledEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.peer; public final class PeerRequestCancelledEvent { + private final PeerRequest peerRequest; PeerRequestCancelledEvent(final PeerRequest peerRequest) { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestExpiredEvent.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestExpiredEvent.java index f4bd36de10..17c75369d9 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestExpiredEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestExpiredEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.peer; public final class PeerRequestExpiredEvent { + private final PeerRequest peerRequest; public PeerRequestExpiredEvent(final PeerRequest peerRequest) { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepository.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepository.java index 1a5c7439ff..bff5ed412d 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepository.java @@ -5,7 +5,5 @@ import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; @Transactional -public interface PeerRequestRepository extends JpaRepository, QueryDslPredicateExecutor { -} - - +public interface PeerRequestRepository + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepositoryImpl.java index 96663a5cd6..b237a4fb4f 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestRepositoryImpl.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class PeerRequestRepositoryImpl extends GenericRepo implements PeerRequestRepository { + @Inject public PeerRequestRepositoryImpl(Provider em) { super(em, PeerRequest.class, QPeerRequest.peerRequest); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestService.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestService.java index 5199cdd733..17e9cea674 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestService.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestService.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.*; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; -public interface PeerRequestService extends GenericService, FilteredService { - +public interface PeerRequestService + extends GenericService, FilteredService { List findAvailableRequests(User user, RequestStatus status, ProjectType pc, Pageable pageable); List findByStatus(RequestStatus status); @@ -24,6 +23,7 @@ public interface PeerRequestService extends GenericService, F void deleteRequest(PeerRequest request); class Filter implements Serializable { + private User supervisor; private User author; private Collection statuses; diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestServiceImpl.java index ad77dcfe22..16938e1036 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerRequestServiceImpl.java @@ -1,26 +1,25 @@ package se.su.dsv.scipro.peer; +import static com.querydsl.core.types.dsl.Expressions.allOf; + import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.Pageable; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.system.AbstractServiceImpl; import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.*; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - public class PeerRequestServiceImpl extends AbstractServiceImpl implements PeerRequestService { private final EventBus eventBus; @@ -125,9 +124,12 @@ public class PeerRequestServiceImpl extends AbstractServiceImpl findAvailableRequests(User user, RequestStatus status, ProjectType pc, Pageable pageable) { if (status != null && pc != null) { - return findAll(hasStatus(status).and(projectTypeIs(pc) - .and(QPeerRequest.peerRequest.project.projectStatus.eq(ProjectStatus.ACTIVE))) - .and(QPeerRequest.peerRequest.project.projectParticipants.any().eq(user).not()), pageable); + return findAll( + hasStatus(status) + .and(projectTypeIs(pc).and(QPeerRequest.peerRequest.project.projectStatus.eq(ProjectStatus.ACTIVE))) + .and(QPeerRequest.peerRequest.project.projectParticipants.any().eq(user).not()), + pageable + ); } else { return findAll(pageable); } @@ -140,8 +142,10 @@ public class PeerRequestServiceImpl extends AbstractServiceImpl findByRequesterAndProject(User requester, Project project) { - return from(QPeerRequest.peerRequest).where(allOf(isRequester(requester), QPeerRequest.peerRequest.project.eq(project))) - .orderBy(QPeerRequest.peerRequest.dateCreated.desc()).fetch(); + return from(QPeerRequest.peerRequest) + .where(allOf(isRequester(requester), QPeerRequest.peerRequest.project.eq(project))) + .orderBy(QPeerRequest.peerRequest.dateCreated.desc()) + .fetch(); } @Override @@ -149,13 +153,15 @@ public class PeerRequestServiceImpl extends AbstractServiceImpl answers = new ArrayList<>(); + @OneToMany(mappedBy = "peerReview", orphanRemoval = true, cascade = CascadeType.ALL) + @OrderBy("id") + private List answers = new ArrayList<>(); // ---------------------------------------------------------------------------------- // getters and setters @@ -174,9 +175,9 @@ public class PeerReview extends DomainObject implements Commentable { // other methods // ---------------------------------------------------------------------------------- @Override - public final String getCommentKey() { - return PeerReview.class.getCanonicalName(); - } + public final String getCommentKey() { + return PeerReview.class.getCanonicalName(); + } public List getMembers() { List members = peerRequest.getMembers(); @@ -199,11 +200,18 @@ public class PeerReview extends DomainObject implements Commentable { public void submit() { for (Answer answer : getAnswers()) { - if (isEmpty(answer.getMotivation()) || answer.getAnswer() == ChecklistAnswerEnum.NO_ANSWER || answer.getAnswer() == null) { + if ( + isEmpty(answer.getMotivation()) || + answer.getAnswer() == ChecklistAnswerEnum.NO_ANSWER || + answer.getAnswer() == null + ) { throw new MissingAnswerException(); } } - if (getAnswers().isEmpty() && (isEmpty(getComment()) || getComment().length() < MINIMUM_COMMENT_LENGTH_IF_NO_ANSWERS)) { + if ( + getAnswers().isEmpty() && + (isEmpty(getComment()) || getComment().length() < MINIMUM_COMMENT_LENGTH_IF_NO_ANSWERS) + ) { throw new TooShortCommentException(); } setStatus(isLate() ? ReviewStatus.EXPIRED : ReviewStatus.COMPLETED); @@ -222,8 +230,7 @@ public class PeerReview extends DomainObject implements Commentable { if (o == this) return true; if (!(o instanceof PeerReview)) return false; final PeerReview other = (PeerReview) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -233,10 +240,27 @@ public class PeerReview extends DomainObject implements Commentable { @Override public String toString() { - return "PeerReview(id=" + this.getId() + ", reviewer=" + this.getReviewer() + ", project=" + - this.getProject() + ", peerRequest=" + this.getPeerRequest() + ", answers=" + this.getAnswers() + - ", file=" + this.getFile() + ", comment=" + this.getComment() + ", status=" + this.getStatus() + - ", deadline=" + this.getDeadline() + ")"; + return ( + "PeerReview(id=" + + this.getId() + + ", reviewer=" + + this.getReviewer() + + ", project=" + + this.getProject() + + ", peerRequest=" + + this.getPeerRequest() + + ", answers=" + + this.getAnswers() + + ", file=" + + this.getFile() + + ", comment=" + + this.getComment() + + ", status=" + + this.getStatus() + + ", deadline=" + + this.getDeadline() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewEvent.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewEvent.java index 837047ad48..7c92619a0d 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewEvent.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; class PeerReviewEvent { + private final PeerReview peerReview; protected PeerReviewEvent(PeerReview peerReview) { diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepository.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepository.java index 8ae4a8cfc9..8579206a4c 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepository.java @@ -1,14 +1,11 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.util.*; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.QueryDslPredicateExecutor; +import se.su.dsv.scipro.system.User; public interface PeerReviewRepository extends JpaRepository, QueryDslPredicateExecutor { List findNonExpiredReviewsByProjectAuthor(User student, ProjectType projectType); } - - diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepositoryImpl.java index 054908f309..fda28be6e8 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewRepositoryImpl.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.GenericRepo; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.system.GenericRepo; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class PeerReviewRepositoryImpl extends GenericRepo implements PeerReviewRepository { + @Inject public PeerReviewRepositoryImpl(Provider em) { super(em, PeerReview.class, QPeerReview.peerReview); @@ -18,9 +18,9 @@ public class PeerReviewRepositoryImpl extends GenericRepo impl @Override public List findNonExpiredReviewsByProjectAuthor(User student, ProjectType projectType) { return createQuery() - .where(QPeerReview.peerReview.reviewer.eq(student)) - .where(QPeerReview.peerReview.project.projectType.eq(projectType)) - .where(QPeerReview.peerReview.status.ne(PeerReview.ReviewStatus.EXPIRED)) - .fetch(); + .where(QPeerReview.peerReview.reviewer.eq(student)) + .where(QPeerReview.peerReview.project.projectType.eq(projectType)) + .where(QPeerReview.peerReview.status.ne(PeerReview.ReviewStatus.EXPIRED)) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewService.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewService.java index 4434bf4477..13e1eae730 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewService.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewService.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.*; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; -public interface PeerReviewService extends GenericService, FilteredService { +public interface PeerReviewService + extends GenericService, FilteredService { List findNonExpiredReviewsByProjectAuthor(User student, Project project); List findAllCompleted(Pageable pageable); List findInProgressReviews(User student, Project project); @@ -20,6 +20,7 @@ public interface PeerReviewService extends GenericService, Fil Long countByStatusAndNoCheckListTemplate(Filter filter, PeerReview.ReviewStatus status); class Filter implements Serializable { + private User supervisor; private User author; private Project authorProject; diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewServiceImpl.java index 24d9eac359..8758af46c6 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerReviewServiceImpl.java @@ -3,17 +3,16 @@ package se.su.dsv.scipro.peer; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.*; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; public class PeerReviewServiceImpl extends AbstractServiceImpl implements PeerReviewService { @@ -97,7 +96,9 @@ public class PeerReviewServiceImpl extends AbstractServiceImpl @Override public List findInProgressReviews(User student, Project project) { - return findAll(reviewerIs(student).and(reviewProjectIs(project).and(hasStatus(PeerReview.ReviewStatus.IN_PROGRESS)))); + return findAll( + reviewerIs(student).and(reviewProjectIs(project).and(hasStatus(PeerReview.ReviewStatus.IN_PROGRESS))) + ); } @Override @@ -112,12 +113,13 @@ public class PeerReviewServiceImpl extends AbstractServiceImpl @Override public List findCompletedReviews(Project project) { - return project.getProjectParticipants() - .stream() - .map(author -> findNonExpiredReviewsByProjectAuthor(author, project)) - .flatMap(List::stream) - .filter(PeerReview::isCompleted) - .toList(); + return project + .getProjectParticipants() + .stream() + .map(author -> findNonExpiredReviewsByProjectAuthor(author, project)) + .flatMap(List::stream) + .filter(PeerReview::isCompleted) + .toList(); } @Override @@ -125,9 +127,7 @@ public class PeerReviewServiceImpl extends AbstractServiceImpl if (filter.getProjectTypes().isEmpty()) { return EMPTY_RESULT; } - return count( - QPeerReview.peerReview.status.eq(status) - .and(toPredicate(filter))); + return count(QPeerReview.peerReview.status.eq(status).and(toPredicate(filter))); } @Override @@ -183,7 +183,11 @@ public class PeerReviewServiceImpl extends AbstractServiceImpl } } - private static void startedBeforeFilter(PeerReviewService.Filter filter, QPeerReview peerReview, BooleanBuilder booleanBuilder) { + private static void startedBeforeFilter( + PeerReviewService.Filter filter, + QPeerReview peerReview, + BooleanBuilder booleanBuilder + ) { if (filter.getCreatedAfter() != null) { booleanBuilder.and(peerReview.dateCreated.after(filter.getCreatedAfter())); } @@ -248,6 +252,4 @@ public class PeerReviewServiceImpl extends AbstractServiceImpl public static BooleanExpression hasProjectType(ProjectType projectType) { return QPeerReview.peerReview.project.projectType.eq(projectType); } - - } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PeerWorkerSchedules.java b/core/src/main/java/se/su/dsv/scipro/peer/PeerWorkerSchedules.java index 4a164beeb5..f9a400c702 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PeerWorkerSchedules.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PeerWorkerSchedules.java @@ -1,21 +1,25 @@ package se.su.dsv.scipro.peer; -import se.su.dsv.scipro.system.Lifecycle; -import se.su.dsv.scipro.workerthreads.Scheduler; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.inject.Singleton; import java.util.concurrent.TimeUnit; +import se.su.dsv.scipro.system.Lifecycle; +import se.su.dsv.scipro.workerthreads.Scheduler; @Singleton public class PeerWorkerSchedules implements Lifecycle { + private final Scheduler scheduler; private final Provider expiredRequestWorker; private final Provider expiredReviewResetWorker; @Inject - public PeerWorkerSchedules(Scheduler scheduler, Provider expiredRequestWorker, Provider expiredReviewResetWorker) { + public PeerWorkerSchedules( + Scheduler scheduler, + Provider expiredRequestWorker, + Provider expiredReviewResetWorker + ) { this.scheduler = scheduler; this.expiredRequestWorker = expiredRequestWorker; this.expiredReviewResetWorker = expiredReviewResetWorker; @@ -28,7 +32,5 @@ public class PeerWorkerSchedules implements Lifecycle { } @Override - public void stop() { - - } + public void stop() {} } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/PerformReviewService.java b/core/src/main/java/se/su/dsv/scipro/peer/PerformReviewService.java index e5f14f6c24..1b38548e63 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/PerformReviewService.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/PerformReviewService.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.peer; +import java.util.Optional; import se.su.dsv.scipro.file.FileUpload; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.Optional; - public interface PerformReviewService { PeerReview getInProgressReview(User peerReviewer, Project project); PeerReview save(PeerReview peerReview); diff --git a/core/src/main/java/se/su/dsv/scipro/peer/RecentlyReviewedException.java b/core/src/main/java/se/su/dsv/scipro/peer/RecentlyReviewedException.java index e7100983d4..e050c4a0b8 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/RecentlyReviewedException.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/RecentlyReviewedException.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.peer; - -public class RecentlyReviewedException extends RuntimeException { -} +package se.su.dsv.scipro.peer; + +public class RecentlyReviewedException extends RuntimeException {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/RequestStatus.java b/core/src/main/java/se/su/dsv/scipro/peer/RequestStatus.java index f873b3ad64..575e8b6fbc 100755 --- a/core/src/main/java/se/su/dsv/scipro/peer/RequestStatus.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/RequestStatus.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.peer; public enum RequestStatus { - WAITING, TAKEN, FINISHED, CANCELED + WAITING, + TAKEN, + FINISHED, + CANCELED, } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/RequestTakenException.java b/core/src/main/java/se/su/dsv/scipro/peer/RequestTakenException.java index 60d5d3bba4..23fed3e278 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/RequestTakenException.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/RequestTakenException.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.peer; - -public class RequestTakenException extends RuntimeException { -} +package se.su.dsv.scipro.peer; + +public class RequestTakenException extends RuntimeException {} diff --git a/core/src/main/java/se/su/dsv/scipro/peer/SecondPeerReviewCompletedEvent.java b/core/src/main/java/se/su/dsv/scipro/peer/SecondPeerReviewCompletedEvent.java index 6c64c14eef..2a804217ed 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/SecondPeerReviewCompletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/SecondPeerReviewCompletedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.peer; public class SecondPeerReviewCompletedEvent extends PeerReviewEvent { + public SecondPeerReviewCompletedEvent(PeerReview peerReview) { super(peerReview); } diff --git a/core/src/main/java/se/su/dsv/scipro/peer/TooShortCommentException.java b/core/src/main/java/se/su/dsv/scipro/peer/TooShortCommentException.java index 8e33e0e417..9ee8ef90c2 100644 --- a/core/src/main/java/se/su/dsv/scipro/peer/TooShortCommentException.java +++ b/core/src/main/java/se/su/dsv/scipro/peer/TooShortCommentException.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.peer; -public class TooShortCommentException extends RuntimeException { -} +public class TooShortCommentException extends RuntimeException {} diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControl.java index eb07a44152..29d4f2e4c5 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControl.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.plagiarism; +import java.io.Serializable; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.system.User; -import java.io.Serializable; - public interface PlagiarismControl { /** * @param receiver Who should receive the analysed report. @@ -17,8 +16,11 @@ public interface PlagiarismControl { sealed interface Status extends Serializable { record NotSubmitted() implements Status {} + record Submitted() implements Status {} + record Analysed(String url, float percentMatched) implements Status {} + record Error(String message) implements Status {} } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControlImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControlImpl.java index d72913163d..137c4aacaf 100755 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControlImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismControlImpl.java @@ -1,6 +1,9 @@ package se.su.dsv.scipro.plagiarism; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.Objects; +import java.util.Optional; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; @@ -8,21 +11,18 @@ import se.su.dsv.scipro.plagiarism.urkund.UrkundSubmission; import se.su.dsv.scipro.plagiarism.urkund.UrkundSubmissionRepository; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Objects; -import java.util.Optional; - public class PlagiarismControlImpl implements PlagiarismControl { + private final PlagiarismRequestRepository plagiarismRequestRepository; private final UrkundSubmissionRepository urkundSubmissionRepository; private final FileService fileService; @Inject public PlagiarismControlImpl( - final PlagiarismRequestRepository plagiarismRequestRepository, - final UrkundSubmissionRepository urkundSubmissionRepository, - final FileService fileService) - { + final PlagiarismRequestRepository plagiarismRequestRepository, + final UrkundSubmissionRepository urkundSubmissionRepository, + final FileService fileService + ) { this.plagiarismRequestRepository = plagiarismRequestRepository; this.urkundSubmissionRepository = urkundSubmissionRepository; this.fileService = fileService; @@ -47,9 +47,14 @@ public class PlagiarismControlImpl implements PlagiarismControl { if (optionalUrkundSubmission.isPresent()) { UrkundSubmission urkundSubmission = optionalUrkundSubmission.get(); return switch (urkundSubmission.getState()) { - case SUBMISSION_FAILED, REJECTED, ERROR -> new Status.Error(improveUrkundMessage(urkundSubmission.getMessage())); + case SUBMISSION_FAILED, REJECTED, ERROR -> new Status.Error( + improveUrkundMessage(urkundSubmission.getMessage()) + ); case SUBMITTED, ACCEPTED -> new Status.Submitted(); - case ANALYZED -> new Status.Analysed(urkundSubmission.getReportUrl(), urkundSubmission.getSignificance()); + case ANALYZED -> new Status.Analysed( + urkundSubmission.getReportUrl(), + urkundSubmission.getSignificance() + ); }; } @@ -63,8 +68,7 @@ public class PlagiarismControlImpl implements PlagiarismControl { private String improveUrkundMessage(String originalMessage) { return switch (originalMessage) { - case "?wsRequestEntityIsTooLargeException" -> - "The document is too large to send automatically. Please log in to URKUND and upload the document manually."; + case "?wsRequestEntityIsTooLargeException" -> "The document is too large to send automatically. Please log in to URKUND and upload the document manually."; default -> originalMessage; }; } @@ -72,12 +76,13 @@ public class PlagiarismControlImpl implements PlagiarismControl { @Override @Transactional public void resubmit(final FileDescription file, final User receiver) { - urkundSubmissionRepository.findByFile(file) - .ifPresent(urkundSubmission -> { - final FileReference document = urkundSubmission.getDocument(); - urkundSubmissionRepository.delete(urkundSubmission); - fileService.delete(document); - }); + urkundSubmissionRepository + .findByFile(file) + .ifPresent(urkundSubmission -> { + final FileReference document = urkundSubmission.getDocument(); + urkundSubmissionRepository.delete(urkundSubmission); + fileService.delete(document); + }); submit(file, receiver); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequest.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequest.java index 1aece5bd51..fe25397821 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequest.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequest.java @@ -1,22 +1,21 @@ package se.su.dsv.scipro.plagiarism; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.util.Objects; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "plagiarism_request") class PlagiarismRequest { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -71,10 +70,12 @@ class PlagiarismRequest { if (o == this) return true; if (!(o instanceof PlagiarismRequest)) return false; final PlagiarismRequest other = (PlagiarismRequest) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getDocument(), other.getDocument()) - && Objects.equals(this.getReceiver(), other.getReceiver()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getDocument(), other.getDocument()) && + Objects.equals(this.getReceiver(), other.getReceiver()) + ); } @Override @@ -84,8 +85,15 @@ class PlagiarismRequest { @Override public String toString() { - return "PlagiarismRequest(id=" + this.getId() + ", fileDescription=" + this.getDocument() + - ", receiver=" + this.getReceiver() + ")"; + return ( + "PlagiarismRequest(id=" + + this.getId() + + ", fileDescription=" + + this.getDocument() + + ", receiver=" + + this.getReceiver() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepository.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepository.java index cf8334dba7..29feb4677c 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepository.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.plagiarism; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.file.FileDescription; - import java.util.Optional; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.system.JpaRepository; public interface PlagiarismRequestRepository extends JpaRepository { Optional findByFileDescription(FileDescription file); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepositoryImpl.java index fc8c91fb57..ff387f43b7 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismRequestRepositoryImpl.java @@ -1,14 +1,16 @@ package se.su.dsv.scipro.plagiarism; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.system.AbstractServiceImpl; + +public class PlagiarismRequestRepositoryImpl + extends AbstractServiceImpl + implements PlagiarismRequestRepository { -public class PlagiarismRequestRepositoryImpl extends AbstractServiceImpl implements PlagiarismRequestRepository { @Inject public PlagiarismRequestRepositoryImpl(final Provider em) { super(em, PlagiarismRequest.class, QPlagiarismRequest.plagiarismRequest); @@ -16,8 +18,9 @@ public class PlagiarismRequestRepositoryImpl extends AbstractServiceImpl findByFileDescription(final FileDescription file) { - final PlagiarismRequest plagiarismRequest = - findOne(QPlagiarismRequest.plagiarismRequest.document.fileDescription.eq(file)); + final PlagiarismRequest plagiarismRequest = findOne( + QPlagiarismRequest.plagiarismRequest.document.fileDescription.eq(file) + ); return Optional.ofNullable(plagiarismRequest); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismSubmitter.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismSubmitter.java index 8edc5b7551..4948156cca 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismSubmitter.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/PlagiarismSubmitter.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.plagiarism; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.file.FileReference; @@ -8,11 +11,8 @@ import se.su.dsv.scipro.plagiarism.urkund.UrkundService; import se.su.dsv.scipro.plagiarism.urkund.UrkundSettings; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.util.List; - public class PlagiarismSubmitter extends AbstractWorker { + private static final Logger LOG = LoggerFactory.getLogger(PlagiarismSubmitter.class); private final Provider urkundSettingsProvider; @@ -22,11 +22,11 @@ public class PlagiarismSubmitter extends AbstractWorker { @Inject public PlagiarismSubmitter( - final Provider urkundSettingsProvider, - final PlagiarismRequestRepository plagiarismRequestRepository, - final UrkundService urkundService, - final FileService fileService) - { + final Provider urkundSettingsProvider, + final PlagiarismRequestRepository plagiarismRequestRepository, + final UrkundService urkundService, + final FileService fileService + ) { this.urkundSettingsProvider = urkundSettingsProvider; this.plagiarismRequestRepository = plagiarismRequestRepository; this.urkundService = urkundService; diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/DocumentInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/DocumentInfo.java index 2e91f462d9..9e4b5793ad 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/DocumentInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/DocumentInfo.java @@ -1,22 +1,22 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.time.LocalDateTime; import java.util.Objects; final class DocumentInfo { + private final int id; private final LocalDateTime accepted; private final String downloadUrl; private final OptOutInfo optOutInfo; public DocumentInfo( - @JsonProperty("Id") int id, - @JsonProperty("Date") LocalDateTime accepted, - @JsonProperty("DownloadUrl") String downloadUrl, - @JsonProperty("OptOutInfo") OptOutInfo optOutInfo) - { + @JsonProperty("Id") int id, + @JsonProperty("Date") LocalDateTime accepted, + @JsonProperty("DownloadUrl") String downloadUrl, + @JsonProperty("OptOutInfo") OptOutInfo optOutInfo + ) { this.id = id; this.accepted = accepted; this.downloadUrl = downloadUrl; @@ -44,10 +44,12 @@ final class DocumentInfo { if (o == this) return true; if (!(o instanceof DocumentInfo)) return false; final DocumentInfo other = (DocumentInfo) o; - return this.getId() == other.getId() - && Objects.equals(this.getAccepted(), other.getAccepted()) - && Objects.equals(this.getDownloadUrl(), other.getDownloadUrl()) - && Objects.equals(this.getOptOutInfo(), other.getOptOutInfo()); + return ( + this.getId() == other.getId() && + Objects.equals(this.getAccepted(), other.getAccepted()) && + Objects.equals(this.getDownloadUrl(), other.getDownloadUrl()) && + Objects.equals(this.getOptOutInfo(), other.getOptOutInfo()) + ); } @Override @@ -57,6 +59,16 @@ final class DocumentInfo { @Override public String toString() { - return "DocumentInfo(id=" + this.getId() + ", accepted=" + this.getAccepted() + ", downloadUrl=" + this.getDownloadUrl() + ", optOutInfo=" + this.getOptOutInfo() + ")"; + return ( + "DocumentInfo(id=" + + this.getId() + + ", accepted=" + + this.getAccepted() + + ", downloadUrl=" + + this.getDownloadUrl() + + ", optOutInfo=" + + this.getOptOutInfo() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ErrorInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ErrorInfo.java index 389f3e41ef..0cbf97e3c6 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ErrorInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ErrorInfo.java @@ -1,18 +1,18 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Objects; import java.util.function.Function; final class ErrorInfo implements UrkundResponse { + private final String technicalMessage; private final String userFriendlyMessage; public ErrorInfo( - @JsonProperty("Message") String technicalMessage, - @JsonProperty("LocalisedMessage") String userFriendlyMessage) - { + @JsonProperty("Message") String technicalMessage, + @JsonProperty("LocalisedMessage") String userFriendlyMessage + ) { this.technicalMessage = technicalMessage; this.userFriendlyMessage = userFriendlyMessage; } @@ -36,8 +36,10 @@ final class ErrorInfo implements UrkundResponse { if (o == this) return true; if (!(o instanceof ErrorInfo)) return false; final ErrorInfo other = (ErrorInfo) o; - return Objects.equals(this.getTechnicalMessage(), other.getTechnicalMessage()) - && Objects.equals(this.getUserFriendlyMessage(), other.getUserFriendlyMessage()); + return ( + Objects.equals(this.getTechnicalMessage(), other.getTechnicalMessage()) && + Objects.equals(this.getUserFriendlyMessage(), other.getUserFriendlyMessage()) + ); } @Override @@ -47,6 +49,12 @@ final class ErrorInfo implements UrkundResponse { @Override public String toString() { - return "ErrorInfo(technicalMessage=" + this.getTechnicalMessage() + ", userFriendlyMessage=" + this.getUserFriendlyMessage() + ")"; + return ( + "ErrorInfo(technicalMessage=" + + this.getTechnicalMessage() + + ", userFriendlyMessage=" + + this.getUserFriendlyMessage() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/OptOutInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/OptOutInfo.java index 4b9dae5fdb..7425a4c0cd 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/OptOutInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/OptOutInfo.java @@ -1,17 +1,14 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Objects; final class OptOutInfo { + private final String url; private final String purpose; - public OptOutInfo( - @JsonProperty("Url") String url, - @JsonProperty("Message") String purpose) - { + public OptOutInfo(@JsonProperty("Url") String url, @JsonProperty("Message") String purpose) { this.url = url; this.purpose = purpose; } @@ -29,8 +26,7 @@ final class OptOutInfo { if (o == this) return true; if (!(o instanceof OptOutInfo)) return false; final OptOutInfo other = (OptOutInfo) o; - return Objects.equals(this.getUrl(), other.getUrl()) - && Objects.equals(this.getPurpose(), other.getPurpose()); + return (Objects.equals(this.getUrl(), other.getUrl()) && Objects.equals(this.getPurpose(), other.getPurpose())); } @Override @@ -40,6 +36,6 @@ final class OptOutInfo { @Override public String toString() { - return "OptOutInfo(url=" + this.getUrl() + ", purpose=" + this.getPurpose() + ")"; + return ("OptOutInfo(url=" + this.getUrl() + ", purpose=" + this.getPurpose() + ")"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReceiverInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReceiverInfo.java index b44583efa4..9cc5c28b70 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReceiverInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReceiverInfo.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Objects; final class ReceiverInfo { + private final String analysisAddress; private final String emailAddress; public ReceiverInfo( - @JsonProperty("AnalysisAddress") String analysisAddress, - @JsonProperty("EmailAddress") String emailAddress) - { + @JsonProperty("AnalysisAddress") String analysisAddress, + @JsonProperty("EmailAddress") String emailAddress + ) { this.analysisAddress = analysisAddress; this.emailAddress = emailAddress; } @@ -29,8 +29,10 @@ final class ReceiverInfo { if (o == this) return true; if (!(o instanceof ReceiverInfo)) return false; final ReceiverInfo other = (ReceiverInfo) o; - return Objects.equals(this.getAnalysisAddress(), other.getAnalysisAddress()) - && Objects.equals(this.getEmailAddress(), other.getEmailAddress()); + return ( + Objects.equals(this.getAnalysisAddress(), other.getAnalysisAddress()) && + Objects.equals(this.getEmailAddress(), other.getEmailAddress()) + ); } @Override @@ -40,6 +42,12 @@ final class ReceiverInfo { @Override public String toString() { - return "ReceiverInfo(analysisAddress=" + this.getAnalysisAddress() + ", emailAddress=" + this.getEmailAddress() + ")"; + return ( + "ReceiverInfo(analysisAddress=" + + this.getAnalysisAddress() + + ", emailAddress=" + + this.getEmailAddress() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReportInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReportInfo.java index 8319d07cde..6413b28168 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReportInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/ReportInfo.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Objects; final class ReportInfo { + private final int id; private final String reportUrl; private final float significance; @@ -12,12 +12,12 @@ final class ReportInfo { private final int sourceCount; public ReportInfo( - @JsonProperty("Id") int id, - @JsonProperty("ReportUrl") String reportUrl, - @JsonProperty("Significance") float significance, - @JsonProperty("MatchCount") int matchCount, - @JsonProperty("SourceCount") int sourceCount) - { + @JsonProperty("Id") int id, + @JsonProperty("ReportUrl") String reportUrl, + @JsonProperty("Significance") float significance, + @JsonProperty("MatchCount") int matchCount, + @JsonProperty("SourceCount") int sourceCount + ) { this.id = id; this.reportUrl = reportUrl; this.significance = significance; @@ -50,20 +50,40 @@ final class ReportInfo { if (o == this) return true; if (!(o instanceof ReportInfo)) return false; final ReportInfo other = (ReportInfo) o; - return this.getId() == other.getId() - && Objects.equals(this.getReportUrl(), other.getReportUrl()) - && Float.compare(this.getSignificance(), other.getSignificance()) == 0 - && this.getMatchCount() == other.getMatchCount() - && this.getSourceCount() == other.getSourceCount(); + return ( + this.getId() == other.getId() && + Objects.equals(this.getReportUrl(), other.getReportUrl()) && + Float.compare(this.getSignificance(), other.getSignificance()) == 0 && + this.getMatchCount() == other.getMatchCount() && + this.getSourceCount() == other.getSourceCount() + ); } @Override public int hashCode() { - return Objects.hash(this.getId(), this.getReportUrl(), this.getSignificance(), this.getMatchCount(), this.getSourceCount()); + return Objects.hash( + this.getId(), + this.getReportUrl(), + this.getSignificance(), + this.getMatchCount(), + this.getSourceCount() + ); } @Override public String toString() { - return "ReportInfo(id=" + this.getId() + ", reportUrl=" + this.getReportUrl() + ", significance=" + this.getSignificance() + ", matchCount=" + this.getMatchCount() + ", sourceCount=" + this.getSourceCount() + ")"; + return ( + "ReportInfo(id=" + + this.getId() + + ", reportUrl=" + + this.getReportUrl() + + ", significance=" + + this.getSignificance() + + ", matchCount=" + + this.getMatchCount() + + ", sourceCount=" + + this.getSourceCount() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusInfo.java index 174fd0b575..2b20d6a3b0 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusInfo.java @@ -1,25 +1,22 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.Objects; final class StatusInfo { + public enum State { Submitted, Rejected, Accepted, Analyzed, - Error + Error, } private final State state; private final String userFriendlyMessage; - public StatusInfo( - @JsonProperty("State") State state, - @JsonProperty("Message") String userFriendlyMessage) - { + public StatusInfo(@JsonProperty("State") State state, @JsonProperty("Message") String userFriendlyMessage) { this.state = state; this.userFriendlyMessage = userFriendlyMessage; } @@ -37,8 +34,10 @@ final class StatusInfo { if (o == this) return true; if (!(o instanceof StatusInfo)) return false; final StatusInfo other = (StatusInfo) o; - return Objects.equals(this.getState(), other.getState()) - && Objects.equals(this.getUserFriendlyMessage(), other.getUserFriendlyMessage()); + return ( + Objects.equals(this.getState(), other.getState()) && + Objects.equals(this.getUserFriendlyMessage(), other.getUserFriendlyMessage()) + ); } @Override @@ -48,6 +47,6 @@ final class StatusInfo { @Override public String toString() { - return "StatusInfo(state=" + this.getState() + ", userFriendlyMessage=" + this.getUserFriendlyMessage() + ")"; + return ("StatusInfo(state=" + this.getState() + ", userFriendlyMessage=" + this.getUserFriendlyMessage() + ")"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusPollingWorker.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusPollingWorker.java index 00c19759ce..320d3323db 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusPollingWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/StatusPollingWorker.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.plagiarism.urkund; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import java.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.sukat.Sukat; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.time.Instant; - public class StatusPollingWorker extends AbstractWorker { + private static final Logger LOG = LoggerFactory.getLogger(StatusPollingWorker.class); private final UrkundSubmissionRepository urkundSubmissionRepository; @@ -19,11 +19,11 @@ public class StatusPollingWorker extends AbstractWorker { @Inject public StatusPollingWorker( - final UrkundSubmissionRepository urkundSubmissionRepository, - final UrkundApi urkundApi, - final Provider urkundSettingsProvider, - final Sukat sukat) - { + final UrkundSubmissionRepository urkundSubmissionRepository, + final UrkundApi urkundApi, + final Provider urkundSettingsProvider, + final Sukat sukat + ) { this.urkundSubmissionRepository = urkundSubmissionRepository; this.urkundApi = urkundApi; this.urkundSettingsProvider = urkundSettingsProvider; @@ -38,21 +38,29 @@ public class StatusPollingWorker extends AbstractWorker { for (UrkundSubmission submission : urkundSubmissionRepository.findNotDone()) { if (submission.getNextPoll().isBefore(Instant.now())) { final UrkundResponse urkundResponse = urkundApi.submissionInfo( - getAnalysisAddress(submission), - submission.getDocument().getFileDescription()); + getAnalysisAddress(submission), + submission.getDocument().getFileDescription() + ); final boolean updated = urkundResponse.fold( - errorInfo -> Boolean.FALSE, - submissionInfo -> { - final UrkundSubmission.State state = Util.getState(submissionInfo.getStatus().getState()); - if (state != submission.getState()) { - submission.setState(state); - submission.setMessage(submissionInfo.getStatus().getUserFriendlyMessage()); - submissionInfo.getReport().map(ReportInfo::getReportUrl).ifPresent(submission::setReportUrl); - submissionInfo.getReport().map(ReportInfo::getSignificance).ifPresent(submission::setSignificance); - return Boolean.TRUE; - } - return Boolean.FALSE; - }); + errorInfo -> Boolean.FALSE, + submissionInfo -> { + final UrkundSubmission.State state = Util.getState(submissionInfo.getStatus().getState()); + if (state != submission.getState()) { + submission.setState(state); + submission.setMessage(submissionInfo.getStatus().getUserFriendlyMessage()); + submissionInfo + .getReport() + .map(ReportInfo::getReportUrl) + .ifPresent(submission::setReportUrl); + submissionInfo + .getReport() + .map(ReportInfo::getSignificance) + .ifPresent(submission::setSignificance); + return Boolean.TRUE; + } + return Boolean.FALSE; + } + ); final PollingDelay next = submission.getPollingDelay().next(); final Instant nextPoll = submission.getNextPoll().plus(next.getDuration()); submission.setPollingDelay(next); @@ -61,7 +69,12 @@ public class StatusPollingWorker extends AbstractWorker { if (submission.getState().isFinal()) { LOG.info("{} reached the final state {}", submission, submission.getState()); } else { - LOG.info("{} reached {} state, will poll again in {}", submission, submission.getState(), submission.getPollingDelay()); + LOG.info( + "{} reached {} state, will poll again in {}", + submission, + submission.getState(), + submission.getPollingDelay() + ); } } urkundSubmissionRepository.save(submission); @@ -78,16 +91,16 @@ public class StatusPollingWorker extends AbstractWorker { private String getAnalysisAddress(UrkundSubmission submission) { if (submission.getAnalysisAddress() != null) { return submission.getAnalysisAddress(); - } - else { - return submission.getReceiver() - .getUsernames() - .stream() - .filter(username -> username.getUsername().endsWith("@su.se")) - .findAny() - .flatMap(sukat::email) - .flatMap(urkundApi::analysisAddress) - .orElse(submission.getReceiver().getEmailAddress()); + } else { + return submission + .getReceiver() + .getUsernames() + .stream() + .filter(username -> username.getUsername().endsWith("@su.se")) + .findAny() + .flatMap(sukat::email) + .flatMap(urkundApi::analysisAddress) + .orElse(submission.getReceiver().getEmailAddress()); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/SubmissionInfo.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/SubmissionInfo.java index f47cfa0586..f9c73ba306 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/SubmissionInfo.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/SubmissionInfo.java @@ -2,13 +2,13 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; - import java.time.LocalDateTime; import java.util.Objects; import java.util.Optional; import java.util.function.Function; final class SubmissionInfo implements UrkundResponse { + private final int id; private final String externalId; private final LocalDateTime submitted; @@ -23,18 +23,18 @@ final class SubmissionInfo implements UrkundResponse { @JsonCreator public SubmissionInfo( - @JsonProperty("Id") int id, - @JsonProperty("ExternalId") String externalId, - @JsonProperty("Timestamp") LocalDateTime submitted, - @JsonProperty("Filename") String filename, - @JsonProperty("MimeType") String mimeType, - @JsonProperty("Status") StatusInfo status, - @JsonProperty("Document") Optional document, - @JsonProperty("Report") Optional report, - @JsonProperty("Subject") String subject, - @JsonProperty("Message") String message, - @JsonProperty("Anonymous") boolean anonymous) - { + @JsonProperty("Id") int id, + @JsonProperty("ExternalId") String externalId, + @JsonProperty("Timestamp") LocalDateTime submitted, + @JsonProperty("Filename") String filename, + @JsonProperty("MimeType") String mimeType, + @JsonProperty("Status") StatusInfo status, + @JsonProperty("Document") Optional document, + @JsonProperty("Report") Optional report, + @JsonProperty("Subject") String subject, + @JsonProperty("Message") String message, + @JsonProperty("Anonymous") boolean anonymous + ) { this.id = id; this.externalId = externalId; this.submitted = submitted; @@ -102,37 +102,64 @@ final class SubmissionInfo implements UrkundResponse { if (o == this) return true; if (!(o instanceof SubmissionInfo)) return false; final SubmissionInfo other = (SubmissionInfo) o; - return this.getId() == other.getId() - && Objects.equals(this.getExternalId(), other.getExternalId()) - && Objects.equals(this.getSubmitted(), other.getSubmitted()) - && Objects.equals(this.getFilename(), other.getFilename()) - && Objects.equals(this.getMimeType(), other.getMimeType()) - && Objects.equals(this.getStatus(), other.getStatus()) - && Objects.equals(this.getDocument(), other.getDocument()) - && Objects.equals(this.getReport(), other.getReport()) - && Objects.equals(this.getSubject(), other.getSubject()) - && Objects.equals(this.getMessage(), other.getMessage()) - && this.isAnonymous() == other.isAnonymous(); + return ( + this.getId() == other.getId() && + Objects.equals(this.getExternalId(), other.getExternalId()) && + Objects.equals(this.getSubmitted(), other.getSubmitted()) && + Objects.equals(this.getFilename(), other.getFilename()) && + Objects.equals(this.getMimeType(), other.getMimeType()) && + Objects.equals(this.getStatus(), other.getStatus()) && + Objects.equals(this.getDocument(), other.getDocument()) && + Objects.equals(this.getReport(), other.getReport()) && + Objects.equals(this.getSubject(), other.getSubject()) && + Objects.equals(this.getMessage(), other.getMessage()) && + this.isAnonymous() == other.isAnonymous() + ); } @Override public int hashCode() { return Objects.hash( - this.getId(), - this.getExternalId(), - this.getSubmitted(), - this.getFilename(), - this.getMimeType(), - this.getStatus(), - this.getDocument(), - this.getReport(), - this.getSubject(), - this.getMessage(), - this.isAnonymous()); + this.getId(), + this.getExternalId(), + this.getSubmitted(), + this.getFilename(), + this.getMimeType(), + this.getStatus(), + this.getDocument(), + this.getReport(), + this.getSubject(), + this.getMessage(), + this.isAnonymous() + ); } @Override public String toString() { - return "SubmissionInfo(id=" + this.getId() + ", externalId=" + this.getExternalId() + ", submitted=" + this.getSubmitted() + ", filename=" + this.getFilename() + ", mimeType=" + this.getMimeType() + ", status=" + this.getStatus() + ", document=" + this.getDocument() + ", report=" + this.getReport() + ", subject=" + this.getSubject() + ", message=" + this.getMessage() + ", anonymous=" + this.isAnonymous() + ")"; + return ( + "SubmissionInfo(id=" + + this.getId() + + ", externalId=" + + this.getExternalId() + + ", submitted=" + + this.getSubmitted() + + ", filename=" + + this.getFilename() + + ", mimeType=" + + this.getMimeType() + + ", status=" + + this.getStatus() + + ", document=" + + this.getDocument() + + ", report=" + + this.getReport() + + ", subject=" + + this.getSubject() + + ", message=" + + this.getMessage() + + ", anonymous=" + + this.isAnonymous() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApi.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApi.java index 5decbfdea8..9a5c5fd7a6 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApi.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApi.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.plagiarism.urkund; -import se.su.dsv.scipro.file.FileDescription; - import java.util.Optional; +import se.su.dsv.scipro.file.FileDescription; public interface UrkundApi { UrkundResponse submitDocument(String receiver, FileDescription file); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApiImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApiImpl.java index 5a5f58f929..3d78a715c7 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApiImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundApiImpl.java @@ -2,11 +2,7 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileService; - import jakarta.inject.Inject; - import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -23,6 +19,8 @@ import java.util.Base64; import java.util.List; import java.util.Optional; import java.util.concurrent.Flow; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileService; /** * URKUND allows multiple submissions using the same external id. SciPro is @@ -47,21 +45,25 @@ public class UrkundApiImpl implements UrkundApi { @Override public UrkundResponse submitDocument(final String receiver, final FileDescription file) { final HttpRequest httpPost = HttpRequest.newBuilder() - .POST(new FixedSizeBodyPublisher(HttpRequest.BodyPublishers.ofInputStream(() -> fileService.getData(file)), file.getSize())) - .uri(URI.create("https://secure.urkund.com/api/rest/submissions/" + receiver + "/" + file.getId())) - .header("x-urkund-filename", urkundFilename(file)) - .header("x-urkund-submitter", file.getUploader().getEmailAddress()) - .header("Accept", "application/json") - .header("Content-Type", file.getMimeType()) - .build(); + .POST( + new FixedSizeBodyPublisher( + HttpRequest.BodyPublishers.ofInputStream(() -> fileService.getData(file)), + file.getSize() + ) + ) + .uri(URI.create("https://secure.urkund.com/api/rest/submissions/" + receiver + "/" + file.getId())) + .header("x-urkund-filename", urkundFilename(file)) + .header("x-urkund-submitter", file.getUploader().getEmailAddress()) + .header("Accept", "application/json") + .header("Content-Type", file.getMimeType()) + .build(); return sendToUrkund(httpPost); } private String urkundFilename(final FileDescription file) { final Charset charset = StandardCharsets.UTF_8; - final byte[] encoded = Base64.getEncoder() - .encode(file.getName().getBytes(charset)); + final byte[] encoded = Base64.getEncoder().encode(file.getName().getBytes(charset)); return new String(encoded, charset); } @@ -69,10 +71,10 @@ public class UrkundApiImpl implements UrkundApi { public UrkundResponse submissionInfo(final String receiver, final FileDescription file) { final String analysisAddress = analysisAddress(receiver).orElse(receiver); final HttpRequest httpPost = HttpRequest.newBuilder() - .GET() - .uri(URI.create("https://secure.urkund.com/api/rest/submissions/" + analysisAddress + "/" + file.getId())) - .header("Accept", "application/json") - .build(); + .GET() + .uri(URI.create("https://secure.urkund.com/api/rest/submissions/" + analysisAddress + "/" + file.getId())) + .header("Accept", "application/json") + .build(); return sendToUrkund(httpPost); } @@ -80,17 +82,21 @@ public class UrkundApiImpl implements UrkundApi { @Override public Optional analysisAddress(final String email) { final HttpRequest httpGet = HttpRequest.newBuilder() - .GET() - .uri(URI.create("https://secure.urkund.com/api/receivers?EmailAddress=" + email)) - .header("Accept", "application/json") - .build(); - final List receiverInfos = sendToUrkund_(httpGet, response -> objectMapper.readValue( + .GET() + .uri(URI.create("https://secure.urkund.com/api/receivers?EmailAddress=" + email)) + .header("Accept", "application/json") + .build(); + final List receiverInfos = sendToUrkund_(httpGet, response -> + objectMapper.readValue( response.body(), - objectMapper.getTypeFactory().constructCollectionType(List.class, ReceiverInfo.class))); - return receiverInfos.stream() - .filter(ri -> ri.getEmailAddress().equals(email)) - .map(ReceiverInfo::getAnalysisAddress) - .findAny(); + objectMapper.getTypeFactory().constructCollectionType(List.class, ReceiverInfo.class) + ) + ); + return receiverInfos + .stream() + .filter(ri -> ri.getEmailAddress().equals(email)) + .map(ReceiverInfo::getAnalysisAddress) + .findAny(); } private interface FailingFunction { @@ -99,9 +105,7 @@ public class UrkundApiImpl implements UrkundApi { private A sendToUrkund_(final HttpRequest request, final FailingFunction, A> f) { UrkundSettings urkundSettings = urkundSettingsRepository.getSettings(); - HttpClient client = HttpClient.newBuilder() - .authenticator(new UrkundAuthenticator(urkundSettings)) - .build(); + HttpClient client = HttpClient.newBuilder().authenticator(new UrkundAuthenticator(urkundSettings)).build(); try { final HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); return f.apply(response); @@ -117,7 +121,10 @@ public class UrkundApiImpl implements UrkundApi { return sendToUrkund_(request, response -> { switch (response.statusCode()) { case 200: - final List submissionInfos = objectMapper.readValue(response.body(), objectMapper.getTypeFactory().constructCollectionType(List.class, SubmissionInfo.class)); + final List submissionInfos = objectMapper.readValue( + response.body(), + objectMapper.getTypeFactory().constructCollectionType(List.class, SubmissionInfo.class) + ); return submissionInfos.get(0); case 202: return objectMapper.readValue(response.body(), SubmissionInfo.class); @@ -128,12 +135,13 @@ public class UrkundApiImpl implements UrkundApi { return objectMapper.readValue(response.body(), ErrorInfo.class); default: final String body = new String(response.body().readAllBytes(), StandardCharsets.UTF_8); - throw new RuntimeException("Unknown response from URKUND: " + response.statusCode() +": " + body); + throw new RuntimeException("Unknown response from URKUND: " + response.statusCode() + ": " + body); } }); } private static class UrkundAuthenticator extends Authenticator { + private final UrkundSettings settings; public UrkundAuthenticator(UrkundSettings settings) { @@ -147,6 +155,7 @@ public class UrkundApiImpl implements UrkundApi { } private static final class FixedSizeBodyPublisher implements HttpRequest.BodyPublisher { + private final HttpRequest.BodyPublisher bodyPublisher; private final long size; diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundResponse.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundResponse.java index 7bf814cf2d..09e28f1e99 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundResponse.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundResponse.java @@ -3,7 +3,7 @@ package se.su.dsv.scipro.plagiarism.urkund; import java.util.function.Function; interface UrkundResponse { - X fold(Function ifError,Function ifSubmission); + X fold(Function ifError, Function ifSubmission); default String getUserFriendlyMessage() { return fold(ErrorInfo::getUserFriendlyMessage, si -> si.getStatus().getUserFriendlyMessage()); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundService.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundService.java index 1bf439d4dd..073af2592c 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundService.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.plagiarism.urkund; +import java.util.Optional; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.system.User; -import java.util.Optional; - public interface UrkundService { UrkundSubmission submit(FileDescription file, User receiver); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundServiceImpl.java index e83125690b..187af3a1bc 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundServiceImpl.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.plagiarism.urkund; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; @@ -8,12 +12,8 @@ import se.su.dsv.scipro.sukat.Sukat; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.Username; -import jakarta.inject.Inject; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Optional; - public class UrkundServiceImpl implements UrkundService { + private final UrkundApi urkundApi; private final UrkundSubmissionRepository urkundSubmissionRepository; private final Sukat sukat; @@ -21,11 +21,11 @@ public class UrkundServiceImpl implements UrkundService { @Inject public UrkundServiceImpl( - final UrkundApi urkundApi, - final UrkundSubmissionRepository urkundSubmissionRepository, - final Sukat sukat, - final FileService fileService) - { + final UrkundApi urkundApi, + final UrkundSubmissionRepository urkundSubmissionRepository, + final Sukat sukat, + final FileService fileService + ) { this.urkundApi = urkundApi; this.urkundSubmissionRepository = urkundSubmissionRepository; this.sukat = sukat; @@ -40,17 +40,18 @@ public class UrkundServiceImpl implements UrkundService { } private UrkundSubmission submitToUrkund(final FileDescription file, final User receiver) { - return receiver.getUsernames() - .stream() - .filter(UrkundServiceImpl::isSuUsername) - .findAny() - .flatMap(sukat::email) - .flatMap(urkundApi::analysisAddress) - .map(analysisAddress -> { - UrkundResponse urkundResponse = urkundApi.submitDocument(analysisAddress, file); - return toSubmission(file, receiver, urkundResponse, analysisAddress); - }) - .orElseGet(() -> missingAnalysisAddress(file, receiver)); + return receiver + .getUsernames() + .stream() + .filter(UrkundServiceImpl::isSuUsername) + .findAny() + .flatMap(sukat::email) + .flatMap(urkundApi::analysisAddress) + .map(analysisAddress -> { + UrkundResponse urkundResponse = urkundApi.submitDocument(analysisAddress, file); + return toSubmission(file, receiver, urkundResponse, analysisAddress); + }) + .orElseGet(() -> missingAnalysisAddress(file, receiver)); } private UrkundSubmission missingAnalysisAddress(final FileDescription file, final User receiver) { @@ -74,21 +75,31 @@ public class UrkundServiceImpl implements UrkundService { return urkundSubmissionRepository.findByFile(file); } - private UrkundSubmission toSubmission(final FileDescription file, final User receiver, final UrkundResponse urkundResponse, String analysisAddress) { + private UrkundSubmission toSubmission( + final FileDescription file, + final User receiver, + final UrkundResponse urkundResponse, + String analysisAddress + ) { final FileReference reference = fileService.createReference(file); final UrkundSubmission submission = new UrkundSubmission(); submission.setDocument(reference); submission.setReceiver(receiver); submission.setAnalysisAddress(analysisAddress); - submission.setState(urkundResponse.fold( + submission.setState( + urkundResponse.fold( error -> UrkundSubmission.State.SUBMISSION_FAILED, - submissionInfo -> Util.getState(submissionInfo.getStatus().getState()))); + submissionInfo -> Util.getState(submissionInfo.getStatus().getState()) + ) + ); submission.setMessage(urkundResponse.getUserFriendlyMessage()); - submission.setSubmitted(urkundResponse.fold( + submission.setSubmitted( + urkundResponse.fold( e -> Instant.now(), - submissionInfo -> submissionInfo.getSubmitted().toInstant(ZoneOffset.UTC))); + submissionInfo -> submissionInfo.getSubmitted().toInstant(ZoneOffset.UTC) + ) + ); submission.setNextPoll(submission.getSubmitted().plus(submission.getPollingDelay().getDuration())); return urkundSubmissionRepository.save(submission); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettings.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettings.java index fa97b51a46..838dd42e80 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettings.java @@ -5,12 +5,12 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import java.util.Objects; @Entity @Table(name = "urkund_settings") public class UrkundSettings { + static final long ID = 1L; @Id @@ -57,11 +57,13 @@ public class UrkundSettings { if (o == this) return true; if (!(o instanceof UrkundSettings)) return false; final UrkundSettings other = (UrkundSettings) o; - return other.canEqual(this) - && this.id == other.id - && this.isEnabled() == other.isEnabled() - && Objects.equals(this.getUsername(), other.getUsername()) - && Objects.equals(this.getPassword(), other.getPassword()); + return ( + other.canEqual(this) && + this.id == other.id && + this.isEnabled() == other.isEnabled() && + Objects.equals(this.getUsername(), other.getUsername()) && + Objects.equals(this.getPassword(), other.getPassword()) + ); } protected boolean canEqual(final Object other) { @@ -75,7 +77,16 @@ public class UrkundSettings { @Override public String toString() { - return "UrkundSettings(id=" + this.id + ", enabled=" + this.isEnabled() + ", username=" + - this.getUsername() + ", password=" + this.getPassword() + ")"; + return ( + "UrkundSettings(id=" + + this.id + + ", enabled=" + + this.isEnabled() + + ", username=" + + this.getUsername() + + ", password=" + + this.getPassword() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryImpl.java index 6ca3bfdc58..e140ef1d99 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryImpl.java @@ -6,6 +6,7 @@ import jakarta.persistence.EntityManager; import java.util.Optional; public class UrkundSettingsRepositoryImpl implements UrkundSettingsRepository { + private final Provider entityManagerProvider; @Inject @@ -15,8 +16,7 @@ public class UrkundSettingsRepositoryImpl implements UrkundSettingsRepository { @Override public UrkundSettings getSettings() { - final UrkundSettings urkundSettings = entityManagerProvider.get() - .find(UrkundSettings.class, UrkundSettings.ID); + final UrkundSettings urkundSettings = entityManagerProvider.get().find(UrkundSettings.class, UrkundSettings.ID); return Optional.ofNullable(urkundSettings).orElse(new UrkundSettings()); } @@ -25,8 +25,7 @@ public class UrkundSettingsRepositoryImpl implements UrkundSettingsRepository { final EntityManager em = entityManagerProvider.get(); if (em.contains(urkundSettings)) { return em.merge(urkundSettings); - } - else { + } else { em.persist(urkundSettings); return urkundSettings; } diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmission.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmission.java index 87580259a7..745f2ed15d 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmission.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmission.java @@ -1,16 +1,12 @@ package se.su.dsv.scipro.plagiarism.urkund; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.User; - import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; @@ -18,10 +14,14 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; import java.time.Instant; import java.util.Objects; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "urkund_submission") public class UrkundSubmission extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -175,45 +175,67 @@ public class UrkundSubmission extends DomainObject { if (o == this) return true; if (!(o instanceof UrkundSubmission)) return false; final UrkundSubmission other = (UrkundSubmission) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getReceiver(), other.getReceiver()) - && Objects.equals(this.getAnalysisAddress(), other.getAnalysisAddress()) - && Objects.equals(this.getState(), other.getState()) - && Objects.equals(this.getSubmitted(), other.getSubmitted()) - && Objects.equals(this.getNextPoll(), other.getNextPoll()) - && Objects.equals(this.getPollingDelay(), other.getPollingDelay()) - && Objects.equals(this.getDocument(), other.getDocument()) - && Objects.equals(this.getMessage(), other.getMessage()) - && Objects.equals(this.getReportUrl(), other.getReportUrl()) - && Objects.equals(this.getSignificance(), other.getSignificance()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getReceiver(), other.getReceiver()) && + Objects.equals(this.getAnalysisAddress(), other.getAnalysisAddress()) && + Objects.equals(this.getState(), other.getState()) && + Objects.equals(this.getSubmitted(), other.getSubmitted()) && + Objects.equals(this.getNextPoll(), other.getNextPoll()) && + Objects.equals(this.getPollingDelay(), other.getPollingDelay()) && + Objects.equals(this.getDocument(), other.getDocument()) && + Objects.equals(this.getMessage(), other.getMessage()) && + Objects.equals(this.getReportUrl(), other.getReportUrl()) && + Objects.equals(this.getSignificance(), other.getSignificance()) + ); } @Override public int hashCode() { return Objects.hash( - this.getId(), - this.getReceiver(), - this.getAnalysisAddress(), - this.getState(), - this.getSubmitted(), - this.getNextPoll(), - this.getPollingDelay(), - this.getDocument(), - this.getMessage(), - this.getReportUrl(), - this.getSignificance()); + this.getId(), + this.getReceiver(), + this.getAnalysisAddress(), + this.getState(), + this.getSubmitted(), + this.getNextPoll(), + this.getPollingDelay(), + this.getDocument(), + this.getMessage(), + this.getReportUrl(), + this.getSignificance() + ); } @Override public String toString() { - return "UrkundSubmission(id=" + this.getId() + ", receiver=" + this.getReceiver() + - ", analysisAddress=" + this.getAnalysisAddress() + ", state=" + - this.getState() + ", submitted=" + this.getSubmitted() + - ", nextPoll=" + this.getNextPoll() + ", pollingDelay=" + this.getPollingDelay() + - ", fileDescription=" + this.getDocument() + ", message=" + this.getMessage() + - ", reportUrl=" + this.getReportUrl() + ", significance=" + this.getSignificance() + ")"; + return ( + "UrkundSubmission(id=" + + this.getId() + + ", receiver=" + + this.getReceiver() + + ", analysisAddress=" + + this.getAnalysisAddress() + + ", state=" + + this.getState() + + ", submitted=" + + this.getSubmitted() + + ", nextPoll=" + + this.getNextPoll() + + ", pollingDelay=" + + this.getPollingDelay() + + ", fileDescription=" + + this.getDocument() + + ", message=" + + this.getMessage() + + ", reportUrl=" + + this.getReportUrl() + + ", significance=" + + this.getSignificance() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -227,7 +249,12 @@ public class UrkundSubmission extends DomainObject { // Nested type // ---------------------------------------------------------------------------------- public enum State { - SUBMISSION_FAILED, SUBMITTED, REJECTED, ACCEPTED, ANALYZED, ERROR; + SUBMISSION_FAILED, + SUBMITTED, + REJECTED, + ACCEPTED, + ANALYZED, + ERROR; public boolean isFinal() { return !(this == SUBMITTED || this == ACCEPTED); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepository.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepository.java index 516538dee5..ed9ae26c00 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepository.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.plagiarism.urkund; -import se.su.dsv.scipro.file.FileDescription; - import java.util.Collection; import java.util.Optional; +import se.su.dsv.scipro.file.FileDescription; public interface UrkundSubmissionRepository { Optional findByFile(FileDescription file); diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryImpl.java index d88963780e..43c05246c3 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryImpl.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.plagiarism.urkund; import com.querydsl.jpa.impl.JPAQuery; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.file.FileDescription; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.Collection; import java.util.Optional; +import se.su.dsv.scipro.file.FileDescription; public class UrkundSubmissionRepositoryImpl implements UrkundSubmissionRepository { + private final Provider entityManagerProvider; @Inject @@ -21,9 +21,9 @@ public class UrkundSubmissionRepositoryImpl implements UrkundSubmissionRepositor @Override public Optional findByFile(final FileDescription file) { final UrkundSubmission urkundSubmission = new JPAQuery(entityManagerProvider.get()) - .from(QUrkundSubmission.urkundSubmission) - .where(QUrkundSubmission.urkundSubmission.document.fileDescription.eq(file)) - .fetchOne(); + .from(QUrkundSubmission.urkundSubmission) + .where(QUrkundSubmission.urkundSubmission.document.fileDescription.eq(file)) + .fetchOne(); return Optional.ofNullable(urkundSubmission); } @@ -33,8 +33,7 @@ public class UrkundSubmissionRepositoryImpl implements UrkundSubmissionRepositor final EntityManager em = entityManagerProvider.get(); if (em.contains(submission)) { return em.merge(submission); - } - else { + } else { em.persist(submission); return submission; } @@ -43,11 +42,14 @@ public class UrkundSubmissionRepositoryImpl implements UrkundSubmissionRepositor @Override public Collection findNotDone() { return new JPAQuery(entityManagerProvider.get()) - .from(QUrkundSubmission.urkundSubmission) - .where(QUrkundSubmission.urkundSubmission.state.in( - UrkundSubmission.State.SUBMITTED, - UrkundSubmission.State.ACCEPTED)) - .fetch(); + .from(QUrkundSubmission.urkundSubmission) + .where( + QUrkundSubmission.urkundSubmission.state.in( + UrkundSubmission.State.SUBMITTED, + UrkundSubmission.State.ACCEPTED + ) + ) + .fetch(); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/Util.java b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/Util.java index 61b4cdf875..dff176e0a9 100644 --- a/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/Util.java +++ b/core/src/main/java/se/su/dsv/scipro/plagiarism/urkund/Util.java @@ -8,12 +8,18 @@ final class Util { static UrkundSubmission.State getState(final StatusInfo.State state) { switch (state) { - case Submitted: return UrkundSubmission.State.SUBMITTED; - case Rejected: return UrkundSubmission.State.REJECTED; - case Accepted: return UrkundSubmission.State.ACCEPTED; - case Analyzed: return UrkundSubmission.State.ANALYZED; - case Error: return UrkundSubmission.State.ERROR; - default: throw new Error(); + case Submitted: + return UrkundSubmission.State.SUBMITTED; + case Rejected: + return UrkundSubmission.State.REJECTED; + case Accepted: + return UrkundSubmission.State.ACCEPTED; + case Analyzed: + return UrkundSubmission.State.ANALYZED; + case Error: + return UrkundSubmission.State.ERROR; + default: + throw new Error(); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/profiles/CurrentProfile.java b/core/src/main/java/se/su/dsv/scipro/profiles/CurrentProfile.java index 6bf6f2bd19..f98759d46d 100755 --- a/core/src/main/java/se/su/dsv/scipro/profiles/CurrentProfile.java +++ b/core/src/main/java/se/su/dsv/scipro/profiles/CurrentProfile.java @@ -9,12 +9,12 @@ public class CurrentProfile { } public Profiles getCurrentProfile() { - if (currentProfileString.equalsIgnoreCase("DEV")){ + if (currentProfileString.equalsIgnoreCase("DEV")) { return Profiles.DEV; - } else if (currentProfileString.equalsIgnoreCase("PROD")){ + } else if (currentProfileString.equalsIgnoreCase("PROD")) { return Profiles.PROD; } else { return Profiles.TEST; } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/profiles/Profiles.java b/core/src/main/java/se/su/dsv/scipro/profiles/Profiles.java index e8d4b5cd41..df69907cd9 100755 --- a/core/src/main/java/se/su/dsv/scipro/profiles/Profiles.java +++ b/core/src/main/java/se/su/dsv/scipro/profiles/Profiles.java @@ -3,5 +3,5 @@ package se.su.dsv.scipro.profiles; public enum Profiles { DEV, PROD, - TEST -} \ No newline at end of file + TEST, +} diff --git a/core/src/main/java/se/su/dsv/scipro/project/Author.java b/core/src/main/java/se/su/dsv/scipro/project/Author.java index 96ec7ce284..73eff81e1d 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/Author.java +++ b/core/src/main/java/se/su/dsv/scipro/project/Author.java @@ -11,14 +11,14 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Objects; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "project_user") public class Author { + // ---------------------------------------------------------------------------------- // Embedded JPA-mapping // ---------------------------------------------------------------------------------- @@ -52,7 +52,11 @@ public class Author { @Basic(optional = false) // Have to specify the column definition to get the default value behaviour // in tests to match the production definition from the migration script - @Column(name = "subscribed_to_final_seminar_notifications", nullable = false, columnDefinition = "BOOLEAN DEFAULT FALSE") + @Column( + name = "subscribed_to_final_seminar_notifications", + nullable = false, + columnDefinition = "BOOLEAN DEFAULT FALSE" + ) private boolean subscribedToFinalSeminarNotifications; // ---------------------------------------------------------------------------------- @@ -117,6 +121,7 @@ public class Author { // ---------------------------------------------------------------------------------- @Embeddable public static class AuthorPK implements Serializable { + private Long projectId; private Long userId; @@ -127,7 +132,7 @@ public class Author { return false; } AuthorPK authorPK = (AuthorPK) o; - return Objects.equals(projectId, authorPK.projectId) && Objects.equals(userId, authorPK.userId); + return (Objects.equals(projectId, authorPK.projectId) && Objects.equals(userId, authorPK.userId)); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/project/ExternalOrganization.java b/core/src/main/java/se/su/dsv/scipro/project/ExternalOrganization.java index fd48cff408..d229c75aa0 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ExternalOrganization.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ExternalOrganization.java @@ -7,6 +7,7 @@ import java.util.Objects; @Embeddable public class ExternalOrganization implements Serializable { + @Basic private String name; @@ -23,8 +24,7 @@ public class ExternalOrganization implements Serializable { if (o == this) return true; if (!(o instanceof ExternalOrganization)) return false; final ExternalOrganization other = (ExternalOrganization) o; - return other.canEqual(this) - && Objects.equals(this.getName(), other.getName()); + return (other.canEqual(this) && Objects.equals(this.getName(), other.getName())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/project/Project.java b/core/src/main/java/se/su/dsv/scipro/project/Project.java index 569d1da4a7..82f8400f9c 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/Project.java +++ b/core/src/main/java/se/su/dsv/scipro/project/Project.java @@ -23,17 +23,6 @@ import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; import jakarta.persistence.Table; - -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.reusable.SciProUtilities; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.ProjectModule; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.ResearchArea; -import se.su.dsv.scipro.system.User; - import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; @@ -47,11 +36,21 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.reusable.SciProUtilities; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.ProjectModule; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.ResearchArea; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "project") @Cacheable(true) public class Project extends DomainObject { + public static final String NO_REVIEWER = "No reviewer"; public static final String NO_CO_SUPERVISOR = "No co-supervisor"; public static final int TITLE_MAX_LENGTH = 255; @@ -135,38 +134,46 @@ public class Project extends DomainObject { @ManyToOne(optional = false) @JoinColumn(name = "supervisor_id", referencedColumnName = "id") - @QueryInit({"unit"}) + @QueryInit({ "unit" }) private User headSupervisor; // ---------------------------------------------------------------------------------- // @ManyToMany JPA-mappings // ---------------------------------------------------------------------------------- @ManyToMany - @JoinTable(name = "project_user", - joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + @JoinTable( + name = "project_user", + joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") + ) private Set projectParticipants = new TreeSet<>(new User.ByNameComparator()); @ManyToMany - @JoinTable(name = "project_reviewer", - joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + @JoinTable( + name = "project_reviewer", + joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") + ) private Set reviewers = new TreeSet<>(new User.ByNameComparator()); @ManyToMany - @JoinTable(name = "project_cosupervisor", - joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) + @JoinTable( + name = "project_cosupervisor", + joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") + ) private Set coSupervisors = new TreeSet<>(new User.ByNameComparator()); // ---------------------------------------------------------------------------------- // JPA-mappings of other tables referencing to this table "project" // ---------------------------------------------------------------------------------- @ElementCollection(fetch = FetchType.LAZY) - @CollectionTable(name = "project_user_note", - joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id")) + @CollectionTable( + name = "project_user_note", + joinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id") + ) @Column(name = "note") - @SuppressWarnings("JpaDataSourceORMInspection") // false warning from IntelliJ for the @MapKeyJoinColumn + @SuppressWarnings("JpaDataSourceORMInspection") // false warning from IntelliJ for the @MapKeyJoinColumn @MapKeyJoinColumn(name = "user_id") private Map userNotes = new HashMap<>(); @@ -270,13 +277,11 @@ public class Project extends DomainObject { } public Date getStateOfMindDate() { - return stateOfMindDate == null ? null - : new Date(stateOfMindDate.getTime()); + return stateOfMindDate == null ? null : new Date(stateOfMindDate.getTime()); } public void setStateOfMindDate(Date stateOfMindDate) { - this.stateOfMindDate = stateOfMindDate == null ? null - : new Date(stateOfMindDate.getTime()); + this.stateOfMindDate = stateOfMindDate == null ? null : new Date(stateOfMindDate.getTime()); } public Integer getIdentifier() { @@ -368,8 +373,7 @@ public class Project extends DomainObject { if (o == this) return true; if (!(o instanceof Project)) return false; final Project other = (Project) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } @Override @@ -379,10 +383,21 @@ public class Project extends DomainObject { @Override public String toString() { - return "Project(id=" + this.getId() + ", identifier=" + this.getIdentifier() + - ", title=" + this.getTitle() + ", projectParticipants=" + this.getProjectParticipants() + - ", headSupervisor=" + this.getHeadSupervisor() + ", projectType=" + - this.getProjectType() + ")"; + return ( + "Project(id=" + + this.getId() + + ", identifier=" + + this.getIdentifier() + + ", title=" + + this.getTitle() + + ", projectParticipants=" + + this.getProjectParticipants() + + ", headSupervisor=" + + this.getHeadSupervisor() + + ", projectType=" + + this.getProjectType() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -457,10 +472,7 @@ public class Project extends DomainObject { } public String getAuthorNames() { - return getProjectParticipants() - .stream() - .map(User::getFullName) - .collect(Collectors.joining(", ")); + return getProjectParticipants().stream().map(User::getFullName).collect(Collectors.joining(", ")); } public boolean hasExternalOrganization() { @@ -534,6 +546,7 @@ public class Project extends DomainObject { // ---------------------------------------------------------------------------------- private static class Builder implements ITitle, IProjectType, IStartDate, IBuild { + private final Project instance = new Project(); @Override diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectActivatedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectActivatedEvent.java index 22b17192e8..cad61f73c4 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectActivatedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectActivatedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.project; public final class ProjectActivatedEvent { + private final Project project; public ProjectActivatedEvent(final Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectCompletedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectCompletedEvent.java index 57a24a798d..5ae7835173 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectCompletedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectCompletedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.project; public final class ProjectCompletedEvent { + private final Project project; public ProjectCompletedEvent(final Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectCreatedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectCreatedEvent.java index 5b3935f038..8020bfcfe0 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectCreatedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectCreatedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.project; public final class ProjectCreatedEvent { + private final Project project; public ProjectCreatedEvent(Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectDeactivatedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectDeactivatedEvent.java index 56c126077f..bab0ce16f4 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectDeactivatedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectDeactivatedEvent.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.project; public final class ProjectDeactivatedEvent { + private final Project project; public ProjectDeactivatedEvent(final Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectPeopleStatisticsServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectPeopleStatisticsServiceImpl.java index ada1db066b..562973491f 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectPeopleStatisticsServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectPeopleStatisticsServiceImpl.java @@ -1,13 +1,14 @@ package se.su.dsv.scipro.project; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.QUser; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.QUser; -public class ProjectPeopleStatisticsServiceImpl extends AbstractServiceImpl implements ProjectPeopleStatisticsService { +public class ProjectPeopleStatisticsServiceImpl + extends AbstractServiceImpl + implements ProjectPeopleStatisticsService { @Inject public ProjectPeopleStatisticsServiceImpl(Provider em) { @@ -17,36 +18,48 @@ public class ProjectPeopleStatisticsServiceImpl extends AbstractServiceImpl, QueryDslPredicateExecutor { List findMultipleAuthors(Collection projects); @@ -15,4 +14,4 @@ public interface ProjectRepo extends JpaRepository, QueryDslPredi String getUserNoteForProject(Project project, User user); void setUserNoteForProject(Project project, User user, String note); -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectRepoImpl.java index 8211412568..33b7e4c7c4 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectRepoImpl.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.project; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.GenericRepo; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; +import jakarta.transaction.Transactional; import java.util.Collection; import java.util.List; +import se.su.dsv.scipro.system.GenericRepo; +import se.su.dsv.scipro.system.User; public class ProjectRepoImpl extends GenericRepo implements ProjectRepo { + @Inject public ProjectRepoImpl(Provider em) { super(em, Project.class, QProject.project); @@ -19,7 +19,9 @@ public class ProjectRepoImpl extends GenericRepo implements Proje @Override public List findMultipleAuthors(Collection projects) { - TypedQuery query = em().createQuery(""" + TypedQuery query = em() + .createQuery( + """ from User u where u.id in ( select participant.id from Project project @@ -27,7 +29,9 @@ public class ProjectRepoImpl extends GenericRepo implements Proje where project in :projects group by participant.id having count(participant.id) > 1) - """, User.class); + """, + User.class + ); query.setParameter("projects", projects); return query.getResultList(); } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectService.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectService.java index 8c91ed6f43..230df2db80 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectService.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectService.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.project; -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.system.*; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.system.*; -public interface ProjectService extends GenericService, FilteredService { +public interface ProjectService + extends GenericService, FilteredService { Long countAuthors(Filter params); List getProjectsByUser(User user); @@ -39,6 +39,7 @@ public interface ProjectService extends GenericService, FilteredS Project complete(Project project); class Filter implements Serializable { + private Collection projectTypes; private String titleContains; private User supervisor; @@ -171,21 +172,23 @@ public interface ProjectService extends GenericService, FilteredS if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getProjectTypes(), other.getProjectTypes()) - && Objects.equals(this.getTitleContains(), other.getTitleContains()) - && Objects.equals(this.getSupervisor(), other.getSupervisor()) - && Objects.equals(this.getReviewer(), other.getReviewer()) - && this.isFilterSupervisor() == other.isFilterSupervisor() - && Objects.equals(this.getRoles(), other.getRoles()) - && Objects.equals(this.getAuthorUser(), other.getAuthorUser()) - && Objects.equals(this.getCreatedAfter(), other.getCreatedAfter()) - && Objects.equals(this.getCreatedBefore(), other.getCreatedBefore()) - && Objects.equals(this.getStatuses(), other.getStatuses()) - && this.isFilterExternal() == other.isFilterExternal() - && this.isNoReviewer() == other.isNoReviewer() - && Objects.equals(this.getUnit(), other.getUnit()) - && Objects.equals(this.getRedStateTime(), other.getRedStateTime()); + return ( + other.canEqual(this) && + Objects.equals(this.getProjectTypes(), other.getProjectTypes()) && + Objects.equals(this.getTitleContains(), other.getTitleContains()) && + Objects.equals(this.getSupervisor(), other.getSupervisor()) && + Objects.equals(this.getReviewer(), other.getReviewer()) && + this.isFilterSupervisor() == other.isFilterSupervisor() && + Objects.equals(this.getRoles(), other.getRoles()) && + Objects.equals(this.getAuthorUser(), other.getAuthorUser()) && + Objects.equals(this.getCreatedAfter(), other.getCreatedAfter()) && + Objects.equals(this.getCreatedBefore(), other.getCreatedBefore()) && + Objects.equals(this.getStatuses(), other.getStatuses()) && + this.isFilterExternal() == other.isFilterExternal() && + this.isNoReviewer() == other.isNoReviewer() && + Objects.equals(this.getUnit(), other.getUnit()) && + Objects.equals(this.getRedStateTime(), other.getRedStateTime()) + ); } protected boolean canEqual(final Object other) { @@ -194,25 +197,57 @@ public interface ProjectService extends GenericService, FilteredS @Override public int hashCode() { - return Objects.hash(this.getProjectTypes(), - this.getTitleContains(), - this.getSupervisor(), - this.getReviewer(), - this.isFilterSupervisor(), - this.getRoles(), - this.getAuthorUser(), - this.getCreatedAfter(), - this.getCreatedBefore(), - this.getStatuses(), - this.isFilterExternal(), - this.isNoReviewer(), - this.getUnit(), - this.getRedStateTime()); + return Objects.hash( + this.getProjectTypes(), + this.getTitleContains(), + this.getSupervisor(), + this.getReviewer(), + this.isFilterSupervisor(), + this.getRoles(), + this.getAuthorUser(), + this.getCreatedAfter(), + this.getCreatedBefore(), + this.getStatuses(), + this.isFilterExternal(), + this.isNoReviewer(), + this.getUnit(), + this.getRedStateTime() + ); } @Override public String toString() { - return "ProjectService.Filter(projectTypes=" + this.getProjectTypes() + ", titleContains=" + this.getTitleContains() + ", supervisor=" + this.getSupervisor() + ", reviewer=" + this.getReviewer() + ", filterSupervisor=" + this.isFilterSupervisor() + ", roles=" + this.getRoles() + ", authorUser=" + this.getAuthorUser() + ", createdAfter=" + this.getCreatedAfter() + ", createdBefore=" + this.getCreatedBefore() + ", statuses=" + this.getStatuses() + ", filterExternal=" + this.isFilterExternal() + ", noReviewer=" + this.isNoReviewer() + ", unit=" + this.getUnit() + ", redStateTime=" + this.getRedStateTime() + ")"; + return ( + "ProjectService.Filter(projectTypes=" + + this.getProjectTypes() + + ", titleContains=" + + this.getTitleContains() + + ", supervisor=" + + this.getSupervisor() + + ", reviewer=" + + this.getReviewer() + + ", filterSupervisor=" + + this.isFilterSupervisor() + + ", roles=" + + this.getRoles() + + ", authorUser=" + + this.getAuthorUser() + + ", createdAfter=" + + this.getCreatedAfter() + + ", createdBefore=" + + this.getCreatedBefore() + + ", statuses=" + + this.getStatuses() + + ", filterExternal=" + + this.isFilterExternal() + + ", noReviewer=" + + this.isNoReviewer() + + ", unit=" + + this.getUnit() + + ", redStateTime=" + + this.getRedStateTime() + + ")" + ); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectServiceImpl.java index e52cae2397..b6da36a842 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectServiceImpl.java @@ -1,28 +1,29 @@ package se.su.dsv.scipro.project; import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.system.Pageable; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.*; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.reusable.SciProUtilities; import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.QUser; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.*; - -public class ProjectServiceImpl extends AbstractServiceImpl implements ProjectService, ProjectNoteService { +public class ProjectServiceImpl + extends AbstractServiceImpl + implements ProjectService, ProjectNoteService { public static final int MIN_TITLE_LENGTH = 3; private final ProjectRepo projectRepo; @@ -55,10 +56,10 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple return (long) 0; } return from(QProject.project) - .where(toPredicate(params)) - .join(QProject.project.projectParticipants, QUser.user) - .select(QUser.user.count()) - .fetchFirst(); + .where(toPredicate(params)) + .join(QProject.project.projectParticipants, QUser.user) + .select(QUser.user.count()) + .fetchFirst(); } @Override @@ -88,7 +89,10 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple @Override public boolean hasSupervisingRole(Project project, User user) { - return Member.Type.SUPERVISOR == getMemberType(project, user) || Member.Type.CO_SUPERVISOR == getMemberType(project, user); + return ( + Member.Type.SUPERVISOR == getMemberType(project, user) || + Member.Type.CO_SUPERVISOR == getMemberType(project, user) + ); } @Override @@ -145,8 +149,7 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple public Project toggleActiveStatus(Project project, boolean state) { if (state) { return activate(project); - } - else { + } else { return deactivate(project); } } @@ -273,10 +276,10 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple private static Predicate hasAnyRole(User employee, Collection roles) { BooleanBuilder bb = new BooleanBuilder(); if (roles != null && !roles.isEmpty() && employee != null) { - for (ProjectTeamMemberRoles role : roles){ - if (role == ProjectTeamMemberRoles.CO_SUPERVISOR){ + for (ProjectTeamMemberRoles role : roles) { + if (role == ProjectTeamMemberRoles.CO_SUPERVISOR) { bb.or(QProject.project.coSupervisors.any().eq(employee)); - } else if (role == ProjectTeamMemberRoles.REVIEWER){ + } else if (role == ProjectTeamMemberRoles.REVIEWER) { bb.or(QProject.project.reviewers.any().eq(employee)); } } @@ -318,9 +321,10 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple private BooleanExpression hasBeenRedForTime(Integer redStateTime) { if (redStateTime != null) { - final Instant now = clock.instant() - .minus(Duration.ofDays(redStateTime)); - return QProject.project.stateOfMindDate.before(Date.from(now)).and(QProject.project.stateOfMind.eq(StateOfMind.NEEDHELP)); + final Instant now = clock.instant().minus(Duration.ofDays(redStateTime)); + return QProject.project.stateOfMindDate + .before(Date.from(now)) + .and(QProject.project.stateOfMind.eq(StateOfMind.NEEDHELP)); } return null; } @@ -352,5 +356,4 @@ public class ProjectServiceImpl extends AbstractServiceImpl imple private static BooleanExpression supervisorUnitIs(Unit unit) { return QProject.project.headSupervisor.unit.eq(unit); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectStatus.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectStatus.java index 912e00b211..644a5110ee 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectStatus.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectStatus.java @@ -1,22 +1,22 @@ package se.su.dsv.scipro.project; public enum ProjectStatus { - ACTIVE { - @Override - public String toString() { - return "Active"; - } - }, - INACTIVE { - @Override - public String toString() { - return "Inactive"; - } - }, - COMPLETED { - @Override - public String toString() { - return "Completed"; - } - } + ACTIVE { + @Override + public String toString() { + return "Active"; + } + }, + INACTIVE { + @Override + public String toString() { + return "Inactive"; + } + }, + COMPLETED { + @Override + public String toString() { + return "Completed"; + } + }, } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ProjectTeamMemberRoles.java b/core/src/main/java/se/su/dsv/scipro/project/ProjectTeamMemberRoles.java index ae1a4410bf..1a4152dbbc 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/ProjectTeamMemberRoles.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ProjectTeamMemberRoles.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.project; public enum ProjectTeamMemberRoles { - - REVIEWER { - @Override - public String toString() { - return "Reviewer"; - } - }, - CO_SUPERVISOR { - @Override - public String toString() { - return "Co-Supervisor"; - } - } + REVIEWER { + @Override + public String toString() { + return "Reviewer"; + } + }, + CO_SUPERVISOR { + @Override + public String toString() { + return "Co-Supervisor"; + } + }, } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ReflectionStatus.java b/core/src/main/java/se/su/dsv/scipro/project/ReflectionStatus.java index 92b94cd7b6..bcac6a09f0 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ReflectionStatus.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ReflectionStatus.java @@ -3,5 +3,5 @@ package se.su.dsv.scipro.project; public enum ReflectionStatus { NOT_SUBMITTED, SUBMITTED, - IMPROVEMENTS_NEEDED + IMPROVEMENTS_NEEDED, } diff --git a/core/src/main/java/se/su/dsv/scipro/project/ReviewerAssignedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ReviewerAssignedEvent.java index 5b71c9f662..2e7c3994fc 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ReviewerAssignedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ReviewerAssignedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.project; import se.su.dsv.scipro.system.User; public final class ReviewerAssignedEvent { + private final Project project; private final User reviewer; diff --git a/core/src/main/java/se/su/dsv/scipro/project/ReviewerUnassignedEvent.java b/core/src/main/java/se/su/dsv/scipro/project/ReviewerUnassignedEvent.java index 5ff2faeabc..787040e4cb 100644 --- a/core/src/main/java/se/su/dsv/scipro/project/ReviewerUnassignedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/project/ReviewerUnassignedEvent.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.project; -public record ReviewerUnassignedEvent(Project project) { -} +public record ReviewerUnassignedEvent(Project project) {} diff --git a/core/src/main/java/se/su/dsv/scipro/project/StateOfMind.java b/core/src/main/java/se/su/dsv/scipro/project/StateOfMind.java index 4e8bc602ee..3a9d3f8774 100755 --- a/core/src/main/java/se/su/dsv/scipro/project/StateOfMind.java +++ b/core/src/main/java/se/su/dsv/scipro/project/StateOfMind.java @@ -1,10 +1,9 @@ /** - * + * */ package se.su.dsv.scipro.project; public enum StateOfMind { - NEEDHELP("Help needed to proceed"), NEUTRAL("No imminent help needed"), FINE("Work proceeds as planned"); @@ -24,8 +23,7 @@ public enum StateOfMind { } @Override - public String toString(){ + public String toString() { return status; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartner.java b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartner.java index 643956fe8e..eb77b656ad 100755 --- a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartner.java +++ b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartner.java @@ -1,7 +1,5 @@ package se.su.dsv.scipro.projectpartner; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.Column; @@ -13,109 +11,120 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - +import java.util.Objects; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; @Entity -@Table(name="project_partner") +@Table(name = "project_partner") @Cacheable(true) public class ProjectPartner extends DomainObject { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @ManyToOne(optional=false) - private User user; - @ManyToOne(optional = false) - @JoinColumn(name = "project_type_id") - private ProjectType projectType; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @ManyToOne(optional = false) - @JoinColumn(name = "application_period_id") - private ApplicationPeriod applicationPeriod; + @ManyToOne(optional = false) + private User user; - @Lob - @Column(name = "info_text", nullable=false) - private String infotext; + @ManyToOne(optional = false) + @JoinColumn(name = "project_type_id") + private ProjectType projectType; - @Basic(optional = false) - @Column(name = "active", nullable = false) - private boolean active = true; + @ManyToOne(optional = false) + @JoinColumn(name = "application_period_id") + private ApplicationPeriod applicationPeriod; - public ProjectPartner(User user){ - this.user = user; - } + @Lob + @Column(name = "info_text", nullable = false) + private String infotext; - public ProjectPartner() { - } + @Basic(optional = false) + @Column(name = "active", nullable = false) + private boolean active = true; - @Override - public Long getId() { - return this.id; - } + public ProjectPartner(User user) { + this.user = user; + } - public User getUser() { - return this.user; - } + public ProjectPartner() {} - public ProjectType getProjectType() { - return this.projectType; - } + @Override + public Long getId() { + return this.id; + } - public ApplicationPeriod getApplicationPeriod() { - return this.applicationPeriod; - } + public User getUser() { + return this.user; + } - public String getInfotext() { - return this.infotext; - } + public ProjectType getProjectType() { + return this.projectType; + } - public void setId(Long id) { - this.id = id; - } + public ApplicationPeriod getApplicationPeriod() { + return this.applicationPeriod; + } - public void setUser(User user) { - this.user = user; - } + public String getInfotext() { + return this.infotext; + } - public void setProjectType(ProjectType projectType) { - this.projectType = projectType; - } + public void setId(Long id) { + this.id = id; + } - public void setApplicationPeriod(ApplicationPeriod applicationPeriod) { - this.applicationPeriod = applicationPeriod; - } + public void setUser(User user) { + this.user = user; + } - public void setInfotext(String infotext) { - this.infotext = infotext; - } + public void setProjectType(ProjectType projectType) { + this.projectType = projectType; + } - @Override - public String toString() { - return "ProjectPartner(id=" + this.getId() + ", user=" + this.getUser() + ", projectType=" + this.getProjectType() + ", applicationPeriod=" + this.getApplicationPeriod() + ", infotext=" + this.getInfotext() + ")"; - } + public void setApplicationPeriod(ApplicationPeriod applicationPeriod) { + this.applicationPeriod = applicationPeriod; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof ProjectPartner)) return false; - final ProjectPartner other = (ProjectPartner) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); - } + public void setInfotext(String infotext) { + this.infotext = infotext; + } - protected boolean canEqual(final Object other) { - return other instanceof ProjectPartner; - } + @Override + public String toString() { + return ( + "ProjectPartner(id=" + + this.getId() + + ", user=" + + this.getUser() + + ", projectType=" + + this.getProjectType() + + ", applicationPeriod=" + + this.getApplicationPeriod() + + ", infotext=" + + this.getInfotext() + + ")" + ); + } - @Override - public int hashCode() { - return Objects.hashCode(this.getId()); - } + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof ProjectPartner)) return false; + final ProjectPartner other = (ProjectPartner) o; + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); + } + + protected boolean canEqual(final Object other) { + return other instanceof ProjectPartner; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.getId()); + } public void setActive(boolean active) { this.active = active; diff --git a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerRepositoryImpl.java index a437f162d5..fc657c02c6 100644 --- a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerRepositoryImpl.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.projectpartner; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.Collection; +import se.su.dsv.scipro.system.AbstractRepository; public class ProjectPartnerRepositoryImpl extends AbstractRepository implements ProjectPartnerRepository { + @Inject public ProjectPartnerRepositoryImpl(Provider em) { super(em); @@ -16,9 +16,7 @@ public class ProjectPartnerRepositoryImpl extends AbstractRepository implements @Override public Collection getActive() { - return from(QProjectPartner.projectPartner) - .where(QProjectPartner.projectPartner.active.isTrue()) - .fetch(); + return from(QProjectPartner.projectPartner).where(QProjectPartner.projectPartner.active.isTrue()).fetch(); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerService.java b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerService.java index ce33acbc94..a3db5c3836 100644 --- a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerService.java +++ b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerService.java @@ -1,15 +1,23 @@ package se.su.dsv.scipro.projectpartner; -import se.su.dsv.scipro.system.Pageable; +import java.util.List; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; -import java.util.List; - public interface ProjectPartnerService extends GenericService { - List getProjectPartnerInSpan(int days, final ApplicationPeriod applicationPeriod, final ProjectType projectType, Pageable pageable); - long countProjectPartnerInSpan(final int days, final ApplicationPeriod applicationPeriod, final ProjectType projectType); + List getProjectPartnerInSpan( + int days, + final ApplicationPeriod applicationPeriod, + final ProjectType projectType, + Pageable pageable + ); + long countProjectPartnerInSpan( + final int days, + final ApplicationPeriod applicationPeriod, + final ProjectType projectType + ); List getPartnersWithoutIdea(ApplicationPeriod applicationPeriod); void remove(ProjectPartner ad); diff --git a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImpl.java index 5af5e3a0a7..21afefa5d8 100644 --- a/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImpl.java @@ -1,23 +1,24 @@ package se.su.dsv.scipro.projectpartner; -import jakarta.transaction.Transactional; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.jpa.JPAExpressions; -import se.su.dsv.scipro.system.Pageable; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.time.Duration; +import java.time.Instant; +import java.util.*; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.match.QIdea; import se.su.dsv.scipro.match.QIdeaParticipation; import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.Duration; -import java.time.Instant; -import java.util.*; - -public class ProjectPartnerServiceImpl extends AbstractServiceImpl implements ProjectPartnerService { +public class ProjectPartnerServiceImpl + extends AbstractServiceImpl + implements ProjectPartnerService { @Inject public ProjectPartnerServiceImpl(Provider em) { @@ -25,44 +26,62 @@ public class ProjectPartnerServiceImpl extends AbstractServiceImpl getProjectPartnerInSpan(int days, final ApplicationPeriod applicationPeriod, final ProjectType projectType, Pageable pageable) { + public List getProjectPartnerInSpan( + int days, + final ApplicationPeriod applicationPeriod, + final ProjectType projectType, + Pageable pageable + ) { if (days == 0) { return findAll(QProjectPartner.projectPartner.projectType.eq(projectType), pageable); } // TODO pull up as parameter to remove dependency on clock (Instant.now) Date date = Date.from(Instant.now().minus(Duration.ofDays(days))); - return findAll(Expressions.allOf( - QProjectPartner.projectPartner.dateCreated.after(date), - QProjectPartner.projectPartner.projectType.eq(projectType), - QProjectPartner.projectPartner.applicationPeriod.eq(applicationPeriod), - QProjectPartner.projectPartner.active.isTrue()), - pageable); + return findAll( + Expressions.allOf( + QProjectPartner.projectPartner.dateCreated.after(date), + QProjectPartner.projectPartner.projectType.eq(projectType), + QProjectPartner.projectPartner.applicationPeriod.eq(applicationPeriod), + QProjectPartner.projectPartner.active.isTrue() + ), + pageable + ); } @Override - public long countProjectPartnerInSpan(int days, final ApplicationPeriod applicationPeriod, final ProjectType projectType) { + public long countProjectPartnerInSpan( + int days, + final ApplicationPeriod applicationPeriod, + final ProjectType projectType + ) { if (days == 0) { return count(QProjectPartner.projectPartner.projectType.eq(projectType)); } // TODO pull up as parameter to remove dependency on clock (Instant.now) Date date = Date.from(Instant.now().minus(Duration.ofDays(days))); - return count(Expressions.allOf( + return count( + Expressions.allOf( QProjectPartner.projectPartner.dateCreated.after(date), QProjectPartner.projectPartner.projectType.eq(projectType), QProjectPartner.projectPartner.applicationPeriod.eq(applicationPeriod), - QProjectPartner.projectPartner.active.isTrue())); + QProjectPartner.projectPartner.active.isTrue() + ) + ); } @Override public List getPartnersWithoutIdea(final ApplicationPeriod applicationPeriod) { - return findAll(Expressions.allOf( + return findAll( + Expressions.allOf( QProjectPartner.projectPartner.user.notIn( - JPAExpressions.select(QIdeaParticipation.ideaParticipation.user) - .from(QIdea.idea) - .join(QIdea.idea.ideaParticipations, QIdeaParticipation.ideaParticipation) - .where(QIdea.idea.applicationPeriod.eq(applicationPeriod))), + JPAExpressions.select(QIdeaParticipation.ideaParticipation.user) + .from(QIdea.idea) + .join(QIdea.idea.ideaParticipations, QIdeaParticipation.ideaParticipation) + .where(QIdea.idea.applicationPeriod.eq(applicationPeriod)) + ), QProjectPartner.projectPartner.applicationPeriod.eq(applicationPeriod) - )); + ) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/projectpartner/RemoveFulfilledPartnerAdsWorker.java b/core/src/main/java/se/su/dsv/scipro/projectpartner/RemoveFulfilledPartnerAdsWorker.java index 9e7d8069d6..4e3e38d937 100644 --- a/core/src/main/java/se/su/dsv/scipro/projectpartner/RemoveFulfilledPartnerAdsWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/projectpartner/RemoveFulfilledPartnerAdsWorker.java @@ -1,23 +1,20 @@ package se.su.dsv.scipro.projectpartner; -import se.su.dsv.scipro.match.Idea; -import se.su.dsv.scipro.match.IdeaService; -import se.su.dsv.scipro.workerthreads.AbstractWorker; - import jakarta.inject.Inject; import java.util.Collection; import java.util.List; import java.util.Set; +import se.su.dsv.scipro.match.Idea; +import se.su.dsv.scipro.match.IdeaService; +import se.su.dsv.scipro.workerthreads.AbstractWorker; public class RemoveFulfilledPartnerAdsWorker extends AbstractWorker { + private final IdeaService ideaService; private final ProjectPartnerRepository projectPartnerRepository; @Inject - public RemoveFulfilledPartnerAdsWorker( - IdeaService ideaService, - ProjectPartnerRepository projectPartnerRepository) - { + public RemoveFulfilledPartnerAdsWorker(IdeaService ideaService, ProjectPartnerRepository projectPartnerRepository) { this.ideaService = ideaService; this.projectPartnerRepository = projectPartnerRepository; } diff --git a/core/src/main/java/se/su/dsv/scipro/reflection/Reflection.java b/core/src/main/java/se/su/dsv/scipro/reflection/Reflection.java index 898d961a2c..965c5b3aaf 100644 --- a/core/src/main/java/se/su/dsv/scipro/reflection/Reflection.java +++ b/core/src/main/java/se/su/dsv/scipro/reflection/Reflection.java @@ -5,7 +5,9 @@ public sealed interface Reflection { record NotSubmitted() implements Reflection { @Override - public boolean isSubmittable() { return true; } + public boolean isSubmittable() { + return true; + } } record Submitted(String reflection) implements Reflection { @@ -17,6 +19,8 @@ public sealed interface Reflection { record ImprovementsNeeded(String oldReflection, String commentBySupervisor) implements Reflection { @Override - public boolean isSubmittable() { return true; } + public boolean isSubmittable() { + return true; + } } } diff --git a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsRequestedEvent.java b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsRequestedEvent.java index 07d8811f99..bb2725cf31 100644 --- a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsRequestedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsRequestedEvent.java @@ -3,5 +3,4 @@ package se.su.dsv.scipro.reflection; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -public record ReflectionImprovementsRequestedEvent(Project project, User author, String supervisorComment) { -} +public record ReflectionImprovementsRequestedEvent(Project project, User author, String supervisorComment) {} diff --git a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsSubmittedEvent.java b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsSubmittedEvent.java index ce43d5eed4..ab4e11b853 100644 --- a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsSubmittedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionImprovementsSubmittedEvent.java @@ -6,5 +6,4 @@ import se.su.dsv.scipro.system.User; /** * This event may be triggered by the supervisor if they edit the reflection after requesting improvements. */ -public record ReflectionImprovementsSubmittedEvent(Project project, User author, String reflection) { -} +public record ReflectionImprovementsSubmittedEvent(Project project, User author, String reflection) {} diff --git a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionServiceImpl.java index 73d934ca32..66805248f9 100644 --- a/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reflection/ReflectionServiceImpl.java @@ -1,7 +1,9 @@ package se.su.dsv.scipro.reflection; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.Optional; import se.su.dsv.scipro.finalseminar.AuthorRepository; import se.su.dsv.scipro.finalseminar.FinalSeminarService; import se.su.dsv.scipro.project.Author; @@ -9,21 +11,18 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ReflectionStatus; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - -import java.util.Optional; - public class ReflectionServiceImpl implements ReflectionService { + private final AuthorRepository authorRepository; private final FinalSeminarService finalSeminarService; private final EventBus eventBus; @Inject public ReflectionServiceImpl( - AuthorRepository authorRepository, - FinalSeminarService finalSeminarService, - EventBus eventBus) - { + AuthorRepository authorRepository, + FinalSeminarService finalSeminarService, + EventBus eventBus + ) { this.authorRepository = authorRepository; this.finalSeminarService = finalSeminarService; this.eventBus = eventBus; @@ -48,47 +47,49 @@ public class ReflectionServiceImpl implements ReflectionService { @Override @Transactional public void submitReflection(Project project, User user, String reflection) { - authorRepository.findByProjectAndUser(project, user) - .ifPresent(author -> { - if (author.getReflectionStatus() == ReflectionStatus.IMPROVEMENTS_NEEDED) { - eventBus.post(new ReflectionImprovementsSubmittedEvent(project, user, reflection)); - } - author.setReflection(reflection); - author.setReflectionStatus(ReflectionStatus.SUBMITTED); - }); + authorRepository + .findByProjectAndUser(project, user) + .ifPresent(author -> { + if (author.getReflectionStatus() == ReflectionStatus.IMPROVEMENTS_NEEDED) { + eventBus.post(new ReflectionImprovementsSubmittedEvent(project, user, reflection)); + } + author.setReflection(reflection); + author.setReflectionStatus(ReflectionStatus.SUBMITTED); + }); } @Override public String getSubmittedReflection(Project project, User author) { - return authorRepository.findByProjectAndUser(project, author) - .map(Author::getReflection) - .orElse(null); + return authorRepository.findByProjectAndUser(project, author).map(Author::getReflection).orElse(null); } @Override @Transactional public void requestNewReflection(Project project, User user, String supervisorComment) { - authorRepository.findByProjectAndUser(project, user) - .ifPresent(author -> { - author.setReflectionStatus(ReflectionStatus.IMPROVEMENTS_NEEDED); - author.setReflectionSupervisorComment(supervisorComment); - }); + authorRepository + .findByProjectAndUser(project, user) + .ifPresent(author -> { + author.setReflectionStatus(ReflectionStatus.IMPROVEMENTS_NEEDED); + author.setReflectionSupervisorComment(supervisorComment); + }); eventBus.post(new ReflectionImprovementsRequestedEvent(project, user, supervisorComment)); } @Override public Reflection getReflection(Project project, User author) { - return authorRepository.findByProjectAndUser(project, author) - .map(this::toReflection) - .orElseGet(Reflection.NotSubmitted::new); + return authorRepository + .findByProjectAndUser(project, author) + .map(this::toReflection) + .orElseGet(Reflection.NotSubmitted::new); } private Reflection toReflection(Author author) { return switch (author.getReflectionStatus()) { case SUBMITTED -> new Reflection.Submitted(author.getReflection()); case IMPROVEMENTS_NEEDED -> new Reflection.ImprovementsNeeded( - author.getReflection(), - author.getReflectionSupervisorComment()); + author.getReflection(), + author.getReflectionSupervisorComment() + ); default -> new Reflection.NotSubmitted(); }; } diff --git a/core/src/main/java/se/su/dsv/scipro/report/AbstractCriterion.java b/core/src/main/java/se/su/dsv/scipro/report/AbstractCriterion.java index e9d80f2699..095b7d8ad7 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/AbstractCriterion.java +++ b/core/src/main/java/se/su/dsv/scipro/report/AbstractCriterion.java @@ -6,15 +6,15 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.Language; - import java.io.Serializable; import java.util.Comparator; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.Language; @MappedSuperclass public abstract class AbstractCriterion extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -37,8 +37,7 @@ public abstract class AbstractCriterion extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected AbstractCriterion() { - } + protected AbstractCriterion() {} protected AbstractCriterion(String title, String titleEn, int sortOrder) { this.title = title; @@ -74,12 +73,14 @@ public abstract class AbstractCriterion extends DomainObject { if (o == this) return true; if (!(o instanceof AbstractCriterion)) return false; final AbstractCriterion other = (AbstractCriterion) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getTitle(), other.getTitle()) - && Objects.equals(this.getTitleEn(), other.getTitleEn()) - && Objects.equals(this.getSortOrder(), other.getSortOrder()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getTitle(), other.getTitle()) && + Objects.equals(this.getTitleEn(), other.getTitleEn()) && + Objects.equals(this.getSortOrder(), other.getSortOrder()) + ); } @Override @@ -89,7 +90,17 @@ public abstract class AbstractCriterion extends DomainObject { @Override public String toString() { - return "AbstractCriterion(id=" + this.getId() + ", title=" + this.getTitle() + ", titleEn=" + this.getTitleEn() + ", sortOrder=" + this.getSortOrder() + ")"; + return ( + "AbstractCriterion(id=" + + this.getId() + + ", title=" + + this.getTitle() + + ", titleEn=" + + this.getTitleEn() + + ", sortOrder=" + + this.getSortOrder() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -107,6 +118,7 @@ public abstract class AbstractCriterion extends DomainObject { // Embedded class // ---------------------------------------------------------------------------------- public static class BySortOrderComparator implements Comparator, Serializable { + @Override public int compare(AbstractCriterion o1, AbstractCriterion o2) { return o1.sortOrder.compareTo(o2.sortOrder); diff --git a/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterion.java b/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterion.java index 81b55d0982..0a9d2e92b1 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterion.java +++ b/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterion.java @@ -8,6 +8,7 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class AbstractGradingCriterion extends AbstractCriterion { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -27,17 +28,20 @@ public abstract class AbstractGradingCriterion extends AbstractCriterion { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected AbstractGradingCriterion() { - - } + protected AbstractGradingCriterion() {} protected AbstractGradingCriterion(String title, String titleEn, int sortOrder, int pointsRequiredToPass) { super(title, titleEn, sortOrder); this.pointsRequiredToPass = pointsRequiredToPass; } - protected AbstractGradingCriterion(String title, String titleEn, Integer sortOrder, int pointsRequiredToPass, - Flag flag) { + protected AbstractGradingCriterion( + String title, + String titleEn, + Integer sortOrder, + int pointsRequiredToPass, + Flag flag + ) { this(title, titleEn, sortOrder, pointsRequiredToPass); this.flag = flag; } @@ -73,10 +77,12 @@ public abstract class AbstractGradingCriterion extends AbstractCriterion { if (o == this) return true; if (!(o instanceof AbstractGradingCriterion)) return false; final AbstractGradingCriterion other = (AbstractGradingCriterion) o; - return other.canEqual(this) - && super.equals(o) - && this.getPointsRequiredToPass() == other.getPointsRequiredToPass() - && this.isFx() == other.isFx(); + return ( + other.canEqual(this) && + super.equals(o) && + this.getPointsRequiredToPass() == other.getPointsRequiredToPass() && + this.isFx() == other.isFx() + ); } @Override @@ -90,8 +96,13 @@ public abstract class AbstractGradingCriterion extends AbstractCriterion { @Override public String toString() { - return "AbstractGradingCriterion(pointsRequiredToPass=" + this.getPointsRequiredToPass() + - ", fx=" + this.isFx() + ")"; + return ( + "AbstractGradingCriterion(pointsRequiredToPass=" + + this.getPointsRequiredToPass() + + ", fx=" + + this.isFx() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -125,6 +136,6 @@ public abstract class AbstractGradingCriterion extends AbstractCriterion { * their opposition and submitted report. It should only be used on * individual criteria. */ - OPPOSITION + OPPOSITION, } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterionPoint.java b/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterionPoint.java index 29e423d0f2..1f271173bd 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterionPoint.java +++ b/core/src/main/java/se/su/dsv/scipro/report/AbstractGradingCriterionPoint.java @@ -1,20 +1,20 @@ package se.su.dsv.scipro.report; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.Column; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.MappedSuperclass; +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; - import se.su.dsv.scipro.system.Language; @MappedSuperclass -public abstract class AbstractGradingCriterionPoint extends DomainObject - implements Comparable { +public abstract class AbstractGradingCriterionPoint + extends DomainObject + implements Comparable { + public static final int DESCRIPTION_LENGTH = 600; // ---------------------------------------------------------------------------------- @@ -39,8 +39,7 @@ public abstract class AbstractGradingCriterionPoint extends DomainObject // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public AbstractGradingCriterionPoint() { - } + public AbstractGradingCriterionPoint() {} // ---------------------------------------------------------------------------------- // Properties (Getters and Setters) @@ -86,22 +85,40 @@ public abstract class AbstractGradingCriterionPoint extends DomainObject if (o == this) return true; if (!(o instanceof AbstractGradingCriterionPoint)) return false; final AbstractGradingCriterionPoint other = (AbstractGradingCriterionPoint) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getPoint(), other.getPoint()) - && Objects.equals(this.getDescription(), other.getDescription()) - && Objects.equals(this.getDescriptionEn(), other.getDescriptionEn()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getPoint(), other.getPoint()) && + Objects.equals(this.getDescription(), other.getDescription()) && + Objects.equals(this.getDescriptionEn(), other.getDescriptionEn()) + ); } @Override public int hashCode() { - return Objects.hash(super.hashCode(), this.getId(), this.getPoint(), this.getDescription(), this.getDescriptionEn()); + return Objects.hash( + super.hashCode(), + this.getId(), + this.getPoint(), + this.getDescription(), + this.getDescriptionEn() + ); } @Override public String toString() { - return "AbstractGradingCriterionPoint(id=" + this.getId() + ", point=" + this.getPoint() + ", description=" + this.getDescription() + ", descriptionEn=" + this.getDescriptionEn() + ")"; + return ( + "AbstractGradingCriterionPoint(id=" + + this.getId() + + ", point=" + + this.getPoint() + + ", description=" + + this.getDescription() + + ", descriptionEn=" + + this.getDescriptionEn() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/report/AttachmentReport.java b/core/src/main/java/se/su/dsv/scipro/report/AttachmentReport.java index 53c135a971..2eaee3a6cf 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/AttachmentReport.java +++ b/core/src/main/java/se/su/dsv/scipro/report/AttachmentReport.java @@ -1,59 +1,55 @@ -package se.su.dsv.scipro.report; - -import se.su.dsv.scipro.file.FileReference; - -import jakarta.persistence.CascadeType; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.MappedSuperclass; -import jakarta.persistence.OneToOne; - -import java.util.Objects; - -@MappedSuperclass -public abstract class AttachmentReport extends Report { - - // ---------------------------------------------------------------------------------- - // JPA-mappings of foreign keys in table of children class (OppositionReport) - // referencing other tables. - // ---------------------------------------------------------------------------------- - @OneToOne(optional = true, cascade = CascadeType.ALL) - @JoinColumn(name = "attachment_file_reference_id", referencedColumnName = "id") - private FileReference attachment; - - // ---------------------------------------------------------------------------------- - // Properties (Getters and Setters) - // ---------------------------------------------------------------------------------- - public FileReference getAttachment() { - return this.attachment; - } - - public void setAttachment(FileReference attachment) { - this.attachment = attachment; - } - - // ---------------------------------------------------------------------------------- - // Methods Common To All Objects - // ---------------------------------------------------------------------------------- - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof AttachmentReport)) return false; - final AttachmentReport other = (AttachmentReport) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.attachment, other.attachment); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), this.attachment); - } - - // ---------------------------------------------------------------------------------- - // Other Methods - // ---------------------------------------------------------------------------------- - @Override - protected boolean canEqual(final Object other) { - return other instanceof AttachmentReport; - } -} +package se.su.dsv.scipro.report; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.OneToOne; +import java.util.Objects; +import se.su.dsv.scipro.file.FileReference; + +@MappedSuperclass +public abstract class AttachmentReport extends Report { + + // ---------------------------------------------------------------------------------- + // JPA-mappings of foreign keys in table of children class (OppositionReport) + // referencing other tables. + // ---------------------------------------------------------------------------------- + @OneToOne(optional = true, cascade = CascadeType.ALL) + @JoinColumn(name = "attachment_file_reference_id", referencedColumnName = "id") + private FileReference attachment; + + // ---------------------------------------------------------------------------------- + // Properties (Getters and Setters) + // ---------------------------------------------------------------------------------- + public FileReference getAttachment() { + return this.attachment; + } + + public void setAttachment(FileReference attachment) { + this.attachment = attachment; + } + + // ---------------------------------------------------------------------------------- + // Methods Common To All Objects + // ---------------------------------------------------------------------------------- + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof AttachmentReport)) return false; + final AttachmentReport other = (AttachmentReport) o; + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.attachment, other.attachment)); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), this.attachment); + } + + // ---------------------------------------------------------------------------------- + // Other Methods + // ---------------------------------------------------------------------------------- + @Override + protected boolean canEqual(final Object other) { + return other instanceof AttachmentReport; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/report/Criterion.java b/core/src/main/java/se/su/dsv/scipro/report/Criterion.java index 63978c9170..78d2d37981 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/Criterion.java +++ b/core/src/main/java/se/su/dsv/scipro/report/Criterion.java @@ -6,13 +6,13 @@ import jakarta.persistence.Entity; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.Language; - import java.util.Objects; +import se.su.dsv.scipro.system.Language; @Entity @Table(name = "criterion") public class Criterion extends AbstractCriterion { + public static final int DESCRIPTION_LENGTH = 2000; // ---------------------------------------------------------------------------------- @@ -34,14 +34,13 @@ public class Criterion extends AbstractCriterion { // JPA-mappings of foreign keys in this table (criterion) referencing other tables. // ---------------------------------------------------------------------------------- @ManyToOne(optional = false) - @JoinColumn(name ="report_id", referencedColumnName = "id") + @JoinColumn(name = "report_id", referencedColumnName = "id") private Report report; // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected Criterion() { - } + protected Criterion() {} Criterion(Report report, String title, String titleEn, String description, String descriptionEn, int sortOrder) { super(title, titleEn, sortOrder); @@ -51,7 +50,14 @@ public class Criterion extends AbstractCriterion { } Criterion(Report report, GradingCriterionTemplate gradingCriterionTemplate) { - this(report, gradingCriterionTemplate.getTitle(), gradingCriterionTemplate.getTitleEn(), gradingCriterionTemplate.getDescription(), gradingCriterionTemplate.getDescriptionEn(), gradingCriterionTemplate.getSortOrder()); + this( + report, + gradingCriterionTemplate.getTitle(), + gradingCriterionTemplate.getTitleEn(), + gradingCriterionTemplate.getDescription(), + gradingCriterionTemplate.getDescriptionEn(), + gradingCriterionTemplate.getSortOrder() + ); } // ---------------------------------------------------------------------------------- @@ -85,12 +91,14 @@ public class Criterion extends AbstractCriterion { if (o == this) return true; if (!(o instanceof Criterion)) return false; final Criterion other = (Criterion) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getReport(), other.getReport()) - && Objects.equals(this.getFeedback(), other.getFeedback()) - && Objects.equals(this.getDescription(), other.getDescription()) - && Objects.equals(this.getDescriptionEn(), other.getDescriptionEn()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getReport(), other.getReport()) && + Objects.equals(this.getFeedback(), other.getFeedback()) && + Objects.equals(this.getDescription(), other.getDescription()) && + Objects.equals(this.getDescriptionEn(), other.getDescriptionEn()) + ); } @Override @@ -100,9 +108,17 @@ public class Criterion extends AbstractCriterion { @Override public String toString() { - return "Criterion(report=" + this.getReport() + ", feedback=" + this.getFeedback() + - ", description=" + this.getDescription() + ", descriptionEn=" + - this.getDescriptionEn() + ")"; + return ( + "Criterion(report=" + + this.getReport() + + ", feedback=" + + this.getFeedback() + + ", description=" + + this.getDescription() + + ", descriptionEn=" + + this.getDescriptionEn() + + ")" + ); } // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/report/DuplicateDateException.java b/core/src/main/java/se/su/dsv/scipro/report/DuplicateDateException.java index 1957362903..27d969bb5a 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/DuplicateDateException.java +++ b/core/src/main/java/se/su/dsv/scipro/report/DuplicateDateException.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.report; +import java.time.LocalDate; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - public class DuplicateDateException extends Exception { + private final LocalDate validFrom; private final ProjectType projectType; diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradeCalculatorServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/report/GradeCalculatorServiceImpl.java index c2a6362c83..906a3cde51 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradeCalculatorServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradeCalculatorServiceImpl.java @@ -28,8 +28,7 @@ public class GradeCalculatorServiceImpl implements GradeCalculatorService { if (degreeType == DegreeType.BACHELOR) { if (getYear(project) >= 2017) { return new se.su.dsv.scipro.report.calculators.vt17.SupervisorBachelorGradeCalculator(); - } - else { + } else { return new SupervisorBachelorGradeCalculator(); } } else if (degreeType == DegreeType.MASTER || degreeType == DegreeType.MAGISTER) { @@ -45,19 +44,19 @@ public class GradeCalculatorServiceImpl implements GradeCalculatorService { } else if (credits == ProjectType.HP_30 || credits == 0) { if (getYear(project) >= 2017) { return new se.su.dsv.scipro.report.calculators.vt17.SupervisorMasterGradeCalculator(); - } - else { + } else { return new SupervisorMaster30GradeCalculator(); } } - throw new IllegalStateException("No grade calculation implemented for master project with " + credits + " credits"); + throw new IllegalStateException( + "No grade calculation implemented for master project with " + credits + " credits" + ); } private GradeCalculator getMagisterGradeCalculator(Project project) { if (getYear(project) >= 2017) { return new se.su.dsv.scipro.report.calculators.vt17.SupervisorMagisterGradeCalculator(); - } - else { + } else { return new SupervisorMaster15GradeCalculator(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradeLimit.java b/core/src/main/java/se/su/dsv/scipro/report/GradeLimit.java index 385d4941f3..26bdd3cbef 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradeLimit.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradeLimit.java @@ -11,6 +11,7 @@ import jakarta.persistence.Table; @Entity @Table(name = "grading_report_template_grade_limit") public class GradeLimit { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterion.java b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterion.java index 10ea7059b0..f6eaa540ea 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterion.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterion.java @@ -11,7 +11,6 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; - import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -22,6 +21,7 @@ import java.util.Objects; @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "type") public abstract class GradingCriterion extends AbstractGradingCriterion { + public static final int FEEDBACK_LENGTH = 2000; // ---------------------------------------------------------------------------------- @@ -34,7 +34,7 @@ public abstract class GradingCriterion extends AbstractGradingCriterion { @Basic @Column(name = "feedback", length = FEEDBACK_LENGTH) private String feedback; - + // ---------------------------------------------------------------------------------- // JPA-mappings of foreign keys in this table (grading_criterion) referencing other // tables. @@ -57,14 +57,23 @@ public abstract class GradingCriterion extends AbstractGradingCriterion { } GradingCriterion(GradingReport gradingReport, GradingCriterionTemplate gradingCriterionTemplate) { - super(gradingCriterionTemplate.getTitle(), gradingCriterionTemplate.getTitleEn(), gradingCriterionTemplate.getSortOrder(), gradingCriterionTemplate.getPointsRequiredToPass(), gradingCriterionTemplate.getFlag()); + super( + gradingCriterionTemplate.getTitle(), + gradingCriterionTemplate.getTitleEn(), + gradingCriterionTemplate.getSortOrder(), + gradingCriterionTemplate.getPointsRequiredToPass(), + gradingCriterionTemplate.getFlag() + ); this.gradingReport = gradingReport; for (GradingCriterionPointTemplate pointTemplate : gradingCriterionTemplate.getGradingCriterionPointTemplates()) { - gradingCriterionPoints.add(new GradingCriterionPoint( + gradingCriterionPoints.add( + new GradingCriterionPoint( pointTemplate.getPoint(), pointTemplate.getDescription(), pointTemplate.getDescriptionEn(), - this)); + this + ) + ); } } @@ -103,11 +112,13 @@ public abstract class GradingCriterion extends AbstractGradingCriterion { if (o == this) return true; if (!(o instanceof GradingCriterion)) return false; final GradingCriterion other = (GradingCriterion) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getGradingReport(), other.getGradingReport()) - && Objects.equals(this.getPoints(), other.getPoints()) - && Objects.equals(this.getFeedback(), other.getFeedback()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getGradingReport(), other.getGradingReport()) && + Objects.equals(this.getPoints(), other.getPoints()) && + Objects.equals(this.getFeedback(), other.getFeedback()) + ); } @Override @@ -117,8 +128,15 @@ public abstract class GradingCriterion extends AbstractGradingCriterion { @Override public String toString() { - return "GradingCriterion(gradingReport=" + this.getGradingReport() + ", points=" + this.getPoints() + - ", feedback=" + this.getFeedback() + ")"; + return ( + "GradingCriterion(gradingReport=" + + this.getGradingReport() + + ", points=" + + this.getPoints() + + ", feedback=" + + this.getFeedback() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -134,7 +152,7 @@ public abstract class GradingCriterion extends AbstractGradingCriterion { } public boolean meetsMinimumPointRequirement() { - return Objects.requireNonNullElse(getPoints(), 0) >= getPointsRequiredToPass(); + return (Objects.requireNonNullElse(getPoints(), 0) >= getPointsRequiredToPass()); } public boolean isAssessed() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPoint.java b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPoint.java index 6c516f95b4..f10d233a88 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPoint.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPoint.java @@ -9,6 +9,7 @@ import java.util.Objects; @Entity @Table(name = "grading_criterion_point") public class GradingCriterionPoint extends AbstractGradingCriterionPoint { + // ---------------------------------------------------------------------------------- // JPA-mappings of foreign keys in this table (grading_criterion_point) referencing other // tables. @@ -20,11 +21,14 @@ public class GradingCriterionPoint extends AbstractGradingCriterionPoint { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - public GradingCriterionPoint() { - } + public GradingCriterionPoint() {} - public GradingCriterionPoint(final Integer point, final String description, - final String descriptionEn, final GradingCriterion gradingCriterion) { + public GradingCriterionPoint( + final Integer point, + final String description, + final String descriptionEn, + final GradingCriterion gradingCriterion + ) { setPoint(point); setDescription(description); setDescriptionEn(descriptionEn); @@ -55,9 +59,11 @@ public class GradingCriterionPoint extends AbstractGradingCriterionPoint { if (o == this) return true; if (!(o instanceof GradingCriterionPoint)) return false; final GradingCriterionPoint other = (GradingCriterionPoint) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getGradingCriterion(), other.getGradingCriterion()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getGradingCriterion(), other.getGradingCriterion()) + ); } @Override @@ -67,7 +73,7 @@ public class GradingCriterionPoint extends AbstractGradingCriterionPoint { @Override public String toString() { - return "GradingCriterionPoint(gradingCriterion=" + this.getGradingCriterion() + ")"; + return ("GradingCriterionPoint(gradingCriterion=" + this.getGradingCriterion() + ")"); } // ---------------------------------------------------------------------------------- @@ -77,5 +83,4 @@ public class GradingCriterionPoint extends AbstractGradingCriterionPoint { protected boolean canEqual(final Object other) { return other instanceof GradingCriterionPoint; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPointTemplate.java b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPointTemplate.java index a41785948a..eba6059798 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPointTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionPointTemplate.java @@ -4,7 +4,6 @@ import jakarta.persistence.Entity; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import java.util.Objects; @Entity @@ -30,7 +29,7 @@ public class GradingCriterionPointTemplate extends AbstractGradingCriterionPoint @Override public String toString() { - return "GradingCriterionPointTemplate(gradingCriterionTemplate=" + this.getGradingCriterionTemplate() + ")"; + return ("GradingCriterionPointTemplate(gradingCriterionTemplate=" + this.getGradingCriterionTemplate() + ")"); } @Override @@ -38,9 +37,11 @@ public class GradingCriterionPointTemplate extends AbstractGradingCriterionPoint if (o == this) return true; if (!(o instanceof GradingCriterionPointTemplate)) return false; final GradingCriterionPointTemplate other = (GradingCriterionPointTemplate) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getGradingCriterionTemplate(), other.getGradingCriterionTemplate()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getGradingCriterionTemplate(), other.getGradingCriterionTemplate()) + ); } @Override @@ -54,6 +55,7 @@ public class GradingCriterionPointTemplate extends AbstractGradingCriterionPoint } public static class Builder { + private final GradingCriterionPointTemplate instance = new GradingCriterionPointTemplate(); public Builder point(Integer point) { diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionTemplate.java b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionTemplate.java index 92ab7539dc..2ba8dfcc4b 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingCriterionTemplate.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.report; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - import jakarta.persistence.CascadeType; import jakarta.persistence.DiscriminatorColumn; import jakarta.persistence.Entity; @@ -14,12 +9,17 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; @Entity @Table(name = "grading_criterion_template") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "type", length = GradingCriterionTemplate.LENGTH) public abstract class GradingCriterionTemplate extends AbstractGradingCriterion { + public static final int LENGTH = 64; @ManyToOne(optional = false) @@ -29,11 +29,16 @@ public abstract class GradingCriterionTemplate extends AbstractGradingCriterion @OneToMany(mappedBy = "gradingCriterionTemplate", orphanRemoval = true, cascade = CascadeType.ALL) private List gradingCriterionPointTemplates = new ArrayList<>(); - protected GradingCriterionTemplate() { + protected GradingCriterionTemplate() {} - } - - GradingCriterionTemplate(GradingReportTemplate gradingReportTemplate, int sortOrder, String title, String titleEn, int pointsRequiredToPass, List gradingCriterionPointTemplates) { + GradingCriterionTemplate( + GradingReportTemplate gradingReportTemplate, + int sortOrder, + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates + ) { super(title, titleEn, sortOrder, pointsRequiredToPass); this.gradingReportTemplate = gradingReportTemplate; this.gradingCriterionPointTemplates = gradingCriterionPointTemplates; @@ -64,7 +69,9 @@ public abstract class GradingCriterionTemplate extends AbstractGradingCriterion StringBuilder desc = new StringBuilder(); String separator = System.getProperty("line.separator"); for (GradingCriterionPointTemplate criterionPointTemplate : gradingCriterionPointTemplates) { - String description = isSwedish ? criterionPointTemplate.getDescription() : criterionPointTemplate.getDescriptionEn(); + String description = isSwedish + ? criterionPointTemplate.getDescription() + : criterionPointTemplate.getDescriptionEn(); if (description != null && !description.equals("")) { desc.append(criterionPointTemplate.getPoint()).append(" p - ").append(description).append(separator); } @@ -93,9 +100,11 @@ public abstract class GradingCriterionTemplate extends AbstractGradingCriterion if (o == this) return true; if (!(o instanceof GradingCriterionTemplate)) return false; final GradingCriterionTemplate other = (GradingCriterionTemplate) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getGradingReportTemplate(), other.getGradingReportTemplate()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getGradingReportTemplate(), other.getGradingReportTemplate()) + ); } @Override @@ -110,6 +119,6 @@ public abstract class GradingCriterionTemplate extends AbstractGradingCriterion @Override public String toString() { - return "GradingCriterionTemplate(gradingReportTemplate=" + this.getGradingReportTemplate() + ")"; + return ("GradingCriterionTemplate(gradingReportTemplate=" + this.getGradingReportTemplate() + ")"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReport.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReport.java index 6957cae4d5..c67a952048 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReport.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReport.java @@ -9,16 +9,15 @@ import jakarta.persistence.Enumerated; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "grading_report") @@ -34,7 +33,11 @@ public abstract class GradingReport extends Report { public static final Grade FX = new Grade("FX"); } - public enum State { INITIAL, REVIEWING, FINALIZED } + public enum State { + INITIAL, + REVIEWING, + FINALIZED, + } // ---------------------------------------------------------------------------------- // Basic JPA-mappings @@ -58,7 +61,7 @@ public abstract class GradingReport extends Report { // ---------------------------------------------------------------------------------- // JPA-mappings of other tables referencing to this table "grading_report" // ---------------------------------------------------------------------------------- - @OneToMany(mappedBy = "gradingReport", cascade = {CascadeType.ALL}) + @OneToMany(mappedBy = "gradingReport", cascade = { CascadeType.ALL }) private List gradingCriteria = new ArrayList<>(); // ---------------------------------------------------------------------------------- @@ -83,7 +86,7 @@ public abstract class GradingReport extends Report { this.state = state; } - public Instant getDateSubmittedToExaminer(){ + public Instant getDateSubmittedToExaminer() { return this.dateSubmittedToExaminer; } @@ -105,7 +108,7 @@ public abstract class GradingReport extends Report { // ---------------------------------------------------------------------------------- @Override public String toString() { - return "GradingReport(state=" + this.getState() + ", project=" + this.getProject() + ")"; + return ("GradingReport(state=" + this.getState() + ", project=" + this.getProject() + ")"); } // ---------------------------------------------------------------------------------- @@ -120,10 +123,7 @@ public abstract class GradingReport extends Report { } public String getAuthorNames() { - return getProject() - .getProjectParticipants() - .stream() - .map(User::getFullName).collect(Collectors.joining(", ")); + return getProject().getProjectParticipants().stream().map(User::getFullName).collect(Collectors.joining(", ")); } public ProjectType getProjectType() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportEvent.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportEvent.java index 48adee1d5c..b55c4186e5 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.report; import se.su.dsv.scipro.project.Project; class GradingReportEvent { + protected GradingReport gradingReport; protected GradingReportEvent(GradingReport gradingReport) { diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportService.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportService.java index c82432c25e..1c38af9b44 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportService.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportService.java @@ -1,23 +1,23 @@ package se.su.dsv.scipro.report; +import java.time.Instant; +import java.util.List; import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; import se.su.dsv.scipro.grading.GradingBasis; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import java.time.Instant; -import java.util.List; - public interface GradingReportService { - SupervisorGradingReport getSupervisorGradingReport(Project project, User student); List getSupervisorGradingReports(Project project); GradingReportTemplate getTemplate(Project project); - Either, SupervisorGradingReport> submitReport(SupervisorGradingReport supervisorGradingReport); + Either, SupervisorGradingReport> submitReport( + SupervisorGradingReport supervisorGradingReport + ); boolean updateOppositionCriteria(SupervisorGradingReport report, FinalSeminarOpposition opposition); diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportServiceImpl.java index 876d3a4010..bc945b6443 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportServiceImpl.java @@ -1,7 +1,12 @@ package se.su.dsv.scipro.report; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDate; +import java.util.*; import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; import se.su.dsv.scipro.grading.GradingBasis; import se.su.dsv.scipro.grading.GradingReportTemplateService; @@ -15,12 +20,6 @@ import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.Instant; -import java.time.LocalDate; -import java.util.*; - public class GradingReportServiceImpl implements GradingReportTemplateService, GradingReportService { private final EventBus eventBus; @@ -32,13 +31,13 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Inject public GradingReportServiceImpl( - EventBus eventBus, - ThesisSubmissionHistoryService thesisSubmissionHistoryService, - Clock clock, - SupervisorGradingReportRepository supervisorGradingReportRepository, - GradingReportTemplateRepo gradingReportTemplateRepo, - ProjectTypeService projectTypeService) - { + EventBus eventBus, + ThesisSubmissionHistoryService thesisSubmissionHistoryService, + Clock clock, + SupervisorGradingReportRepository supervisorGradingReportRepository, + GradingReportTemplateRepo gradingReportTemplateRepo, + ProjectTypeService projectTypeService + ) { this.eventBus = eventBus; this.thesisSubmissionHistoryService = thesisSubmissionHistoryService; this.clock = clock; @@ -52,7 +51,8 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G public boolean updateOppositionCriteria(SupervisorGradingReport report, FinalSeminarOpposition opposition) { for (GradingCriterion gradingCriterion : report.getIndividualCriteria()) { boolean isOppositionCriterion = gradingCriterion.getFlag() == GradingCriterion.Flag.OPPOSITION; - boolean betterGrade = gradingCriterion.getPoints() == null || opposition.getPoints() > gradingCriterion.getPoints(); + boolean betterGrade = + gradingCriterion.getPoints() == null || opposition.getPoints() > gradingCriterion.getPoints(); if (isOppositionCriterion && betterGrade) { gradingCriterion.setFeedback(opposition.getFeedback()); gradingCriterion.setPoints(opposition.getPoints()); @@ -65,19 +65,20 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Override public GradingBasis getGradingBasis(Project project) { - SupervisorGradingReport supervisorGradingReport = getSupervisorGradingReports(project) - .get(0); - List assessment = supervisorGradingReport.getProjectCriteria() - .stream() - .sorted(Comparator.comparing(GradingCriterion::getSortOrder)) - .map(gc -> toAssessment(supervisorGradingReport.getReportLanguage(), gc)) - .toList(); + SupervisorGradingReport supervisorGradingReport = getSupervisorGradingReports(project).get(0); + List assessment = supervisorGradingReport + .getProjectCriteria() + .stream() + .sorted(Comparator.comparing(GradingCriterion::getSortOrder)) + .map(gc -> toAssessment(supervisorGradingReport.getReportLanguage(), gc)) + .toList(); return new GradingBasis( - assessment, - supervisorGradingReport.isSubmitted(), - supervisorGradingReport.getMotivation(), - supervisorGradingReport.getRejectionComment(), - supervisorGradingReport.getRejectionCommentFeedback()); + assessment, + supervisorGradingReport.isSubmitted(), + supervisorGradingReport.getMotivation(), + supervisorGradingReport.getRejectionComment(), + supervisorGradingReport.getRejectionCommentFeedback() + ); } @Override @@ -103,34 +104,32 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Override public Instant getDateSentToExaminer(Project project) { return getSupervisorGradingReports(project) - .stream() - .map(SupervisorGradingReport::getDateSubmittedToExaminer) - .filter(Objects::nonNull) - .max(Comparator.naturalOrder()) - .orElse(null); + .stream() + .map(SupervisorGradingReport::getDateSubmittedToExaminer) + .filter(Objects::nonNull) + .max(Comparator.naturalOrder()) + .orElse(null); } - private GradingBasis.Assessment toAssessment( - Language language, - GradingCriterion gc) { - List requirements = gc.getGradingCriterionPoints() - .stream() - .sorted(Comparator.comparing(GradingCriterionPoint::getPoint)) - .map(gcp -> toRequirement(language, gcp)) - .toList(); + private GradingBasis.Assessment toAssessment(Language language, GradingCriterion gc) { + List requirements = gc + .getGradingCriterionPoints() + .stream() + .sorted(Comparator.comparing(GradingCriterionPoint::getPoint)) + .map(gcp -> toRequirement(language, gcp)) + .toList(); String title = gc.getTitle(language); - GradingBasis.Criterion criterion = new GradingBasis.Criterion(title, requirements, gc.getPointsRequiredToPass()); + GradingBasis.Criterion criterion = new GradingBasis.Criterion( + title, + requirements, + gc.getPointsRequiredToPass() + ); return new GradingBasis.Assessment(criterion, gc.getPoints()); } - private GradingBasis.Criterion.Requirement toRequirement( - Language language, - GradingCriterionPoint gcp) - { + private GradingBasis.Criterion.Requirement toRequirement(Language language, GradingCriterionPoint gcp) { String description = gcp.getDescription(language); - return new GradingBasis.Criterion.Requirement( - gcp.getPoint(), - description); + return new GradingBasis.Criterion.Requirement(gcp.getPoint(), description); } @Override @@ -162,7 +161,9 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Override @Transactional - public Either, SupervisorGradingReport> submitReport(SupervisorGradingReport supervisorGradingReport) { + public Either, SupervisorGradingReport> submitReport( + SupervisorGradingReport supervisorGradingReport + ) { final ArrayList errors = new ArrayList<>(); for (GradingCriterion gradingCriterion : supervisorGradingReport.getGradingCriteria()) { if (!gradingCriterion.isAssessed()) { @@ -184,16 +185,17 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G eventBus.post(new SupervisorGradingReportSubmittedEvent(supervisorGradingReport)); if (isBlank(rejectionCommentFeedback)) { thesisSubmissionHistoryService.addInitialSubmission( - supervisorGradingReport.getProject(), - supervisorGradingReport.getUser(), - clock.instant()); - } - else { + supervisorGradingReport.getProject(), + supervisorGradingReport.getUser(), + clock.instant() + ); + } else { thesisSubmissionHistoryService.addResubmission( - supervisorGradingReport.getProject(), - supervisorGradingReport.getUser(), - clock.instant(), - rejectionCommentFeedback); + supervisorGradingReport.getProject(), + supervisorGradingReport.getUser(), + clock.instant(), + rejectionCommentFeedback + ); } supervisorGradingReportRepository.save(supervisorGradingReport); @@ -241,11 +243,7 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Override public GradingReportTemplate update(long templateId, GradingReportTemplateUpdate update) - throws ValidDateMustBeInTheFutureException, - NoSuchTemplateException, - DuplicateDateException, - TemplateLockedException - { + throws ValidDateMustBeInTheFutureException, NoSuchTemplateException, DuplicateDateException, TemplateLockedException { LocalDate today = LocalDate.now(clock); if (!update.validFrom().isAfter(today)) { throw new ValidDateMustBeInTheFutureException(update.validFrom(), today.plusDays(1)); @@ -257,11 +255,12 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G } GradingReportTemplate currentTemplate = gradingReportTemplateRepo.getCurrentTemplate( - template.getProjectType(), - update.validFrom()); - if (currentTemplate.getId() != templateId && - Objects.equals(currentTemplate.getValidFrom(), update.validFrom())) - { + template.getProjectType(), + update.validFrom() + ); + if ( + currentTemplate.getId() != templateId && Objects.equals(currentTemplate.getValidFrom(), update.validFrom()) + ) { throw new DuplicateDateException(update.validFrom(), template.getProjectType()); } @@ -274,19 +273,17 @@ public class GradingReportServiceImpl implements GradingReportTemplateService, G @Override public GradingReportTemplate create(ProjectType projectType, GradingReportTemplateUpdate update) - throws ValidDateMustBeInTheFutureException, DuplicateDateException - { + throws ValidDateMustBeInTheFutureException, DuplicateDateException { LocalDate today = LocalDate.now(clock); if (!update.validFrom().isAfter(today)) { throw new ValidDateMustBeInTheFutureException(update.validFrom(), today.plusDays(1)); } GradingReportTemplate currentTemplate = gradingReportTemplateRepo.getCurrentTemplate( - projectType, - update.validFrom()); - if (currentTemplate != null && - Objects.equals(currentTemplate.getValidFrom(), update.validFrom())) - { + projectType, + update.validFrom() + ); + if (currentTemplate != null && Objects.equals(currentTemplate.getValidFrom(), update.validFrom())) { throw new DuplicateDateException(update.validFrom(), projectType); } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplate.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplate.java index 55fe04823b..76ebe71687 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplate.java @@ -14,17 +14,16 @@ import jakarta.persistence.OrderBy; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "grading_report_template") @@ -61,7 +60,7 @@ public class GradingReportTemplate extends DomainObject { // ---------------------------------------------------------------------------------- // JPA-mappings of other tables referencing to this table "grading_report_template" // ---------------------------------------------------------------------------------- - @OneToMany(mappedBy = "gradingReportTemplate", cascade = {CascadeType.ALL}, orphanRemoval = true) + @OneToMany(mappedBy = "gradingReportTemplate", cascade = { CascadeType.ALL }, orphanRemoval = true) @OrderBy("sortOrder ASC") private List criteria = new ArrayList<>(); @@ -72,9 +71,7 @@ public class GradingReportTemplate extends DomainObject { // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected GradingReportTemplate() { - - } + protected GradingReportTemplate() {} public GradingReportTemplate(ProjectType projectType, LocalDate validFrom) { if (projectType == null) { @@ -144,8 +141,7 @@ public class GradingReportTemplate extends DomainObject { if (o == this) return true; if (!(o instanceof GradingReportTemplate)) return false; final GradingReportTemplate other = (GradingReportTemplate) o; - return other.canEqual(this) - && Objects.equals(this.id, other.id); + return other.canEqual(this) && Objects.equals(this.id, other.id); } @Override @@ -155,8 +151,15 @@ public class GradingReportTemplate extends DomainObject { @Override public String toString() { - return "GradingReportTemplate(id=" + this.id + ", projectType=" + this.projectType + ", validFrom=" + - this.validFrom + ")"; + return ( + "GradingReportTemplate(id=" + + this.id + + ", projectType=" + + this.projectType + + ", validFrom=" + + this.validFrom + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -173,37 +176,64 @@ public class GradingReportTemplate extends DomainObject { return new OppositionReport(this, finalSeminarOpposition); } - public GradingCriterionTemplate addProjectCriterion(String title, String titleEn, int pointsRequiredToPass, - List gradingCriterionPointTemplates) { + public GradingCriterionTemplate addProjectCriterion( + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates + ) { return addProjectCriterion(title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates, null); } - public GradingCriterionTemplate addProjectCriterion(String title, String titleEn, int pointsRequiredToPass, - List gradingCriterionPointTemplates, - AbstractGradingCriterion.Flag flag) { - GradingCriterionTemplate gradingCriterionTemplate = new ProjectGradingCriterionTemplate(this, - criteria.size(), title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates); + public GradingCriterionTemplate addProjectCriterion( + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag flag + ) { + GradingCriterionTemplate gradingCriterionTemplate = new ProjectGradingCriterionTemplate( + this, + criteria.size(), + title, + titleEn, + pointsRequiredToPass, + gradingCriterionPointTemplates + ); gradingCriterionTemplate.setFlag(flag); criteria.add(gradingCriterionTemplate); return gradingCriterionTemplate; } - public GradingCriterionTemplate addIndividualCriterion(String title, String titleEn, int pointsRequiredToPass, - List gradingCriterionPointTemplates) { + public GradingCriterionTemplate addIndividualCriterion( + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates + ) { return addIndividualCriterion(title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates, null); } - public GradingCriterionTemplate addIndividualCriterion(String title, String titleEn, int pointsRequiredToPass, - List gradingCriterionPointTemplates, - AbstractGradingCriterion.Flag flag) { - GradingCriterionTemplate gradingCriterionTemplate = new IndividualGradingCriterionTemplate(this, - criteria.size(), title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates); + public GradingCriterionTemplate addIndividualCriterion( + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag flag + ) { + GradingCriterionTemplate gradingCriterionTemplate = new IndividualGradingCriterionTemplate( + this, + criteria.size(), + title, + titleEn, + pointsRequiredToPass, + gradingCriterionPointTemplates + ); gradingCriterionTemplate.setFlag(flag); criteria.add(gradingCriterionTemplate); return gradingCriterionTemplate; } - protected boolean canEqual(final Object other) { return other instanceof GradingReportTemplate; } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateGradeCalculator.java index 777770eb3b..f5ab570767 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateGradeCalculator.java @@ -4,6 +4,7 @@ import java.util.Comparator; import java.util.Objects; class GradingReportTemplateGradeCalculator implements GradeCalculator { + private final GradingReportTemplate template; GradingReportTemplateGradeCalculator(GradingReportTemplate template) { @@ -18,22 +19,24 @@ class GradingReportTemplateGradeCalculator implements GradeCalculator { } } long points = getPoints(gradingReport); - String textualGrade = template.getGradeLimits() - .stream() - .filter(gradeLimit -> points >= gradeLimit.getLowerLimit()) - .max(Comparator.comparing(GradeLimit::getLowerLimit)) - .map(GradeLimit::getGrade) - .orElseGet(template::getFailingGrade); + String textualGrade = template + .getGradeLimits() + .stream() + .filter(gradeLimit -> points >= gradeLimit.getLowerLimit()) + .max(Comparator.comparing(GradeLimit::getLowerLimit)) + .map(GradeLimit::getGrade) + .orElseGet(template::getFailingGrade); return new GradingReport.Grade(textualGrade); } @Override public long getPoints(GradingReport gradingReport) { - return gradingReport.getGradingCriteria() - .stream() - .map(GradingCriterion::getPoints) - .filter(Objects::nonNull) - .mapToInt(Integer::intValue) - .sum(); + return gradingReport + .getGradingCriteria() + .stream() + .map(GradingCriterion::getPoints) + .filter(Objects::nonNull) + .mapToInt(Integer::intValue) + .sum(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepo.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepo.java index 9ae1d6560f..27b2e650ce 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepo.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.report; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.grading.GradingReportTemplateUpdate; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.ProjectType; - import java.time.LocalDate; import java.util.List; +import se.su.dsv.scipro.grading.GradingReportTemplateUpdate; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.ProjectType; public interface GradingReportTemplateRepo extends JpaRepository { GradingReportTemplate getTemplate(Project project); diff --git a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepoImpl.java index 7eec180ce5..8702aec340 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/GradingReportTemplateRepoImpl.java @@ -2,20 +2,21 @@ package se.su.dsv.scipro.report; import com.querydsl.jpa.JPAExpressions; import com.querydsl.jpa.JPQLQuery; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.grading.GradingReportTemplateUpdate; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.ProjectType; - +import jakarta.transaction.Transactional; import java.time.LocalDate; import java.util.List; +import se.su.dsv.scipro.grading.GradingReportTemplateUpdate; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.GenericRepo; +import se.su.dsv.scipro.system.ProjectType; + +public class GradingReportTemplateRepoImpl + extends GenericRepo + implements GradingReportTemplateRepo { -public class GradingReportTemplateRepoImpl extends GenericRepo implements GradingReportTemplateRepo { @Inject public GradingReportTemplateRepoImpl(Provider em) { super(em, GradingReportTemplate.class, QGradingReportTemplate.gradingReportTemplate); @@ -30,11 +31,9 @@ public class GradingReportTemplateRepoImpl extends GenericRepo validFrom = JPAExpressions - .select(template.validFrom.max()) - .from(template) - .where(template.projectType.eq(projectType) - .and(template.validFrom.loe(now))); + JPQLQuery validFrom = JPAExpressions.select(template.validFrom.max()) + .from(template) + .where(template.projectType.eq(projectType).and(template.validFrom.loe(now))); return findOne(template.projectType.eq(projectType).and(template.validFrom.eq(validFrom))); } @@ -42,18 +41,25 @@ public class GradingReportTemplateRepoImpl extends GenericRepo validFrom = JPAExpressions - .select(template.validFrom.min()) - .from(template) - .where(template.projectType.eq(gradingReportTemplate.getProjectType()) - .and(template.validFrom.gt(gradingReportTemplate.getValidFrom()))); - return findOne(template.projectType.eq(gradingReportTemplate.getProjectType()).and(template.validFrom.eq(validFrom))); + JPQLQuery validFrom = JPAExpressions.select(template.validFrom.min()) + .from(template) + .where( + template.projectType + .eq(gradingReportTemplate.getProjectType()) + .and(template.validFrom.gt(gradingReportTemplate.getValidFrom())) + ); + return findOne( + template.projectType.eq(gradingReportTemplate.getProjectType()).and(template.validFrom.eq(validFrom)) + ); } @Override public List getTemplatesValidAfter(ProjectType projectType, LocalDate date) { - return findAll(QGradingReportTemplate.gradingReportTemplate.projectType.eq(projectType) - .and(QGradingReportTemplate.gradingReportTemplate.validFrom.gt(date))); + return findAll( + QGradingReportTemplate.gradingReportTemplate.projectType + .eq(projectType) + .and(QGradingReportTemplate.gradingReportTemplate.validFrom.gt(date)) + ); } @Override @@ -69,40 +75,45 @@ public class GradingReportTemplateRepoImpl extends GenericRepo pointTemplates = criteria.requirements() - .stream() - .map(this::toPointTemplate) - .toList(); - AbstractGradingCriterion.Flag flag = criteria.flag() == null ? null : switch (criteria.flag()) { - case OPPOSITION -> AbstractGradingCriterion.Flag.OPPOSITION; - case REFLECTION -> AbstractGradingCriterion.Flag.REFLECTION; - //case null -> null; sigh java 17 - }; + final List pointTemplates = criteria + .requirements() + .stream() + .map(this::toPointTemplate) + .toList(); + AbstractGradingCriterion.Flag flag = criteria.flag() == null + ? null + : switch (criteria.flag()) { + case OPPOSITION -> AbstractGradingCriterion.Flag.OPPOSITION; + case REFLECTION -> AbstractGradingCriterion.Flag.REFLECTION; + //case null -> null; sigh java 17 + }; switch (criteria.type()) { case THESIS -> { gradingReportTemplate.addProjectCriterion( - criteria.title().swedish(), - criteria.title().english(), - criteria.minimumPointsRequiredToPass(), - pointTemplates, - flag); + criteria.title().swedish(), + criteria.title().english(), + criteria.minimumPointsRequiredToPass(), + pointTemplates, + flag + ); } case INDIVIDUAL -> { gradingReportTemplate.addIndividualCriterion( - criteria.title().swedish(), - criteria.title().english(), - criteria.minimumPointsRequiredToPass(), - pointTemplates, - flag); + criteria.title().swedish(), + criteria.title().english(), + criteria.minimumPointsRequiredToPass(), + pointTemplates, + flag + ); } } } @@ -125,11 +136,13 @@ public class GradingReportTemplateRepoImpl extends GenericRepo gradingCriterionPointTemplates) { + protected IndividualGradingCriterionTemplate() {} + + IndividualGradingCriterionTemplate( + GradingReportTemplate gradingReportTemplate, + int sortOrder, + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates + ) { super(gradingReportTemplate, sortOrder, title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates); } diff --git a/core/src/main/java/se/su/dsv/scipro/report/NoSuchTemplateException.java b/core/src/main/java/se/su/dsv/scipro/report/NoSuchTemplateException.java index 0013f826d2..1536dfef3d 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/NoSuchTemplateException.java +++ b/core/src/main/java/se/su/dsv/scipro/report/NoSuchTemplateException.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.report; -public class NoSuchTemplateException extends Exception { -} +public class NoSuchTemplateException extends Exception {} diff --git a/core/src/main/java/se/su/dsv/scipro/report/OppositionReport.java b/core/src/main/java/se/su/dsv/scipro/report/OppositionReport.java index 426e393399..11b087cc80 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/OppositionReport.java +++ b/core/src/main/java/se/su/dsv/scipro/report/OppositionReport.java @@ -8,15 +8,14 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "opposition_report") @@ -40,17 +39,18 @@ public class OppositionReport extends AttachmentReport { // ---------------------------------------------------------------------------------- // JPA-mappings of other tables referencing to this table "opposition_report" // ---------------------------------------------------------------------------------- - @OneToMany(mappedBy = "report", cascade = {CascadeType.ALL}) + @OneToMany(mappedBy = "report", cascade = { CascadeType.ALL }) private List oppositionCriteria = new ArrayList<>(); // ---------------------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------------------- - protected OppositionReport() { - } + protected OppositionReport() {} - public OppositionReport(GradingReportTemplate gradingReportTemplate, - FinalSeminarOpposition finalSeminarOpposition) { + public OppositionReport( + GradingReportTemplate gradingReportTemplate, + FinalSeminarOpposition finalSeminarOpposition + ) { this.finalSeminarOpposition = finalSeminarOpposition; createCriteriaFromTemplate(gradingReportTemplate); } @@ -86,12 +86,13 @@ public class OppositionReport extends AttachmentReport { } public String getAuthorNames() { - return finalSeminarOpposition.getFinalSeminar() - .getProject() - .getProjectParticipants() - .stream() - .map(User::getFullName) - .collect(Collectors.joining(", ")); + return finalSeminarOpposition + .getFinalSeminar() + .getProject() + .getProjectParticipants() + .stream() + .map(User::getFullName) + .collect(Collectors.joining(", ")); } public String getSupervisorName() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepo.java b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepo.java index 68fbc4dd66..082bcaeba3 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepo.java @@ -1,9 +1,10 @@ package se.su.dsv.scipro.report; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; import se.su.dsv.scipro.system.JpaRepository; import se.su.dsv.scipro.system.QueryDslPredicateExecutor; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -public interface OppositionReportRepo extends JpaRepository, QueryDslPredicateExecutor { +public interface OppositionReportRepo + extends JpaRepository, QueryDslPredicateExecutor { OppositionReport findByFinalSeminarOpposition(FinalSeminarOpposition finalSeminarOpposition); } diff --git a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepoImpl.java index b83ff0adba..e8246cc24c 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportRepoImpl.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.report; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; +import se.su.dsv.scipro.system.GenericRepo; public class OppositionReportRepoImpl extends GenericRepo implements OppositionReportRepo { + @Inject public OppositionReportRepoImpl(Provider em) { super(em, OppositionReport.class, QOppositionReport.oppositionReport); diff --git a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportService.java b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportService.java index defc900002..60f1db90b0 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportService.java +++ b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportService.java @@ -6,5 +6,5 @@ public interface OppositionReportService { OppositionReport findOrCreateReport(FinalSeminarOpposition finalSeminarOpposition); void save(OppositionReport oppositionReport); void deleteOppositionReport(FinalSeminarOpposition finalSeminarOpposition); - void deleteOpponentReport(FinalSeminarOpposition modelObject); + void deleteOpponentReport(FinalSeminarOpposition modelObject); } diff --git a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportServiceImpl.java index 231fe6f692..f993503d09 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/OppositionReportServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/OppositionReportServiceImpl.java @@ -1,15 +1,13 @@ package se.su.dsv.scipro.report; - +import jakarta.inject.Inject; +import jakarta.inject.Named; import jakarta.transaction.Transactional; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; import se.su.dsv.scipro.finalseminar.FinalSeminarOppositionRepo; -import jakarta.inject.Inject; -import jakarta.inject.Named; - @Named public class OppositionReportServiceImpl implements OppositionReportService { @@ -19,7 +17,12 @@ public class OppositionReportServiceImpl implements OppositionReportService { private FinalSeminarOppositionRepo finalSeminarOppositionRepo; @Inject - public OppositionReportServiceImpl(OppositionReportRepo oppositionReportRepo, GradingReportTemplateRepo gradingReportTemplateRepo, FileService fileService, FinalSeminarOppositionRepo finalSeminarOppositionRepo) { + public OppositionReportServiceImpl( + OppositionReportRepo oppositionReportRepo, + GradingReportTemplateRepo gradingReportTemplateRepo, + FileService fileService, + FinalSeminarOppositionRepo finalSeminarOppositionRepo + ) { this.oppositionReportRepo = oppositionReportRepo; this.gradingReportTemplateRepo = gradingReportTemplateRepo; this.fileService = fileService; @@ -33,13 +36,13 @@ public class OppositionReportServiceImpl implements OppositionReportService { if (oppositionReport != null) { return oppositionReport; } else { - OppositionReport newReport = gradingReportTemplateRepo.getTemplate(finalSeminarOpposition.getProject()) - .createOppositionReport(finalSeminarOpposition); + OppositionReport newReport = gradingReportTemplateRepo + .getTemplate(finalSeminarOpposition.getProject()) + .createOppositionReport(finalSeminarOpposition); return oppositionReportRepo.save(newReport); } } - @Override public void save(OppositionReport oppositionReport) { oppositionReportRepo.save(oppositionReport); diff --git a/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterion.java b/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterion.java index 218da2c3d7..ee7a336217 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterion.java +++ b/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterion.java @@ -4,8 +4,8 @@ import jakarta.persistence.Entity; @Entity public class ProjectGradingCriterion extends GradingCriterion { - protected ProjectGradingCriterion() { - } + + protected ProjectGradingCriterion() {} ProjectGradingCriterion(GradingReport gradingReport, GradingCriterionTemplate gradingCriterionTemplate) { super(gradingReport, gradingCriterionTemplate); diff --git a/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterionTemplate.java b/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterionTemplate.java index a4188d24d2..1fad29aedb 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterionTemplate.java +++ b/core/src/main/java/se/su/dsv/scipro/report/ProjectGradingCriterionTemplate.java @@ -5,10 +5,17 @@ import java.util.List; @Entity public class ProjectGradingCriterionTemplate extends GradingCriterionTemplate { - protected ProjectGradingCriterionTemplate() { - } - ProjectGradingCriterionTemplate(GradingReportTemplate gradingReportTemplate, int sortOrder, String title, String titleEn, int pointsRequiredToPass, List gradingCriterionPointTemplates) { + protected ProjectGradingCriterionTemplate() {} + + ProjectGradingCriterionTemplate( + GradingReportTemplate gradingReportTemplate, + int sortOrder, + String title, + String titleEn, + int pointsRequiredToPass, + List gradingCriterionPointTemplates + ) { super(gradingReportTemplate, sortOrder, title, titleEn, pointsRequiredToPass, gradingCriterionPointTemplates); } diff --git a/core/src/main/java/se/su/dsv/scipro/report/Report.java b/core/src/main/java/se/su/dsv/scipro/report/Report.java index da88711b3b..d525867389 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/Report.java +++ b/core/src/main/java/se/su/dsv/scipro/report/Report.java @@ -9,14 +9,14 @@ import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.InheritanceType; import jakarta.persistence.Table; -import se.su.dsv.scipro.system.DomainObject; - import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Table(name = "report") @Inheritance(strategy = InheritanceType.JOINED) public abstract class Report extends DomainObject { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -52,8 +52,7 @@ public abstract class Report extends DomainObject { if (o == this) return true; if (!(o instanceof Report)) return false; final Report other = (Report) o; - return other.canEqual(this) - && Objects.equals(this.id, other.id); + return other.canEqual(this) && Objects.equals(this.id, other.id); } @Override @@ -72,7 +71,9 @@ public abstract class Report extends DomainObject { public void submit() { if (!isFinished()) { - throw new IllegalStateException("Report is not finished: you need to score and give feedback to every criteria"); + throw new IllegalStateException( + "Report is not finished: you need to score and give feedback to every criteria" + ); } submitted = true; } diff --git a/core/src/main/java/se/su/dsv/scipro/report/ReportService.java b/core/src/main/java/se/su/dsv/scipro/report/ReportService.java index ee6c1442f3..a077143c0e 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/ReportService.java +++ b/core/src/main/java/se/su/dsv/scipro/report/ReportService.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.report; +import java.util.Optional; import se.su.dsv.scipro.file.FileUpload; import se.su.dsv.scipro.system.GenericService; -import java.util.Optional; - -public interface ReportService extends GenericService { +public interface ReportService extends GenericService { AttachmentReport submit(AttachmentReport report); void save(AttachmentReport report, Optional fileUpload); diff --git a/core/src/main/java/se/su/dsv/scipro/report/ReportServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/report/ReportServiceImpl.java index a0f324029f..41b6e7a2a6 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/ReportServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/ReportServiceImpl.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.report; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileService; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.util.Optional; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileService; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.system.AbstractServiceImpl; public class ReportServiceImpl extends AbstractServiceImpl implements ReportService { diff --git a/core/src/main/java/se/su/dsv/scipro/report/SubmissionError.java b/core/src/main/java/se/su/dsv/scipro/report/SubmissionError.java index 345cf7489f..7fc72bf8c7 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/SubmissionError.java +++ b/core/src/main/java/se/su/dsv/scipro/report/SubmissionError.java @@ -2,18 +2,18 @@ package se.su.dsv.scipro.report; import java.util.function.Function; -sealed public interface SubmissionError { - +public sealed interface SubmissionError { A fold( Function ifUnassessed, - Function ifNoRejectionCommentFeedback); + Function ifNoRejectionCommentFeedback + ); record UnassessedCriterion(GradingCriterion gradingCriterion) implements SubmissionError { @Override public A fold( Function ifUnassessed, - Function ifNoRejectionCommentFeedback) - { + Function ifNoRejectionCommentFeedback + ) { return ifUnassessed.apply(this); } } @@ -22,8 +22,8 @@ sealed public interface SubmissionError { @Override public A fold( Function ifUnassessed, - Function ifNoRejectionCommentFeedback) - { + Function ifNoRejectionCommentFeedback + ) { return ifNoRejectionCommentFeedback.apply(this); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReport.java b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReport.java index 59b4bca6b8..333cb28c03 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReport.java +++ b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReport.java @@ -6,16 +6,16 @@ import jakarta.persistence.Entity; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "supervisor_grading_report") public class SupervisorGradingReport extends GradingReport { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -113,7 +113,7 @@ public class SupervisorGradingReport extends GradingReport { } public boolean hasProvidedRejectionFeedback() { - return rejectionComment == null || (rejectionCommentFeedback != null && !rejectionCommentFeedback.isBlank()); + return (rejectionComment == null || (rejectionCommentFeedback != null && !rejectionCommentFeedback.isBlank())); } private boolean allCriteriaAssessed() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportFactory.java b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportFactory.java index 13d81d38f4..572178355a 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportFactory.java +++ b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportFactory.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.report; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; public class SupervisorGradingReportFactory implements GradingCriterionTemplateVisitor { @@ -36,4 +35,3 @@ public class SupervisorGradingReportFactory implements GradingCriterionTemplateV return supervisorGradingReport; } } - diff --git a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportRepositoryImpl.java index be7c252236..055c276d01 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportRepositoryImpl.java @@ -7,9 +7,10 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.AbstractRepository; import se.su.dsv.scipro.system.User; -public class SupervisorGradingReportRepositoryImpl extends AbstractRepository - implements SupervisorGradingReportRepository -{ +public class SupervisorGradingReportRepositoryImpl + extends AbstractRepository + implements SupervisorGradingReportRepository { + @Inject public SupervisorGradingReportRepositoryImpl(Provider em) { super(em); @@ -20,8 +21,7 @@ public class SupervisorGradingReportRepositoryImpl extends AbstractRepository EntityManager entityManager = em(); if (entityManager.contains(report)) { return entityManager.merge(report); - } - else { + } else { entityManager.persist(report); return report; } @@ -30,8 +30,11 @@ public class SupervisorGradingReportRepositoryImpl extends AbstractRepository @Override public SupervisorGradingReport getReport(Project project, User author) { return from(QSupervisorGradingReport.supervisorGradingReport) - .where(QSupervisorGradingReport.supervisorGradingReport.user.eq(author).and( - QSupervisorGradingReport.supervisorGradingReport.project.eq(project))) - .fetchOne(); + .where( + QSupervisorGradingReport.supervisorGradingReport.user + .eq(author) + .and(QSupervisorGradingReport.supervisorGradingReport.project.eq(project)) + ) + .fetchOne(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportSubmittedEvent.java b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportSubmittedEvent.java index 31a56ed6e4..e0cf099640 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportSubmittedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/report/SupervisorGradingReportSubmittedEvent.java @@ -8,7 +8,6 @@ public final class SupervisorGradingReportSubmittedEvent extends GradingReportEv public SupervisorGradingReportSubmittedEvent(SupervisorGradingReport gradingReport) { super(gradingReport); - this.gradingReport = gradingReport; } diff --git a/core/src/main/java/se/su/dsv/scipro/report/TemplateLockedException.java b/core/src/main/java/se/su/dsv/scipro/report/TemplateLockedException.java index 217cdff1da..894b5793c7 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/TemplateLockedException.java +++ b/core/src/main/java/se/su/dsv/scipro/report/TemplateLockedException.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.report; import java.time.LocalDate; public class TemplateLockedException extends Exception { + private final LocalDate becameValidAt; public TemplateLockedException(LocalDate becameValidAt) { diff --git a/core/src/main/java/se/su/dsv/scipro/report/ValidDateMustBeInTheFutureException.java b/core/src/main/java/se/su/dsv/scipro/report/ValidDateMustBeInTheFutureException.java index dcaee0092b..a52ada1cb8 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/ValidDateMustBeInTheFutureException.java +++ b/core/src/main/java/se/su/dsv/scipro/report/ValidDateMustBeInTheFutureException.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.report; import java.time.LocalDate; public class ValidDateMustBeInTheFutureException extends Exception { + private final LocalDate validFrom; private final LocalDate earliestAllowedValidFrom; diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractBachelorGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractBachelorGradeCalculator.java index 5312f2f0ac..5390287449 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractBachelorGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractBachelorGradeCalculator.java @@ -26,6 +26,7 @@ public abstract class AbstractBachelorGradeCalculator implements GradeCalculator public abstract Iterable getGradingCriteria(GradingReport gradingReport); private static class BachelorCalculation extends Calculation { + private final Iterable gradingCriteria; public BachelorCalculation(Iterable gradingCriteria) { @@ -62,6 +63,5 @@ public abstract class AbstractBachelorGradeCalculator implements GradeCalculator protected int getNumberOfIndividualCriteriaRequiredToGetFx() { return NUMBER_OF_INDIVIDUAL_CRITERIA_NEEDED_TO_GET_FX; } - } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster15GradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster15GradeCalculator.java index ddcac4fcda..2429b39c80 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster15GradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster15GradeCalculator.java @@ -50,7 +50,7 @@ public abstract class AbstractMaster15GradeCalculator implements GradeCalculator } private boolean meetsRequirementsForA(int total) { - return total > POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion(); + return (total > POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion()); } private boolean hasPointsForDeadlineCriterion() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster30GradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster30GradeCalculator.java index 8af5903636..d41d20afd9 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster30GradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/AbstractMaster30GradeCalculator.java @@ -51,7 +51,7 @@ public abstract class AbstractMaster30GradeCalculator implements GradeCalculator } private boolean meetsRequirementsForA(int totalPoints) { - return totalPoints > POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion(); + return (totalPoints > POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion()); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/Calculation.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/Calculation.java index 5e8f7aed31..25c3251229 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/Calculation.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/Calculation.java @@ -20,8 +20,10 @@ public abstract class Calculation { } protected boolean fulfilledFxRequirements() { - return countFxFlaggedProjectCriteriaWithAtLeastOnePoint() >= getNumberOfProjectCriteriaRequiredToGetFx() - && countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() >= getNumberOfIndividualCriteriaRequiredToGetFx(); + return ( + countFxFlaggedProjectCriteriaWithAtLeastOnePoint() >= getNumberOfProjectCriteriaRequiredToGetFx() && + countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() >= getNumberOfIndividualCriteriaRequiredToGetFx() + ); } protected abstract GradingReport.Grade convertPointsToGrade(); @@ -71,7 +73,9 @@ public abstract class Calculation { protected int countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() { int completed = 0; for (GradingCriterion gradingCriterion : getGradingCriteria()) { - if (gradingCriterion.isFx() && gradingCriterion.getPoints() > 0 && gradingCriterion.isIndividualCriterion()) { + if ( + gradingCriterion.isFx() && gradingCriterion.getPoints() > 0 && gradingCriterion.isIndividualCriterion() + ) { completed++; } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculator.java index c4a0da5a9a..bb408e08db 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorBachelorGradeCalculator extends AbstractBachelorGradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculator.java index 7a721e4b72..a8c0db0188 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorMaster15GradeCalculator extends AbstractMaster15GradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculator.java index 19947b3ec1..4d6f152e79 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorMaster30GradeCalculator extends AbstractMaster30GradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractBachelorGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractBachelorGradeCalculator.java index 3105340080..20db21dd21 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractBachelorGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractBachelorGradeCalculator.java @@ -26,6 +26,7 @@ public abstract class AbstractBachelorGradeCalculator implements GradeCalculator public abstract Iterable getGradingCriteria(GradingReport gradingReport); private static class BachelorCalculation extends Calculation { + private final Iterable gradingCriteria; public BachelorCalculation(Iterable gradingCriteria) { @@ -71,6 +72,5 @@ public abstract class AbstractBachelorGradeCalculator implements GradeCalculator protected int getIndividualCriteriaPointsRequiredToGetFx() { return INDIVIDUAL_CRITERIA_POINTS_NEEDED_TO_GET_FX; } - } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMagisterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMagisterGradeCalculator.java index dbfa5d7c33..fc9bae2299 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMagisterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMagisterGradeCalculator.java @@ -50,7 +50,7 @@ public abstract class AbstractMagisterGradeCalculator implements GradeCalculator } private boolean meetsRequirementsForA(int total) { - return total >= POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion(); + return (total >= POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion()); } private boolean hasPointsForDeadlineCriterion() { diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMasterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMasterGradeCalculator.java index 5e1cb0352b..e8bad8944f 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMasterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/AbstractMasterGradeCalculator.java @@ -51,7 +51,7 @@ public abstract class AbstractMasterGradeCalculator implements GradeCalculator { } private boolean meetsRequirementsForA(int totalPoints) { - return totalPoints >= POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion(); + return (totalPoints >= POINTS_REQUIRED_FOR_A && hasPointsForDeadlineCriterion()); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/Calculation.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/Calculation.java index 99de270742..667acc6cbe 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/Calculation.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/Calculation.java @@ -20,8 +20,10 @@ public abstract class Calculation { } protected boolean fulfilledFxRequirements() { - return countFxFlaggedProjectCriteriaWithAtLeastOnePoint() >= getNumberOfProjectCriteriaRequiredToGetFx() - && countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() >= getIndividualCriteriaPointsRequiredToGetFx(); + return ( + countFxFlaggedProjectCriteriaWithAtLeastOnePoint() >= getNumberOfProjectCriteriaRequiredToGetFx() && + countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() >= getIndividualCriteriaPointsRequiredToGetFx() + ); } protected abstract GradingReport.Grade convertPointsToGrade(); @@ -71,7 +73,9 @@ public abstract class Calculation { protected int countFxFlaggedIndividualCriteriaWithAtLeastOnePoint() { int points = 0; for (GradingCriterion gradingCriterion : getGradingCriteria()) { - if (gradingCriterion.isFx() && gradingCriterion.getPoints() > 0 && gradingCriterion.isIndividualCriterion()) { + if ( + gradingCriterion.isFx() && gradingCriterion.getPoints() > 0 && gradingCriterion.isIndividualCriterion() + ) { points += gradingCriterion.getPoints(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerBachelorGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerBachelorGradeCalculator.java index 83c92b1354..54ccfeebaf 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerBachelorGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerBachelorGradeCalculator.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.report.calculators.vt17; -import se.su.dsv.scipro.report.GradingCriterion; -import se.su.dsv.scipro.report.GradingReport; -import se.su.dsv.scipro.report.SupervisorGradingReport; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.report.GradingCriterion; +import se.su.dsv.scipro.report.GradingReport; +import se.su.dsv.scipro.report.SupervisorGradingReport; public class ReviewerBachelorGradeCalculator extends AbstractBachelorGradeCalculator { diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMagisterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMagisterGradeCalculator.java index 6a99a27d02..d366440d99 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMagisterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMagisterGradeCalculator.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.report.calculators.vt17; -import se.su.dsv.scipro.report.GradingCriterion; -import se.su.dsv.scipro.report.GradingReport; -import se.su.dsv.scipro.report.SupervisorGradingReport; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.report.GradingCriterion; +import se.su.dsv.scipro.report.GradingReport; +import se.su.dsv.scipro.report.SupervisorGradingReport; public class ReviewerMagisterGradeCalculator extends AbstractMagisterGradeCalculator { diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMasterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMasterGradeCalculator.java index 58481f5fbf..c4561b6d65 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMasterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/ReviewerMasterGradeCalculator.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.report.calculators.vt17; -import se.su.dsv.scipro.report.GradingCriterion; -import se.su.dsv.scipro.report.GradingReport; -import se.su.dsv.scipro.report.SupervisorGradingReport; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.report.GradingCriterion; +import se.su.dsv.scipro.report.GradingReport; +import se.su.dsv.scipro.report.SupervisorGradingReport; public class ReviewerMasterGradeCalculator extends AbstractMasterGradeCalculator { diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorBachelorGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorBachelorGradeCalculator.java index a0bb7d4dd9..9b9501f1e5 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorBachelorGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorBachelorGradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorBachelorGradeCalculator extends AbstractBachelorGradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMagisterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMagisterGradeCalculator.java index e681ef6b70..8895aa4282 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMagisterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMagisterGradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorMagisterGradeCalculator extends AbstractMagisterGradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMasterGradeCalculator.java b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMasterGradeCalculator.java index 37eb94d778..44c37ea7d2 100644 --- a/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMasterGradeCalculator.java +++ b/core/src/main/java/se/su/dsv/scipro/report/calculators/vt17/SupervisorMasterGradeCalculator.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReport; public class SupervisorMasterGradeCalculator extends AbstractMasterGradeCalculator { + @Override public Iterable getGradingCriteria(GradingReport gradingReport) { return gradingReport.getGradingCriteria(); diff --git a/core/src/main/java/se/su/dsv/scipro/reusable/SciProUtilities.java b/core/src/main/java/se/su/dsv/scipro/reusable/SciProUtilities.java index cf5d8d8c26..0ed066a174 100755 --- a/core/src/main/java/se/su/dsv/scipro/reusable/SciProUtilities.java +++ b/core/src/main/java/se/su/dsv/scipro/reusable/SciProUtilities.java @@ -43,8 +43,7 @@ public final class SciProUtilities { */ public static int safeLongToInt(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { - throw new IllegalArgumentException - (l + " cannot be cast to int without changing its value."); + throw new IllegalArgumentException(l + " cannot be cast to int without changing its value."); } return (int) l; } @@ -80,8 +79,7 @@ public final class SciProUtilities { public static Calendar toCalendar(final LocalDate localDate) { if (localDate == null) { return null; - } - else { + } else { final Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth()); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/AbstractReviewerApprovalServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/AbstractReviewerApprovalServiceImpl.java index 39c3bfe513..5a4df0bad1 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/AbstractReviewerApprovalServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/AbstractReviewerApprovalServiceImpl.java @@ -1,44 +1,54 @@ -package se.su.dsv.scipro.reviewing; - -import com.google.common.eventbus.EventBus; -import com.querydsl.core.types.dsl.EntityPathBase; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileService; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.util.Either; - -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.*; - -abstract class AbstractReviewerApprovalServiceImpl extends AbstractServiceImpl implements ReviewerApprovalService { - - protected final FileService fileDescriptionService; - protected final EventBus eventBus; - - AbstractReviewerApprovalServiceImpl(Provider em, Class clazz, EntityPathBase path, final EventBus eventBus, final FileService fileDescriptionService) { - super(em, clazz, path); - this.eventBus = eventBus; - this.fileDescriptionService = fileDescriptionService; - } - - @Override - public boolean requiresUpload(final Project project) { - return findBy(project).map(ReviewerApproval::isRejected).orElse(Boolean.TRUE); - } - - protected Either addNewRequest(final String comment, final FileReference storedThesis, final T earlier) { - final Decision currentDecision = earlier.getCurrentDecision(); - if (currentDecision.getStatus() == Status.REJECTED) { - final Date deadline = getDeadline(new Date()); - earlier.addNewThesis(storedThesis, comment, deadline); - return Either.right(earlier); - } - else { - return Either.left(new AlreadyRequested(currentDecision)); - } - } - - protected abstract Date getDeadline(Date requested); -} +package se.su.dsv.scipro.reviewing; + +import com.google.common.eventbus.EventBus; +import com.querydsl.core.types.dsl.EntityPathBase; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.util.*; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileService; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.util.Either; + +abstract class AbstractReviewerApprovalServiceImpl + extends AbstractServiceImpl + implements ReviewerApprovalService { + + protected final FileService fileDescriptionService; + protected final EventBus eventBus; + + AbstractReviewerApprovalServiceImpl( + Provider em, + Class clazz, + EntityPathBase path, + final EventBus eventBus, + final FileService fileDescriptionService + ) { + super(em, clazz, path); + this.eventBus = eventBus; + this.fileDescriptionService = fileDescriptionService; + } + + @Override + public boolean requiresUpload(final Project project) { + return findBy(project).map(ReviewerApproval::isRejected).orElse(Boolean.TRUE); + } + + protected Either addNewRequest( + final String comment, + final FileReference storedThesis, + final T earlier + ) { + final Decision currentDecision = earlier.getCurrentDecision(); + if (currentDecision.getStatus() == Status.REJECTED) { + final Date deadline = getDeadline(new Date()); + earlier.addNewThesis(storedThesis, comment, deadline); + return Either.right(earlier); + } else { + return Either.left(new AlreadyRequested(currentDecision)); + } + } + + protected abstract Date getDeadline(Date requested); +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/AlreadyRequested.java b/core/src/main/java/se/su/dsv/scipro/reviewing/AlreadyRequested.java index 96cc818559..45c28b2f79 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/AlreadyRequested.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/AlreadyRequested.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.reviewing; public class AlreadyRequested { + private final Decision decision; public AlreadyRequested(final Decision decision) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/Decision.java b/core/src/main/java/se/su/dsv/scipro/reviewing/Decision.java index 6d3fb25f16..67d701cdc9 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/Decision.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/Decision.java @@ -1,14 +1,12 @@ package se.su.dsv.scipro.reviewing; -import jakarta.persistence.Column; -import jakarta.persistence.GenerationType; -import se.su.dsv.scipro.file.FileReference; - import jakarta.persistence.Basic; +import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; @@ -16,16 +14,17 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; -import se.su.dsv.scipro.system.User; - import java.time.Instant; import java.time.LocalDate; import java.util.Date; import java.util.Optional; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "decision") public class Decision { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -93,7 +92,13 @@ public class Decision { this(reviewerApproval, thesis, Instant.now(), comment, deadline); } - Decision(ReviewerApproval reviewerApproval, final FileReference thesis, final Instant requested, final String comment, final Date deadline) { + Decision( + ReviewerApproval reviewerApproval, + final FileReference thesis, + final Instant requested, + final String comment, + final Date deadline + ) { this.reviewerApproval = reviewerApproval; this.thesis = thesis; this.requested = Date.from(requested); @@ -191,7 +196,12 @@ public class Decision { decideWithDecisionDate(status, reason, attachment, Instant.now()); } - private void decideWithDecisionDate(final Status status, final String reason, final Optional attachment, final Instant decisionDate) { + private void decideWithDecisionDate( + final Status status, + final String reason, + final Optional attachment, + final Instant decisionDate + ) { if (this.status != Status.UNDECIDED) { throw new IllegalStateException(); } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepository.java b/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepository.java index f27798992f..ee7a1a2581 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.time.LocalDate; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; public interface DecisionRepository { int countUniqueProjectsWithDecision(User reviewer, LocalDate fromDate, LocalDate toDate); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepositoryImpl.java index cd05696c0c..5843cf3335 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/DecisionRepositoryImpl.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.reviewing; +import jakarta.inject.Inject; +import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import java.time.LocalDate; +import java.util.List; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.AbstractRepository; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.time.LocalDate; -import java.util.List; - public class DecisionRepositoryImpl extends AbstractRepository implements DecisionRepository { + @Inject public DecisionRepositoryImpl(Provider em) { super(em); @@ -20,17 +20,18 @@ public class DecisionRepositoryImpl extends AbstractRepository implements Decisi public int countUniqueProjectsWithDecision(User reviewer, LocalDate fromDate, LocalDate toDate) { return (int) from(QDecision.decision) .select(QDecision.decision.reviewerApproval.id) - .where(QDecision.decision.assignedReviewer.eq(reviewer) - .and(QDecision.decision.reviewerAssignedAt.goe(fromDate)) - .and(QDecision.decision.reviewerAssignedAt.loe(toDate))) + .where( + QDecision.decision.assignedReviewer + .eq(reviewer) + .and(QDecision.decision.reviewerAssignedAt.goe(fromDate)) + .and(QDecision.decision.reviewerAssignedAt.loe(toDate)) + ) .distinct() .fetchCount(); } @Override public List findBy(Project project) { - return from(QDecision.decision) - .where(QDecision.decision.reviewerApproval.project.eq(project)) - .fetch(); + return from(QDecision.decision).where(QDecision.decision.reviewerApproval.project.eq(project)).fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApproval.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApproval.java index ca8bc179b9..09501b4885 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApproval.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApproval.java @@ -1,17 +1,21 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; - import jakarta.persistence.Entity; import java.util.*; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; @Entity public class FinalSeminarApproval extends ReviewerApproval { protected FinalSeminarApproval() {} // JPA - public FinalSeminarApproval(final Project project, final FileReference thesis, final String comment, final Date deadline) { + public FinalSeminarApproval( + final Project project, + final FileReference thesis, + final String comment, + final Date deadline + ) { this.project = project; this.decisions.add(new Decision(this, thesis, comment, deadline)); } @@ -20,5 +24,4 @@ public class FinalSeminarApproval extends ReviewerApproval { public Step getStep() { return Step.FINAL_SEMINAR_APPROVAL; } - } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalApprovedEvent.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalApprovedEvent.java index fa90290525..cd2e492bd3 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalApprovedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalApprovedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.project.Project; public final class FinalSeminarApprovalApprovedEvent { + private final ReviewerApproval process; public FinalSeminarApprovalApprovedEvent(final ReviewerApproval process) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRejectedEvent.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRejectedEvent.java index 2ab3d4742f..b2a3ed0b72 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRejectedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRejectedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.project.Project; public class FinalSeminarApprovalRejectedEvent { + private final Project project; public FinalSeminarApprovalRejectedEvent(final Project project) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRequestEvent.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRequestEvent.java index 0f04008d36..00e8ed979c 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRequestEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalRequestEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.project.Project; public class FinalSeminarApprovalRequestEvent { + private final FinalSeminarApproval finalSeminarApproval; public FinalSeminarApprovalRequestEvent(final FinalSeminarApproval finalSeminarApproval) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalService.java index 94b9cee1b0..2b72f36a30 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalService.java @@ -3,7 +3,5 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.project.Project; public interface FinalSeminarApprovalService extends ReviewerApprovalService { - FinalSeminarApproval findByProject(Project project); - } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImpl.java index fec755260c..05190c4e4a 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImpl.java @@ -1,7 +1,12 @@ package se.su.dsv.scipro.reviewing; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; +import java.util.Date; +import java.util.Optional; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.file.FileUpload; @@ -9,41 +14,46 @@ import se.su.dsv.scipro.misc.DaysService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.Date; -import java.util.Optional; - -public class FinalSeminarApprovalServiceImpl extends AbstractReviewerApprovalServiceImpl implements FinalSeminarApprovalService { +public class FinalSeminarApprovalServiceImpl + extends AbstractReviewerApprovalServiceImpl + implements FinalSeminarApprovalService { private final DaysService daysService; private final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService; @Inject public FinalSeminarApprovalServiceImpl( - final Provider em, - final FileService fileDescriptionService, - final EventBus eventBus, - final DaysService daysService, - final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService) - { - super(em, FinalSeminarApproval.class, QFinalSeminarApproval.finalSeminarApproval, eventBus, fileDescriptionService); + final Provider em, + final FileService fileDescriptionService, + final EventBus eventBus, + final DaysService daysService, + final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService + ) { + super( + em, + FinalSeminarApproval.class, + QFinalSeminarApproval.finalSeminarApproval, + eventBus, + fileDescriptionService + ); this.daysService = daysService; this.reviewerDeadlineSettingsService = reviewerDeadlineSettingsService; } @Override @Transactional - public Either requestApproval(final Project project, FileUpload thesis, final String comment) { + public Either requestApproval( + final Project project, + FileUpload thesis, + final String comment + ) { final FileReference storedThesis = fileDescriptionService.storeFile(thesis); final Either finalSeminarApproval = findBy(project) - .map(earlier -> addNewRequest(comment, storedThesis, earlier)) - .orElseGet(() -> Either.right(newApproval(project, storedThesis, comment))); + .map(earlier -> addNewRequest(comment, storedThesis, earlier)) + .orElseGet(() -> Either.right(newApproval(project, storedThesis, comment))); - final Either persisted = - finalSeminarApproval.map(this::save); + final Either persisted = finalSeminarApproval.map(this::save); persisted.foreach(fsa -> eventBus.post(new FinalSeminarApprovalRequestEvent(fsa))); return persisted; } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/MyReviewService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/MyReviewService.java index e95b5fe670..32433dd3b3 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/MyReviewService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/MyReviewService.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.Page; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Collection; import java.util.List; +import se.su.dsv.scipro.system.Page; +import se.su.dsv.scipro.system.User; public interface MyReviewService { List findAllDecisions(Filter filter, final Page pageable); @@ -15,10 +14,14 @@ public interface MyReviewService { Decision findDecision(Long id); enum Sort { - REQUESTED, DEADLINE, TITLE, SUPERVISOR + REQUESTED, + DEADLINE, + TITLE, + SUPERVISOR, } - class Filter implements Serializable{ + class Filter implements Serializable { + private User user; private boolean showAll; private ReviewerApproval.Step step; diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/NewReviewerInteractionMessage.java b/core/src/main/java/se/su/dsv/scipro/reviewing/NewReviewerInteractionMessage.java index b3165a270f..66bd92ff4f 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/NewReviewerInteractionMessage.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/NewReviewerInteractionMessage.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.project.Project; public final class NewReviewerInteractionMessage { + private final Project project; private final ForumPost message; diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ProjectFinalSeminarStatisticsService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ProjectFinalSeminarStatisticsService.java index 1556cfe7a3..96de74e37d 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ProjectFinalSeminarStatisticsService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ProjectFinalSeminarStatisticsService.java @@ -1,23 +1,26 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.system.GenericService; -import se.su.dsv.scipro.system.ProjectType; - import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; public interface ProjectFinalSeminarStatisticsService extends GenericService { Long countFinalSeminarStatistics(ProjectFinalSeminarStatisticsService.Filter filter); Long countFinalSeminarStatisticsOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter); - Iterable finalSeminarStatisticsNoOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter, Pageable pageable); + Iterable finalSeminarStatisticsNoOkFromReviewer( + ProjectFinalSeminarStatisticsService.Filter filter, + Pageable pageable + ); Long countFinalSeminarStatisticsNoOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter); class Filter implements Serializable { + private Collection projectTypes; private Date createdAfter; private Date createdBefore; @@ -78,13 +81,15 @@ public interface ProjectFinalSeminarStatisticsService extends GenericService implements ProjectFinalSeminarStatisticsService { +public class ProjectFinalSeminarStatisticsServiceImpl + extends AbstractServiceImpl + implements ProjectFinalSeminarStatisticsService { @Inject public ProjectFinalSeminarStatisticsServiceImpl(Provider em) { @@ -34,62 +35,68 @@ public class ProjectFinalSeminarStatisticsServiceImpl extends AbstractServiceImp @Override public Long countFinalSeminarStatistics(ProjectFinalSeminarStatisticsService.Filter filter) { return new JPAQuery<>(em()) - .select(QProject.project.count()) - .from(QProject.project, QFinalSeminar.finalSeminar) - .where(toPredicate(filter)) - .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) - .fetchFirst(); + .select(QProject.project.count()) + .from(QProject.project, QFinalSeminar.finalSeminar) + .where(toPredicate(filter)) + .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) + .fetchFirst(); } @Override public Long countFinalSeminarStatisticsOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter) { return new JPAQuery<>(em()) - .select(QProject.project.count()) - .from(QProject.project, QFinalSeminar.finalSeminar, QFinalSeminarApproval.finalSeminarApproval) - .where(toPredicate(filter)) - .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) - .where(QFinalSeminarApproval.finalSeminarApproval.project.eq(QProject.project), - QFinalSeminarApproval.finalSeminarApproval.instanceOf(FinalSeminarApproval.class), - QFinalSeminarApproval.finalSeminarApproval.decisions.any().status.eq(Status.APPROVED)) - .fetchFirst(); + .select(QProject.project.count()) + .from(QProject.project, QFinalSeminar.finalSeminar, QFinalSeminarApproval.finalSeminarApproval) + .where(toPredicate(filter)) + .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) + .where( + QFinalSeminarApproval.finalSeminarApproval.project.eq(QProject.project), + QFinalSeminarApproval.finalSeminarApproval.instanceOf(FinalSeminarApproval.class), + QFinalSeminarApproval.finalSeminarApproval.decisions.any().status.eq(Status.APPROVED) + ) + .fetchFirst(); } @Override - public Iterable finalSeminarStatisticsNoOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter, Pageable pageable) { + public Iterable finalSeminarStatisticsNoOkFromReviewer( + ProjectFinalSeminarStatisticsService.Filter filter, + Pageable pageable + ) { StringPath sort = Expressions.stringPath(QProject.project, pageable.getSort().getProperty()); return new JPAQuery<>(em()) - .select(QProject.project) - .from(QProject.project, QFinalSeminar.finalSeminar) - .where(toPredicate(filter)) - .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) - .where(noOk()) - .offset(pageable.getOffset()) - .limit(pageable.getLimit()) - .orderBy(pageable.getSort().isAscending() ? sort.asc() : sort.desc()) - .fetch(); + .select(QProject.project) + .from(QProject.project, QFinalSeminar.finalSeminar) + .where(toPredicate(filter)) + .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) + .where(noOk()) + .offset(pageable.getOffset()) + .limit(pageable.getLimit()) + .orderBy(pageable.getSort().isAscending() ? sort.asc() : sort.desc()) + .fetch(); } private BooleanExpression noOk() { return anyOf( - QProject.project.notIn(JPAExpressions - .select(QFinalSeminarApproval.finalSeminarApproval.project) - .from(QFinalSeminarApproval.finalSeminarApproval) - .where(QFinalSeminarApproval.finalSeminarApproval.decisions.any().status.eq(Status.APPROVED))), - JPAExpressions - .selectFrom(QFinalSeminarApproval.finalSeminarApproval) - .where(QFinalSeminarApproval.finalSeminarApproval.project.eq(QProject.project)) - .notExists()); + QProject.project.notIn( + JPAExpressions.select(QFinalSeminarApproval.finalSeminarApproval.project) + .from(QFinalSeminarApproval.finalSeminarApproval) + .where(QFinalSeminarApproval.finalSeminarApproval.decisions.any().status.eq(Status.APPROVED)) + ), + JPAExpressions.selectFrom(QFinalSeminarApproval.finalSeminarApproval) + .where(QFinalSeminarApproval.finalSeminarApproval.project.eq(QProject.project)) + .notExists() + ); } @Override public Long countFinalSeminarStatisticsNoOkFromReviewer(ProjectFinalSeminarStatisticsService.Filter filter) { return new JPAQuery<>(em()) - .select(QProject.project.count()) - .from(QProject.project, QFinalSeminar.finalSeminar) - .where(toPredicate(filter)) - .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) - .where(noOk()) - .fetchFirst(); + .select(QProject.project.count()) + .from(QProject.project, QFinalSeminar.finalSeminar) + .where(toPredicate(filter)) + .where(QFinalSeminar.finalSeminar.project.eq(QProject.project)) + .where(noOk()) + .fetchFirst(); } private static Predicate toPredicate(final Filter filter) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewPeriod.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewPeriod.java index f8d03a7045..1d0421c983 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewPeriod.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewPeriod.java @@ -3,5 +3,8 @@ package se.su.dsv.scipro.reviewing; import java.time.Year; public record ReviewPeriod(Year year, Part part) { - public enum Part { SPRING, AUTUMN } + public enum Part { + SPRING, + AUTUMN, + } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApproval.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApproval.java index cdad680797..9e91d2fca1 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApproval.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApproval.java @@ -1,128 +1,129 @@ -package se.su.dsv.scipro.reviewing; - -import jakarta.persistence.GenerationType; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.Table; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DomainObject; - -import jakarta.persistence.CascadeType; -import jakarta.persistence.DiscriminatorColumn; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.OneToMany; -import jakarta.persistence.OneToOne; -import jakarta.persistence.OrderBy; - -import java.util.Collections; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -@Entity -@Table(name = "reviewer_approval") -@DiscriminatorColumn(name = "type", length = 64) -public abstract class ReviewerApproval extends DomainObject { - // ---------------------------------------------------------------------------------- - // Basic JPA-mappings - // ---------------------------------------------------------------------------------- - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - // ---------------------------------------------------------------------------------- - // JPA-mappings of foreign keys in this table (reviewer_approval) referencing other - // tables. - // ---------------------------------------------------------------------------------- - @OneToOne(optional = false) - @JoinColumn(name = "project_id", referencedColumnName = "id") - protected Project project; - - // ---------------------------------------------------------------------------------- - // JPA-mappings of other tables referencing to this table "reviewer_approval" - // ---------------------------------------------------------------------------------- - @OneToMany(mappedBy = "reviewerApproval", cascade = CascadeType.ALL) - @OrderBy("requested desc") - protected List decisions = new LinkedList<>(); - - // ---------------------------------------------------------------------------------- - // Properties (Getters and Setters) - // ---------------------------------------------------------------------------------- - @Override - public Long getId() { - return this.id; - } - - public Project getProject(){return this.project;} - - // ---------------------------------------------------------------------------------- - // Other methods - // ---------------------------------------------------------------------------------- - public abstract Step getStep(); - - public Decision getCurrentDecision() { - return decisions.get(0); - } - - public FileReference getCurrentThesis() { - return getCurrentDecision().getThesis(); - } - - public Status getCurrentStatus() { - return getCurrentDecision().getStatus(); - } - - public boolean isDecided() { - return getCurrentStatus() != Status.UNDECIDED; - } - - public String getCurrentReason() { - return getCurrentDecision().getReason(); - } - - public Optional getCurrentAttachment() { - return getCurrentDecision().getAttachment(); - } - - public void approve(final String reason, final Optional attachment) { - getCurrentDecision().approve(reason, attachment); - } - - public void reject(final String reason, final Optional attachment) { - getCurrentDecision().reject(reason, attachment); - } - - public void addNewThesis(final FileReference thesis, final String comment, final Date deadline) { - if (getCurrentStatus() != Status.REJECTED) { - throw new IllegalStateException(); - } - this.decisions.add(0, new Decision(this, thesis, comment, deadline)); - } - - public List getHistory() { - return Collections.unmodifiableList(decisions); - } - - public boolean isRejected() { - return getCurrentStatus() == Status.REJECTED; - } - - public boolean isApproved() { - return getCurrentStatus() == Status.APPROVED; - } - - public Date getCurrentDeadline() { - return getCurrentDecision().getDeadline(); - } - - // ---------------------------------------------------------------------------------- - // Nested types. - // ---------------------------------------------------------------------------------- - public enum Step { - ROUGH_DRAFT_APPROVAL, - FINAL_SEMINAR_APPROVAL - } -} +package se.su.dsv.scipro.reviewing; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.DiscriminatorColumn; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import jakarta.persistence.OrderBy; +import jakarta.persistence.Table; +import java.util.Collections; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DomainObject; + +@Entity +@Table(name = "reviewer_approval") +@DiscriminatorColumn(name = "type", length = 64) +public abstract class ReviewerApproval extends DomainObject { + + // ---------------------------------------------------------------------------------- + // Basic JPA-mappings + // ---------------------------------------------------------------------------------- + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // ---------------------------------------------------------------------------------- + // JPA-mappings of foreign keys in this table (reviewer_approval) referencing other + // tables. + // ---------------------------------------------------------------------------------- + @OneToOne(optional = false) + @JoinColumn(name = "project_id", referencedColumnName = "id") + protected Project project; + + // ---------------------------------------------------------------------------------- + // JPA-mappings of other tables referencing to this table "reviewer_approval" + // ---------------------------------------------------------------------------------- + @OneToMany(mappedBy = "reviewerApproval", cascade = CascadeType.ALL) + @OrderBy("requested desc") + protected List decisions = new LinkedList<>(); + + // ---------------------------------------------------------------------------------- + // Properties (Getters and Setters) + // ---------------------------------------------------------------------------------- + @Override + public Long getId() { + return this.id; + } + + public Project getProject() { + return this.project; + } + + // ---------------------------------------------------------------------------------- + // Other methods + // ---------------------------------------------------------------------------------- + public abstract Step getStep(); + + public Decision getCurrentDecision() { + return decisions.get(0); + } + + public FileReference getCurrentThesis() { + return getCurrentDecision().getThesis(); + } + + public Status getCurrentStatus() { + return getCurrentDecision().getStatus(); + } + + public boolean isDecided() { + return getCurrentStatus() != Status.UNDECIDED; + } + + public String getCurrentReason() { + return getCurrentDecision().getReason(); + } + + public Optional getCurrentAttachment() { + return getCurrentDecision().getAttachment(); + } + + public void approve(final String reason, final Optional attachment) { + getCurrentDecision().approve(reason, attachment); + } + + public void reject(final String reason, final Optional attachment) { + getCurrentDecision().reject(reason, attachment); + } + + public void addNewThesis(final FileReference thesis, final String comment, final Date deadline) { + if (getCurrentStatus() != Status.REJECTED) { + throw new IllegalStateException(); + } + this.decisions.add(0, new Decision(this, thesis, comment, deadline)); + } + + public List getHistory() { + return Collections.unmodifiableList(decisions); + } + + public boolean isRejected() { + return getCurrentStatus() == Status.REJECTED; + } + + public boolean isApproved() { + return getCurrentStatus() == Status.APPROVED; + } + + public Date getCurrentDeadline() { + return getCurrentDecision().getDeadline(); + } + + // ---------------------------------------------------------------------------------- + // Nested types. + // ---------------------------------------------------------------------------------- + public enum Step { + ROUGH_DRAFT_APPROVAL, + FINAL_SEMINAR_APPROVAL, + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApprovalService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApprovalService.java index 963dd91bc7..4abbb6afaa 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApprovalService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerApprovalService.java @@ -1,15 +1,14 @@ -package se.su.dsv.scipro.reviewing; - -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.util.Either; - -import java.util.Optional; - -public interface ReviewerApprovalService { - Either requestApproval(Project project, FileUpload thesis, String comment); - - Optional findBy(Project project); - - boolean requiresUpload(Project project); -} +package se.su.dsv.scipro.reviewing; + +import java.util.Optional; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.util.Either; + +public interface ReviewerApprovalService { + Either requestApproval(Project project, FileUpload thesis, String comment); + + Optional findBy(Project project); + + boolean requiresUpload(Project project); +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignedDeadline.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignedDeadline.java index 3e1c8bf390..f45c8bbb55 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignedDeadline.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignedDeadline.java @@ -2,19 +2,19 @@ package se.su.dsv.scipro.reviewing; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; -import se.su.dsv.scipro.misc.DaysService; -import se.su.dsv.scipro.project.ReviewerAssignedEvent; -import se.su.dsv.scipro.project.ReviewerUnassignedEvent; -import se.su.dsv.scipro.reviewing.*; - import jakarta.inject.Inject; import jakarta.inject.Singleton; import java.time.Clock; import java.time.LocalDate; import java.util.Date; +import se.su.dsv.scipro.misc.DaysService; +import se.su.dsv.scipro.project.ReviewerAssignedEvent; +import se.su.dsv.scipro.project.ReviewerUnassignedEvent; +import se.su.dsv.scipro.reviewing.*; @Singleton public class ReviewerAssignedDeadline { + private final RoughDraftApprovalService roughDraftApprovalService; private final FinalSeminarApprovalService finalSeminarApprovalService; private final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService; @@ -22,12 +22,12 @@ public class ReviewerAssignedDeadline { private final Clock clock; ReviewerAssignedDeadline( - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService, - ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, - DaysService daysService, - Clock clock) - { + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService, + ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, + DaysService daysService, + Clock clock + ) { this.roughDraftApprovalService = roughDraftApprovalService; this.finalSeminarApprovalService = finalSeminarApprovalService; this.reviewerDeadlineSettingsService = reviewerDeadlineSettingsService; @@ -37,14 +37,20 @@ public class ReviewerAssignedDeadline { @Inject public ReviewerAssignedDeadline( - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService, - ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, - DaysService daysService, - EventBus eventBus, - Clock clock) - { - this(roughDraftApprovalService, finalSeminarApprovalService, reviewerDeadlineSettingsService, daysService, clock); + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService, + ReviewerDeadlineSettingsService reviewerDeadlineSettingsService, + DaysService daysService, + EventBus eventBus, + Clock clock + ) { + this( + roughDraftApprovalService, + finalSeminarApprovalService, + reviewerDeadlineSettingsService, + daysService, + clock + ); eventBus.register(this); } @@ -52,46 +58,50 @@ public class ReviewerAssignedDeadline { public void reviewerAssigned(ReviewerAssignedEvent event) { ReviewerDeadlineSettings deadlineSettings = reviewerDeadlineSettingsService.getInstance(); - roughDraftApprovalService.findBy(event.getProject()) - .filter(rda -> !rda.isDecided()) - .map(ReviewerApproval::getCurrentDecision) - .ifPresent(currentDecision -> { - Date deadline = getDeadline(deadlineSettings.getRoughDraftApproval()); - currentDecision.setDeadline(deadline); - currentDecision.setAssignedReviewer(event.getReviewer()); - currentDecision.setReviewerAssignedAt(LocalDate.now(clock)); - }); + roughDraftApprovalService + .findBy(event.getProject()) + .filter(rda -> !rda.isDecided()) + .map(ReviewerApproval::getCurrentDecision) + .ifPresent(currentDecision -> { + Date deadline = getDeadline(deadlineSettings.getRoughDraftApproval()); + currentDecision.setDeadline(deadline); + currentDecision.setAssignedReviewer(event.getReviewer()); + currentDecision.setReviewerAssignedAt(LocalDate.now(clock)); + }); - finalSeminarApprovalService.findBy(event.getProject()) - .filter(fsa -> !fsa.isDecided()) - .map(ReviewerApproval::getCurrentDecision) - .ifPresent(currentDecision -> { - Date deadline = getDeadline(deadlineSettings.getFinalSeminarApproval()); - currentDecision.setDeadline(deadline); - currentDecision.setAssignedReviewer(event.getReviewer()); - currentDecision.setReviewerAssignedAt(LocalDate.now(clock)); - }); + finalSeminarApprovalService + .findBy(event.getProject()) + .filter(fsa -> !fsa.isDecided()) + .map(ReviewerApproval::getCurrentDecision) + .ifPresent(currentDecision -> { + Date deadline = getDeadline(deadlineSettings.getFinalSeminarApproval()); + currentDecision.setDeadline(deadline); + currentDecision.setAssignedReviewer(event.getReviewer()); + currentDecision.setReviewerAssignedAt(LocalDate.now(clock)); + }); } @Subscribe public void reviewerUnassigned(ReviewerUnassignedEvent event) { - roughDraftApprovalService.findBy(event.project()) - .filter(rda -> !rda.isDecided()) - .map(ReviewerApproval::getCurrentDecision) - .ifPresent(currentDecision -> { - currentDecision.setDeadline(null); - currentDecision.setAssignedReviewer(null); - currentDecision.setReviewerAssignedAt(null); - }); + roughDraftApprovalService + .findBy(event.project()) + .filter(rda -> !rda.isDecided()) + .map(ReviewerApproval::getCurrentDecision) + .ifPresent(currentDecision -> { + currentDecision.setDeadline(null); + currentDecision.setAssignedReviewer(null); + currentDecision.setReviewerAssignedAt(null); + }); - finalSeminarApprovalService.findBy(event.project()) - .filter(fsa -> !fsa.isDecided()) - .map(ReviewerApproval::getCurrentDecision) - .ifPresent(currentDecision -> { - currentDecision.setDeadline(null); - currentDecision.setAssignedReviewer(null); - currentDecision.setReviewerAssignedAt(null); - }); + finalSeminarApprovalService + .findBy(event.project()) + .filter(fsa -> !fsa.isDecided()) + .map(ReviewerApproval::getCurrentDecision) + .ifPresent(currentDecision -> { + currentDecision.setDeadline(null); + currentDecision.setAssignedReviewer(null); + currentDecision.setReviewerAssignedAt(null); + }); } @Subscribe diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignmentService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignmentService.java index 4ccf1720da..ff9d6a8cba 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignmentService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerAssignmentService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.reviewing; +import java.time.LocalDate; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; - public interface ReviewerAssignmentService { ReviewerCandidates getCandidatesToReview(Project project, LocalDate date); @@ -17,6 +16,9 @@ public interface ReviewerAssignmentService { record CurrentTarget(int target, int assigned) {} enum ReviewerAssignment { - OK, ERROR_IS_SUPERVISOR, WARNING_NO_REVIEW_REQUEST, ERROR_IS_NOT_REVIEWER + OK, + ERROR_IS_SUPERVISOR, + WARNING_NO_REVIEW_REQUEST, + ERROR_IS_NOT_REVIEWER, } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCandidates.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCandidates.java index 2b2bdf9b84..792497d95e 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCandidates.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCandidates.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.User; - import java.util.List; +import se.su.dsv.scipro.system.User; /** * Candidates that can review a project. @@ -13,13 +12,13 @@ import java.util.List; * @param unavailable reviewers that are not available */ public record ReviewerCandidates( - ReviewPeriod period, - List good, - List wrongResearchArea, - List wrongLanguage, - List busy, - List unavailable) -{ + ReviewPeriod period, + List good, + List wrongResearchArea, + List wrongLanguage, + List busy, + List unavailable +) { public record Candidate(User reviewer, int target, int assigned, String note) { public int remainingTargets() { return target - assigned; diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityService.java index d2eebc1e24..70064e2a95 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.Unit; -import se.su.dsv.scipro.system.User; - import java.time.Year; import java.util.List; +import se.su.dsv.scipro.system.Unit; +import se.su.dsv.scipro.system.User; public interface ReviewerCapacityService { record Target(Year year, int spring, int autumn, String note) {} @@ -39,4 +38,4 @@ public interface ReviewerCapacityService { RemainingTargets getRemainingTargets(User reviewer, Year year); record RemainingTargets(int spring, int autumn) {} -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImpl.java index 08e67aa38b..627ff612a5 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImpl.java @@ -1,18 +1,8 @@ package se.su.dsv.scipro.reviewing; import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectService; -import se.su.dsv.scipro.project.ReviewerAssignedEvent; -import se.su.dsv.scipro.project.ReviewerUnassignedEvent; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.Language; -import se.su.dsv.scipro.system.Unit; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.system.UserService; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import java.time.LocalDate; import java.time.Month; import java.time.Year; @@ -24,8 +14,18 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectService; +import se.su.dsv.scipro.project.ReviewerAssignedEvent; +import se.su.dsv.scipro.project.ReviewerUnassignedEvent; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.system.Language; +import se.su.dsv.scipro.system.Unit; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.system.UserService; public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, ReviewerAssignmentService { + private final ReviewerTargetRepository reviewerTargetRepository; private final DecisionRepository decisionRepository; private final UserService userService; @@ -34,12 +34,12 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev @Inject public ReviewerCapacityServiceImpl( - ReviewerTargetRepository reviewerTargetRepository, - DecisionRepository decisionRepository, - UserService userService, - ProjectService projectService, - EventBus eventBus) - { + ReviewerTargetRepository reviewerTargetRepository, + DecisionRepository decisionRepository, + UserService userService, + ProjectService projectService, + EventBus eventBus + ) { this.reviewerTargetRepository = reviewerTargetRepository; this.decisionRepository = decisionRepository; this.userService = userService; @@ -56,8 +56,7 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev targetToUpdate.setAutumn(target.autumn()); targetToUpdate.setNote(target.note()); reviewerTargetRepository.save(targetToUpdate); - } - else { + } else { ReviewerTarget reviewerTargetToSave = new ReviewerTarget(); reviewerTargetToSave.setReviewer(reviewer); reviewerTargetToSave.setYear(target.year().getValue()); @@ -70,12 +69,13 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev @Override public List getUnitsWithReviewers() { - return userService.findActiveReviewers() - .stream() - .map(User::getUnit) - .distinct() - .sorted(Comparator.comparing(Unit::getTitle)) - .toList(); + return userService + .findActiveReviewers() + .stream() + .map(User::getUnit) + .distinct() + .sorted(Comparator.comparing(Unit::getTitle)) + .toList(); } @Override @@ -85,37 +85,45 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev @Override public List getActiveReviewersOnUnit(Unit unit) { - return userService.findActiveReviewers() - .stream() - .filter(reviewer -> Objects.equals(reviewer.getUnit(), unit)) - .toList(); + return userService + .findActiveReviewers() + .stream() + .filter(reviewer -> Objects.equals(reviewer.getUnit(), unit)) + .toList(); } @Override public Target getTarget(User reviewer, Year year) { - return reviewerTargetRepository.getReviewerTarget(reviewer, year) - .map(reviewerTarget -> new Target(year, reviewerTarget.getSpring(), reviewerTarget.getAutumn(), reviewerTarget.getNote())) - .orElse(new Target(year, 0, 0, "")); + return reviewerTargetRepository + .getReviewerTarget(reviewer, year) + .map(reviewerTarget -> + new Target(year, reviewerTarget.getSpring(), reviewerTarget.getAutumn(), reviewerTarget.getNote()) + ) + .orElse(new Target(year, 0, 0, "")); } @Override public List getTargetHistory(User reviewer, Year year) { return Stream.iterate(year, y -> y.minusYears(1)) - .skip(1) // skip given year - .limit(3) // get three years - .map(historicYear -> { - Optional reviewerTarget = reviewerTargetRepository.getReviewerTarget(reviewer, historicYear); - int completedInSpring = countSpringReviews(reviewer, historicYear); - int completedInAutumn = countAutumnReviews(reviewer, historicYear); - return new TargetHistory( - historicYear, - reviewerTarget.map(ReviewerTarget::getSpring).orElse(0), - reviewerTarget.map(ReviewerTarget::getAutumn).orElse(0), - completedInSpring, - completedInAutumn); - }) - .sorted(Comparator.comparing(TargetHistory::year).reversed()) - .toList(); + .skip(1) // skip given year + .limit(3) // get three years + .map(historicYear -> { + Optional reviewerTarget = reviewerTargetRepository.getReviewerTarget( + reviewer, + historicYear + ); + int completedInSpring = countSpringReviews(reviewer, historicYear); + int completedInAutumn = countAutumnReviews(reviewer, historicYear); + return new TargetHistory( + historicYear, + reviewerTarget.map(ReviewerTarget::getSpring).orElse(0), + reviewerTarget.map(ReviewerTarget::getAutumn).orElse(0), + completedInSpring, + completedInAutumn + ); + }) + .sorted(Comparator.comparing(TargetHistory::year).reversed()) + .toList(); } @Override @@ -163,47 +171,44 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev if (target > 0) { if (assigned < target) { boolean canReviewAllLanguages = reviewer.getLanguages().containsAll(EnumSet.allOf(Language.class)); - boolean canSuperviseProjectsLanguage = canReviewAllLanguages || reviewer.getLanguages().contains(project.getLanguage()); + boolean canSuperviseProjectsLanguage = + canReviewAllLanguages || reviewer.getLanguages().contains(project.getLanguage()); boolean matchingResearchArea = reviewer.getResearchAreas().contains(project.getResearchArea()); if (canSuperviseProjectsLanguage && matchingResearchArea) { good.add(candidate); - } - else if (!canSuperviseProjectsLanguage) { + } else if (!canSuperviseProjectsLanguage) { wrongLanguage.add(candidate); - } - else if (!matchingResearchArea) { + } else if (!matchingResearchArea) { wrongResearchArea.add(candidate); } - } - else { + } else { busy.add(candidate); } - } - else { + } else { unavailable.add(candidate); } } Comparator byLastName = Comparator.comparing( - ReviewerCandidates.Candidate::reviewer, - Comparator.comparing(User::getLastName)); - Comparator byNumberOfResearchAreas = Comparator.comparing( - candidate -> candidate.reviewer().getResearchAreas().size()); + ReviewerCandidates.Candidate::reviewer, + Comparator.comparing(User::getLastName) + ); + Comparator byNumberOfResearchAreas = Comparator.comparing(candidate -> + candidate.reviewer().getResearchAreas().size() + ); Comparator byRemainingTargets = Comparator.comparing( - ReviewerCandidates.Candidate::remainingTargets); + ReviewerCandidates.Candidate::remainingTargets + ); - good.sort(byRemainingTargets.reversed() - .thenComparing(byNumberOfResearchAreas) - .thenComparing(byLastName)); - wrongResearchArea.sort(byRemainingTargets.reversed() - .thenComparing(byLastName)); + good.sort(byRemainingTargets.reversed().thenComparing(byNumberOfResearchAreas).thenComparing(byLastName)); + wrongResearchArea.sort(byRemainingTargets.reversed().thenComparing(byLastName)); busy.sort(byLastName); unavailable.sort(byLastName); wrongLanguage.sort(byLastName); ReviewPeriod reviewPeriod = !date.isAfter(endOfSpring(date.getYear())) - ? new ReviewPeriod(Year.of(date.getYear()), ReviewPeriod.Part.SPRING) - : new ReviewPeriod(Year.of(date.getYear()), ReviewPeriod.Part.AUTUMN); + ? new ReviewPeriod(Year.of(date.getYear()), ReviewPeriod.Part.SPRING) + : new ReviewPeriod(Year.of(date.getYear()), ReviewPeriod.Part.AUTUMN); return new ReviewerCandidates(reviewPeriod, good, wrongResearchArea, wrongLanguage, busy, unavailable); } @@ -244,17 +249,14 @@ public class ReviewerCapacityServiceImpl implements ReviewerCapacityService, Rev @Override public CurrentTarget getCurrentTarget(User reviewer, LocalDate date) { int assignedReviews = countAssignedReviews(reviewer, date); - int currentTarget = getTarget(reviewer, date) - .map(rt -> getPeriodTarget(rt, date)) - .orElse(0); + int currentTarget = getTarget(reviewer, date).map(rt -> getPeriodTarget(rt, date)).orElse(0); return new CurrentTarget(currentTarget, assignedReviews); } private int countAssignedReviews(User reviewer, LocalDate fromDate) { if (fromDate.getMonthValue() <= Month.JUNE.getValue()) { return countReviews(reviewer, startOfSpring(fromDate.getYear()), endOfSpring(fromDate.getYear())); - } - else { + } else { return countReviews(reviewer, startOfAutumn(fromDate.getYear()), endOfAutumn(fromDate.getYear())); } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupService.java index d626972501..330b8ddd2d 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupService.java @@ -1,10 +1,14 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.util.Pair; - import java.util.Date; import java.util.List; +import se.su.dsv.scipro.util.Pair; public interface ReviewerDeadlineFollowupService { - List> getLateReviewerApprovals(ReviewerApproval.Step step, Date startDate, Date endDate, final Date now); + List> getLateReviewerApprovals( + ReviewerApproval.Step step, + Date startDate, + Date endDate, + final Date now + ); } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupServiceImpl.java index 1edd826fb5..74b7f28b09 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineFollowupServiceImpl.java @@ -1,19 +1,18 @@ package se.su.dsv.scipro.reviewing; +import static com.querydsl.core.types.dsl.Expressions.allOf; +import static com.querydsl.core.types.dsl.Expressions.anyOf; + import com.querydsl.core.types.SubQueryExpression; import com.querydsl.jpa.JPAExpressions; -import se.su.dsv.scipro.system.AbstractRepository; -import se.su.dsv.scipro.util.Pair; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.Date; import java.util.List; - -import static com.querydsl.core.types.dsl.Expressions.allOf; -import static com.querydsl.core.types.dsl.Expressions.anyOf; +import se.su.dsv.scipro.system.AbstractRepository; +import se.su.dsv.scipro.util.Pair; public class ReviewerDeadlineFollowupServiceImpl extends AbstractRepository implements ReviewerDeadlineFollowupService { @@ -23,26 +22,35 @@ public class ReviewerDeadlineFollowupServiceImpl extends AbstractRepository impl } @Override - public List> getLateReviewerApprovals(ReviewerApproval.Step step, Date startDate, Date endDate, final Date now) { + public List> getLateReviewerApprovals( + ReviewerApproval.Step step, + Date startDate, + Date endDate, + final Date now + ) { List decisions = from(QDecision.decision) - .where(allOf(QDecision.decision.requested.after(startDate), - QDecision.decision.requested.before(endDate), - QDecision.decision.reviewerApproval.id.in(getSubQueryList(step)), - anyOf( - allOf(QDecision.decision.deadline.before(now), QDecision.decision.decisionDate.isNull()), - QDecision.decision.decisionDate.after(QDecision.decision.deadline)) - ) + .where( + allOf( + QDecision.decision.requested.after(startDate), + QDecision.decision.requested.before(endDate), + QDecision.decision.reviewerApproval.id.in(getSubQueryList(step)), + anyOf( + allOf(QDecision.decision.deadline.before(now), QDecision.decision.decisionDate.isNull()), + QDecision.decision.decisionDate.after(QDecision.decision.deadline) + ) ) - .fetch(); + ) + .fetch(); return getLateDecisions(decisions); } private SubQueryExpression getSubQueryList(ReviewerApproval.Step step) { - if (step == ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL) - return JPAExpressions.select(QRoughDraftApproval.roughDraftApproval.id) - .from(QRoughDraftApproval.roughDraftApproval); - return JPAExpressions.select(QFinalSeminarApproval.finalSeminarApproval.id) - .from(QFinalSeminarApproval.finalSeminarApproval); + if (step == ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL) return JPAExpressions.select( + QRoughDraftApproval.roughDraftApproval.id + ).from(QRoughDraftApproval.roughDraftApproval); + return JPAExpressions.select(QFinalSeminarApproval.finalSeminarApproval.id).from( + QFinalSeminarApproval.finalSeminarApproval + ); } private List> getLateDecisions(final List decisions) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettings.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettings.java index 044ada8fb5..2d57461d51 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettings.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.*; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Table(name = "reviewer_deadline_settings") @@ -22,8 +21,7 @@ public class ReviewerDeadlineSettings extends DomainObject { @Column(name = "final_grading", nullable = false) private int finalGrading = 5; - public ReviewerDeadlineSettings() { - } + public ReviewerDeadlineSettings() {} public ReviewerDeadlineSettings(final Long id) { this.id = id; @@ -64,7 +62,17 @@ public class ReviewerDeadlineSettings extends DomainObject { @Override public String toString() { - return "ReviewerDeadlineSettings(id=" + this.getId() + ", roughDraftApproval=" + this.getRoughDraftApproval() + ", finalSeminarApproval=" + this.getFinalSeminarApproval() + ", finalGrading=" + this.getFinalGrading() + ")"; + return ( + "ReviewerDeadlineSettings(id=" + + this.getId() + + ", roughDraftApproval=" + + this.getRoughDraftApproval() + + ", finalSeminarApproval=" + + this.getFinalSeminarApproval() + + ", finalGrading=" + + this.getFinalGrading() + + ")" + ); } @Override @@ -72,12 +80,14 @@ public class ReviewerDeadlineSettings extends DomainObject { if (o == this) return true; if (!(o instanceof ReviewerDeadlineSettings)) return false; final ReviewerDeadlineSettings other = (ReviewerDeadlineSettings) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && this.getRoughDraftApproval() == other.getRoughDraftApproval() - && this.getFinalSeminarApproval() == other.getFinalSeminarApproval() - && this.getFinalGrading() == other.getFinalGrading(); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + this.getRoughDraftApproval() == other.getRoughDraftApproval() && + this.getFinalSeminarApproval() == other.getFinalSeminarApproval() && + this.getFinalGrading() == other.getFinalGrading() + ); } protected boolean canEqual(final Object other) { @@ -86,6 +96,11 @@ public class ReviewerDeadlineSettings extends DomainObject { @Override public int hashCode() { - return Objects.hash(this.getId(), this.getRoughDraftApproval(), this.getFinalSeminarApproval(), this.getFinalGrading()); + return Objects.hash( + this.getId(), + this.getRoughDraftApproval(), + this.getFinalSeminarApproval(), + this.getFinalGrading() + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsRepositoryImpl.java index 6839c0cac5..d6e7e8177d 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsRepositoryImpl.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.reviewing; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.AbstractRepository; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractRepository; public class ReviewerDeadlineSettingsRepositoryImpl - extends AbstractRepository - implements ReviewerDeadlineSettingsRepository -{ + extends AbstractRepository + implements ReviewerDeadlineSettingsRepository { + @Inject public ReviewerDeadlineSettingsRepositoryImpl(Provider em) { super(em); @@ -25,8 +24,7 @@ public class ReviewerDeadlineSettingsRepositoryImpl EntityManager entityManager = em(); if (entityManager.contains(entity)) { return entityManager.merge(entity); - } - else { + } else { entityManager.persist(entity); return entity; } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsServiceImpl.java index 3f0db387dd..da0cb4c471 100755 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDeadlineSettingsServiceImpl.java @@ -1,34 +1,33 @@ package se.su.dsv.scipro.reviewing; -import jakarta.transaction.Transactional; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; public class ReviewerDeadlineSettingsServiceImpl implements ReviewerDeadlineSettingsService { - private static final long INSTANCE_ID = 1L; + private static final long INSTANCE_ID = 1L; - private final ReviewerDeadlineSettingsRepository repository; + private final ReviewerDeadlineSettingsRepository repository; - @Inject - public ReviewerDeadlineSettingsServiceImpl(ReviewerDeadlineSettingsRepository repository) { - this.repository = repository; - } + @Inject + public ReviewerDeadlineSettingsServiceImpl(ReviewerDeadlineSettingsRepository repository) { + this.repository = repository; + } - @Override - @Transactional - public ReviewerDeadlineSettings getInstance() { - ReviewerDeadlineSettings settings = repository.findOne(INSTANCE_ID); - if(settings==null) { - settings = new ReviewerDeadlineSettings(INSTANCE_ID); - save(settings); - } - return settings; - } + @Override + @Transactional + public ReviewerDeadlineSettings getInstance() { + ReviewerDeadlineSettings settings = repository.findOne(INSTANCE_ID); + if (settings == null) { + settings = new ReviewerDeadlineSettings(INSTANCE_ID); + save(settings); + } + return settings; + } - @Override - @Transactional - public ReviewerDeadlineSettings save(ReviewerDeadlineSettings entity) { - return repository.save(entity); - } + @Override + @Transactional + public ReviewerDeadlineSettings save(ReviewerDeadlineSettings entity) { + return repository.save(entity); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorker.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorker.java index 16e011b3c1..58dfa5fc64 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorker.java @@ -1,14 +1,6 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.data.enums.DateStyle; -import se.su.dsv.scipro.mail.MailEvent; -import se.su.dsv.scipro.mail.MailEventService; -import se.su.dsv.scipro.misc.DaysService; -import se.su.dsv.scipro.reviewing.MyReviewService.Filter; -import se.su.dsv.scipro.system.Unit; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.workerthreads.AbstractWorker; - +import jakarta.inject.Inject; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -20,7 +12,14 @@ import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; -import jakarta.inject.Inject; +import se.su.dsv.scipro.data.enums.DateStyle; +import se.su.dsv.scipro.mail.MailEvent; +import se.su.dsv.scipro.mail.MailEventService; +import se.su.dsv.scipro.misc.DaysService; +import se.su.dsv.scipro.reviewing.MyReviewService.Filter; +import se.su.dsv.scipro.system.Unit; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.workerthreads.AbstractWorker; public class ReviewerDecisionReminderWorker extends AbstractWorker { @@ -28,12 +27,14 @@ public class ReviewerDecisionReminderWorker extends AbstractWorker { private static final SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.DATE.getFormat()); private static final Filter finalSeminarApprovalFilter = new Filter(); + static { finalSeminarApprovalFilter.setStatuses(Collections.singleton(Status.UNDECIDED)); finalSeminarApprovalFilter.setStep(ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL); } private static final Filter roughDraftApprovalFilter = new Filter(); + static { roughDraftApprovalFilter.setStatuses(Collections.singleton(Status.UNDECIDED)); roughDraftApprovalFilter.setStep(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL); @@ -45,10 +46,10 @@ public class ReviewerDecisionReminderWorker extends AbstractWorker { @Inject public ReviewerDecisionReminderWorker( - MyReviewService myReviewService, - DaysService daysService, - MailEventService mailEventService) - { + MyReviewService myReviewService, + DaysService daysService, + MailEventService mailEventService + ) { this.myReviewService = myReviewService; this.daysService = daysService; this.mailEventService = mailEventService; @@ -57,34 +58,39 @@ public class ReviewerDecisionReminderWorker extends AbstractWorker { @Override protected void doWork() { List reviewerRoughDraftApprovals = myReviewService.findAllApprovals(roughDraftApprovalFilter); - List reviewerFinalSeminarApprovals = myReviewService.findAllApprovals(finalSeminarApprovalFilter); + List reviewerFinalSeminarApprovals = myReviewService.findAllApprovals( + finalSeminarApprovalFilter + ); Date today = new Date(); Predicate needRemindingToday = needReminding(today, this::reminderDays); beginTransaction(); - reviewerRoughDraftApprovals.stream() - .filter(needRemindingToday) - .collect(Collectors.groupingBy(ra -> Optional.ofNullable(ra.getProject().getReviewer()))) - .forEach((reviewer, approvals) -> { - final MailEvent mailEvent = generateRoughDraftReminder(reviewer, approvals); - mailEventService.save(mailEvent); - }); - reviewerFinalSeminarApprovals.stream() - .filter(needRemindingToday) - .collect(Collectors.groupingBy(ra -> Optional.ofNullable(ra.getProject().getReviewer()))) - .forEach((reviewer, approvals) -> { - final MailEvent mailEvent = generateFinalSeminarReminder(reviewer, approvals); - mailEventService.save(mailEvent); - }); + reviewerRoughDraftApprovals + .stream() + .filter(needRemindingToday) + .collect(Collectors.groupingBy(ra -> Optional.ofNullable(ra.getProject().getReviewer()))) + .forEach((reviewer, approvals) -> { + final MailEvent mailEvent = generateRoughDraftReminder(reviewer, approvals); + mailEventService.save(mailEvent); + }); + reviewerFinalSeminarApprovals + .stream() + .filter(needRemindingToday) + .collect(Collectors.groupingBy(ra -> Optional.ofNullable(ra.getProject().getReviewer()))) + .forEach((reviewer, approvals) -> { + final MailEvent mailEvent = generateFinalSeminarReminder(reviewer, approvals); + mailEventService.save(mailEvent); + }); commitTransaction(); } private Set reminderDays(Date date) { - return daysAfterToRemind.stream() - .map(days -> daysService.workDaysAfter(date, days)) - .collect(Collectors.toSet()); + return daysAfterToRemind + .stream() + .map(days -> daysService.workDaysAfter(date, days)) + .collect(Collectors.toSet()); } static Predicate needReminding(Date today, Function> getReminderDays) { @@ -111,7 +117,11 @@ public class ReviewerDecisionReminderWorker extends AbstractWorker { return generateReminder(reviewer, reviewerApprovals, "final seminar"); } - private static MailEvent generateReminder(Optional reviewer, List reviewerApprovals, String approvalType) { + private static MailEvent generateReminder( + Optional reviewer, + List reviewerApprovals, + String approvalType + ) { MailEvent reminder = new MailEvent(); reviewer.ifPresent(reminder.getRecipients()::add); Optional gru = reviewer.map(User::getUnit).map(Unit::getMatchResponsible); @@ -119,21 +129,33 @@ public class ReviewerDecisionReminderWorker extends AbstractWorker { reminder.setSubject("Missed SciPro " + approvalType + " approval deadline"); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder - .append("According to the information in Scipro,").append('\n') - .append("the following ").append(approvalType).append(" approval(s) that ") - .append(reviewer.map(User::getFullName).orElse("nobody")) - .append(" is responsible for are past due:").append('\n') - .append('\n'); + .append("According to the information in Scipro,") + .append('\n') + .append("the following ") + .append(approvalType) + .append(" approval(s) that ") + .append(reviewer.map(User::getFullName).orElse("nobody")) + .append(" is responsible for are past due:") + .append('\n') + .append('\n'); for (ReviewerApproval approval : reviewerApprovals) { stringBuilder - .append("-Deadline: ").append(sdf.format(approval.getCurrentDeadline())).append('\n') - .append("-Supervisor: ").append(approval.getProject().getHeadSupervisor().getFullName()).append('\n') - .append("-Author(s): ").append(approval.getProject().getAuthorNames()).append('\n') - .append("-Title: ").append(approval.getProject().getTitle()).append('\n') - .append('\n'); + .append("-Deadline: ") + .append(sdf.format(approval.getCurrentDeadline())) + .append('\n') + .append("-Supervisor: ") + .append(approval.getProject().getHeadSupervisor().getFullName()) + .append('\n') + .append("-Author(s): ") + .append(approval.getProject().getAuthorNames()) + .append('\n') + .append("-Title: ") + .append(approval.getProject().getTitle()) + .append('\n') + .append('\n'); } stringBuilder.append("/Reviewer support"); reminder.setMessageBody(stringBuilder.toString()); return reminder; } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionService.java index f2ccfaab43..ec1042048b 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerDecisionService.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.file.FileUpload; - import java.util.*; +import se.su.dsv.scipro.file.FileUpload; public interface ReviewerDecisionService { void reject(ReviewerApproval finalSeminarApproval, String reason, Optional feedback); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionService.java index 0f84683bc6..01e5d1e45c 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionService.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.reviewing; +import java.util.*; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.*; - public interface ReviewerInteractionService { ReviewerThread getReviewerThread(Project project); List getPosts(Project project); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImpl.java index f0e62aacc6..53022565bd 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImpl.java @@ -1,7 +1,9 @@ package se.su.dsv.scipro.reviewing; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.*; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.BasicForumService; import se.su.dsv.scipro.forum.dataobjects.ForumPost; @@ -10,9 +12,6 @@ import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class ReviewerInteractionServiceImpl implements ReviewerInteractionService { private final ReviewerThreadRepository reviewerThreadRepository; @@ -20,7 +19,11 @@ public class ReviewerInteractionServiceImpl implements ReviewerInteractionServic private final EventBus eventBus; @Inject - public ReviewerInteractionServiceImpl(ReviewerThreadRepository reviewerThreadRepository, BasicForumService forumService, final EventBus eventBus) { + public ReviewerInteractionServiceImpl( + ReviewerThreadRepository reviewerThreadRepository, + BasicForumService forumService, + final EventBus eventBus + ) { this.reviewerThreadRepository = reviewerThreadRepository; this.forumService = forumService; this.eventBus = eventBus; @@ -50,7 +53,12 @@ public class ReviewerInteractionServiceImpl implements ReviewerInteractionServic @Override @Transactional - public ForumPost reply(final Project project, final User user, final String content, final Set attachments) { + public ForumPost reply( + final Project project, + final User user, + final String content, + final Set attachments + ) { ReviewerThread reviewerThread = getReviewerThread(project); ForumPost reply = forumService.createReply(reviewerThread.getForumThread(), user, content, attachments); eventBus.post(new NewReviewerInteractionMessage(project, reply)); @@ -64,5 +72,4 @@ public class ReviewerInteractionServiceImpl implements ReviewerInteractionServic forumService.setRead(user, post, true); } } - } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTarget.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTarget.java index 29803d920f..5393025519 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTarget.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTarget.java @@ -8,14 +8,14 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import java.util.Objects; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Objects; - @Entity @Table(name = "reviewer_target") public class ReviewerTarget extends DomainObject { + @Id @GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY) private Long id; @@ -91,25 +91,36 @@ public class ReviewerTarget extends DomainObject { @Override public String toString() { - return "ReviewerTarget{" + - "id=" + id + - ", reviewer=" + reviewer + - ", year=" + year + - ", spring=" + spring + - ", autumn=" + autumn + - ", note='" + note + '\'' + - '}'; + return ( + "ReviewerTarget{" + + "id=" + + id + + ", reviewer=" + + reviewer + + ", year=" + + year + + ", spring=" + + spring + + ", autumn=" + + autumn + + ", note='" + + note + + '\'' + + '}' + ); } @Override public boolean equals(Object o) { - return o instanceof ReviewerTarget that - && year == that.year - && spring == that.spring - && autumn == that.autumn - && Objects.equals(id, that.id) - && Objects.equals(reviewer, that.reviewer) - && Objects.equals(note, that.note); + return ( + o instanceof ReviewerTarget that && + year == that.year && + spring == that.spring && + autumn == that.autumn && + Objects.equals(id, that.id) && + Objects.equals(reviewer, that.reviewer) && + Objects.equals(note, that.note) + ); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepository.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepository.java index 7dca0b09bf..dd245eb5ac 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.User; - import java.time.Year; import java.util.List; import java.util.Optional; +import se.su.dsv.scipro.system.User; public interface ReviewerTargetRepository { void save(ReviewerTarget reviewerTarget); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepositoryImpl.java index ba1b9b961c..7f68858057 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerTargetRepositoryImpl.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.reviewing; -import jakarta.transaction.Transactional; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.system.AbstractRepository; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.time.Year; import java.util.List; import java.util.Optional; +import se.su.dsv.scipro.system.AbstractRepository; +import se.su.dsv.scipro.system.User; public class ReviewerTargetRepositoryImpl extends AbstractRepository implements ReviewerTargetRepository { + @Inject public ReviewerTargetRepositoryImpl(Provider em) { super(em); @@ -30,19 +30,18 @@ public class ReviewerTargetRepositoryImpl extends AbstractRepository implements @Override public Optional getReviewerTarget(User reviewer, Year year) { - ReviewerTarget current = - from(QReviewerTarget.reviewerTarget) - .where(QReviewerTarget.reviewerTarget.reviewer.eq(reviewer)) - .where(QReviewerTarget.reviewerTarget.year.eq(year.getValue())) - .fetchOne(); + ReviewerTarget current = from(QReviewerTarget.reviewerTarget) + .where(QReviewerTarget.reviewerTarget.reviewer.eq(reviewer)) + .where(QReviewerTarget.reviewerTarget.year.eq(year.getValue())) + .fetchOne(); return Optional.ofNullable(current); } @Override public List getReviewerTargetsBeforeYear(User reviewer, Year year) { return from(QReviewerTarget.reviewerTarget) - .where(QReviewerTarget.reviewerTarget.reviewer.eq(reviewer)) - .where(QReviewerTarget.reviewerTarget.year.lt(year.getValue())) - .fetch(); + .where(QReviewerTarget.reviewerTarget.reviewer.eq(reviewer)) + .where(QReviewerTarget.reviewerTarget.year.lt(year.getValue())) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepository.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepository.java index 4dc40f5bb5..284c44b762 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.system.JpaRepository; +import java.util.Optional; import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; import se.su.dsv.scipro.project.Project; - -import java.util.Optional; +import se.su.dsv.scipro.system.JpaRepository; public interface ReviewerThreadRepository extends JpaRepository { Optional findByProject(Project project); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepositoryImpl.java index 7cc9d289b6..29143455b5 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewerThreadRepositoryImpl.java @@ -1,16 +1,18 @@ package se.su.dsv.scipro.reviewing; -import se.su.dsv.scipro.forum.dataobjects.QReviewerThread; -import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.forum.dataobjects.QReviewerThread; +import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.GenericRepo; + +public class ReviewerThreadRepositoryImpl + extends GenericRepo + implements ReviewerThreadRepository { -public class ReviewerThreadRepositoryImpl extends GenericRepo implements ReviewerThreadRepository { @Inject public ReviewerThreadRepositoryImpl(final Provider em) { super(em, ReviewerThread.class, QReviewerThread.reviewerThread); diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewingServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewingServiceImpl.java index b56e733c68..0666993786 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewingServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/ReviewingServiceImpl.java @@ -1,170 +1,176 @@ -package se.su.dsv.scipro.reviewing; - -import com.google.common.eventbus.EventBus; -import com.querydsl.core.BooleanBuilder; -import com.querydsl.core.types.OrderSpecifier; -import com.querydsl.core.types.Predicate; -import com.querydsl.core.types.dsl.BooleanExpression; -import com.querydsl.core.types.dsl.LiteralExpression; -import com.querydsl.jpa.impl.JPAQuery; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileService; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.project.QProject; -import se.su.dsv.scipro.system.AbstractServiceImpl; -import se.su.dsv.scipro.system.Page; -import se.su.dsv.scipro.system.User; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.*; - -import static com.querydsl.core.types.dsl.Expressions.allOf; - -public class ReviewingServiceImpl extends AbstractServiceImpl implements MyReviewService, ReviewerDecisionService { - - private final FileService fileDescriptionService; - private final EventBus eventBus; - - @Inject - public ReviewingServiceImpl(Provider em, FileService fileDescriptionService, final EventBus eventBus) { - super(em, ReviewerApproval.class, QReviewerApproval.reviewerApproval); - this.fileDescriptionService = fileDescriptionService; - this.eventBus = eventBus; - } - - @Override - public List findAllDecisions(final Filter filter, final Page pageable) { - BooleanBuilder predicate = fromFilterForDecision(filter); - LiteralExpression sortProperty = switch (pageable.sort().sortBy()) { - case REQUESTED -> QDecision.decision.requested; - case DEADLINE -> QDecision.decision.deadline; - case TITLE -> QReviewerApproval.reviewerApproval.project.title; - case SUPERVISOR -> QReviewerApproval.reviewerApproval.project.headSupervisor.fullName; - }; - OrderSpecifier orderBy = pageable.sort().direction() == Page.Direction.ASCENDING - ? sortProperty.asc() - : sortProperty.desc(); - return new JPAQuery<>(em()) - .select(QDecision.decision) - .from(QDecision.decision) - .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) - .join(QReviewerApproval.reviewerApproval.project, QProject.project) - .where(predicate) - .limit(pageable.limit()) - .offset(pageable.offset()) - .orderBy(orderBy) - .fetch(); - } - - @Override - public List findAllApprovals(final Filter filter) { - return findAll(fromFilterForApprovals(filter)); - } - - @Override - public long countDecisions(final Filter filter) { - return from(QDecision.decision) - .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) - .where(fromFilterForDecision(filter)) - .select(QDecision.decision.count()) - .fetchFirst(); - } - - @Override - public long countUndecidedRoughDraft(final User reviewer) { - return from(QDecision.decision) - .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) - .where(forReviewer(reviewer).and(isUndecided()).and(forStep(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL))) - .select(QDecision.decision.count()) - .fetchFirst(); - } - - @Override - public Decision findDecision(Long id) { - return new JPAQuery<>(em()) - .select(QDecision.decision) - .from(QDecision.decision) - .where(QDecision.decision.id.eq(id)) - .fetchOne(); - } - - @Override - @Transactional - public void reject(final ReviewerApproval reviewerApproval, final String reason, final Optional feedback) { - Optional feedbackFile = store(feedback); - reviewerApproval.reject(reason, feedbackFile); - save(reviewerApproval); - - if (reviewerApproval instanceof FinalSeminarApproval) { - eventBus.post(new FinalSeminarApprovalRejectedEvent(reviewerApproval.getProject())); - } - else if (reviewerApproval instanceof RoughDraftApproval) { - eventBus.post(new RoughDraftApprovalRejectedEvent(reviewerApproval)); - } - } - - @Override - @Transactional - public void approve(final ReviewerApproval process, final String reason, final Optional feedback) { - Optional feedbackFile = store(feedback); - process.approve(reason, feedbackFile); - save(process); - - if (process instanceof FinalSeminarApproval) { - eventBus.post(new FinalSeminarApprovalApprovedEvent(process)); - } - else if (process instanceof RoughDraftApproval) { - eventBus.post(new RoughDraftApprovalApprovedEvent(process)); - } - } - - private static BooleanExpression forReviewer(final User reviewer) { - return QReviewerApproval.reviewerApproval.project.reviewers.any().eq(reviewer); - } - - private static BooleanExpression forStep(final ReviewerApproval.Step step) { - if (step == ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL) { - return QReviewerApproval.reviewerApproval.instanceOf(RoughDraftApproval.class); - } - return QReviewerApproval.reviewerApproval.instanceOf(FinalSeminarApproval.class); - } - - private static BooleanExpression forStatus(final Collection statuses) { - return QReviewerApproval.reviewerApproval.decisions.any().status.in(statuses); - } - - private BooleanBuilder fromFilterForDecision(Filter filter) { - BooleanBuilder bb = new BooleanBuilder(); - bb.and(forReviewer(filter.getUser())); - bb.and(forStep(filter.getStep())); - if (!filter.isShowAll()) { - bb.and(isUndecided()); - } - - return bb; - } - - private BooleanBuilder fromFilterForApprovals(Filter filter) { - BooleanBuilder bb = new BooleanBuilder(); - bb.and(forStep(filter.getStep())); - bb.and(forStatus(filter.getStatuses())); - return bb; - } - - - private static Predicate isUndecided() { - return allOf( - QDecision.decision.status.eq(Status.UNDECIDED), - QReviewerApproval.reviewerApproval.project.projectStatus.eq(ProjectStatus.ACTIVE) - ); - } - - private Optional store(final Optional feedback) { - return feedback.map(fileDescriptionService::storeFile); - } - -} +package se.su.dsv.scipro.reviewing; + +import static com.querydsl.core.types.dsl.Expressions.allOf; + +import com.google.common.eventbus.EventBus; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.OrderSpecifier; +import com.querydsl.core.types.Predicate; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.LiteralExpression; +import com.querydsl.jpa.impl.JPAQuery; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.*; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileService; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.project.QProject; +import se.su.dsv.scipro.system.AbstractServiceImpl; +import se.su.dsv.scipro.system.Page; +import se.su.dsv.scipro.system.User; + +public class ReviewingServiceImpl + extends AbstractServiceImpl + implements MyReviewService, ReviewerDecisionService { + + private final FileService fileDescriptionService; + private final EventBus eventBus; + + @Inject + public ReviewingServiceImpl( + Provider em, + FileService fileDescriptionService, + final EventBus eventBus + ) { + super(em, ReviewerApproval.class, QReviewerApproval.reviewerApproval); + this.fileDescriptionService = fileDescriptionService; + this.eventBus = eventBus; + } + + @Override + public List findAllDecisions(final Filter filter, final Page pageable) { + BooleanBuilder predicate = fromFilterForDecision(filter); + LiteralExpression sortProperty = + switch (pageable.sort().sortBy()) { + case REQUESTED -> QDecision.decision.requested; + case DEADLINE -> QDecision.decision.deadline; + case TITLE -> QReviewerApproval.reviewerApproval.project.title; + case SUPERVISOR -> QReviewerApproval.reviewerApproval.project.headSupervisor.fullName; + }; + OrderSpecifier orderBy = pageable.sort().direction() == Page.Direction.ASCENDING + ? sortProperty.asc() + : sortProperty.desc(); + return new JPAQuery<>(em()) + .select(QDecision.decision) + .from(QDecision.decision) + .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) + .join(QReviewerApproval.reviewerApproval.project, QProject.project) + .where(predicate) + .limit(pageable.limit()) + .offset(pageable.offset()) + .orderBy(orderBy) + .fetch(); + } + + @Override + public List findAllApprovals(final Filter filter) { + return findAll(fromFilterForApprovals(filter)); + } + + @Override + public long countDecisions(final Filter filter) { + return from(QDecision.decision) + .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) + .where(fromFilterForDecision(filter)) + .select(QDecision.decision.count()) + .fetchFirst(); + } + + @Override + public long countUndecidedRoughDraft(final User reviewer) { + return from(QDecision.decision) + .join(QDecision.decision.reviewerApproval, QReviewerApproval.reviewerApproval) + .where(forReviewer(reviewer).and(isUndecided()).and(forStep(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL))) + .select(QDecision.decision.count()) + .fetchFirst(); + } + + @Override + public Decision findDecision(Long id) { + return new JPAQuery<>(em()) + .select(QDecision.decision) + .from(QDecision.decision) + .where(QDecision.decision.id.eq(id)) + .fetchOne(); + } + + @Override + @Transactional + public void reject( + final ReviewerApproval reviewerApproval, + final String reason, + final Optional feedback + ) { + Optional feedbackFile = store(feedback); + reviewerApproval.reject(reason, feedbackFile); + save(reviewerApproval); + + if (reviewerApproval instanceof FinalSeminarApproval) { + eventBus.post(new FinalSeminarApprovalRejectedEvent(reviewerApproval.getProject())); + } else if (reviewerApproval instanceof RoughDraftApproval) { + eventBus.post(new RoughDraftApprovalRejectedEvent(reviewerApproval)); + } + } + + @Override + @Transactional + public void approve(final ReviewerApproval process, final String reason, final Optional feedback) { + Optional feedbackFile = store(feedback); + process.approve(reason, feedbackFile); + save(process); + + if (process instanceof FinalSeminarApproval) { + eventBus.post(new FinalSeminarApprovalApprovedEvent(process)); + } else if (process instanceof RoughDraftApproval) { + eventBus.post(new RoughDraftApprovalApprovedEvent(process)); + } + } + + private static BooleanExpression forReviewer(final User reviewer) { + return QReviewerApproval.reviewerApproval.project.reviewers.any().eq(reviewer); + } + + private static BooleanExpression forStep(final ReviewerApproval.Step step) { + if (step == ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL) { + return QReviewerApproval.reviewerApproval.instanceOf(RoughDraftApproval.class); + } + return QReviewerApproval.reviewerApproval.instanceOf(FinalSeminarApproval.class); + } + + private static BooleanExpression forStatus(final Collection statuses) { + return QReviewerApproval.reviewerApproval.decisions.any().status.in(statuses); + } + + private BooleanBuilder fromFilterForDecision(Filter filter) { + BooleanBuilder bb = new BooleanBuilder(); + bb.and(forReviewer(filter.getUser())); + bb.and(forStep(filter.getStep())); + if (!filter.isShowAll()) { + bb.and(isUndecided()); + } + + return bb; + } + + private BooleanBuilder fromFilterForApprovals(Filter filter) { + BooleanBuilder bb = new BooleanBuilder(); + bb.and(forStep(filter.getStep())); + bb.and(forStatus(filter.getStatuses())); + return bb; + } + + private static Predicate isUndecided() { + return allOf( + QDecision.decision.status.eq(Status.UNDECIDED), + QReviewerApproval.reviewerApproval.project.projectStatus.eq(ProjectStatus.ACTIVE) + ); + } + + private Optional store(final Optional feedback) { + return feedback.map(fileDescriptionService::storeFile); + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApproval.java b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApproval.java index 47391707b6..bd8854b67b 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApproval.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApproval.java @@ -1,24 +1,27 @@ -package se.su.dsv.scipro.reviewing; - -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; - -import jakarta.persistence.Entity; -import java.util.*; - -@Entity -public class RoughDraftApproval extends ReviewerApproval { - - protected RoughDraftApproval() {} - - public RoughDraftApproval(final Project project, final FileReference thesis, final String comment, final Date deadline) { - this.project = project; - this.decisions.add(new Decision(this, thesis, comment, deadline)); - } - - @Override - public Step getStep() { - return Step.ROUGH_DRAFT_APPROVAL; - } - -} +package se.su.dsv.scipro.reviewing; + +import jakarta.persistence.Entity; +import java.util.*; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; + +@Entity +public class RoughDraftApproval extends ReviewerApproval { + + protected RoughDraftApproval() {} + + public RoughDraftApproval( + final Project project, + final FileReference thesis, + final String comment, + final Date deadline + ) { + this.project = project; + this.decisions.add(new Decision(this, thesis, comment, deadline)); + } + + @Override + public Step getStep() { + return Step.ROUGH_DRAFT_APPROVAL; + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalRequestedEvent.java b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalRequestedEvent.java index 2fe85bf207..93a962f1fb 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalRequestedEvent.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalRequestedEvent.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.project.Project; public class RoughDraftApprovalRequestedEvent { + private final RoughDraftApproval roughDraftApproval; public RoughDraftApprovalRequestedEvent(final RoughDraftApproval roughDraftApproval) { diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalService.java b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalService.java index e2e87f3cca..a4e41dfa40 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalService.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalService.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.reviewing; - -public interface RoughDraftApprovalService extends ReviewerApprovalService { -} +package se.su.dsv.scipro.reviewing; + +public interface RoughDraftApprovalService extends ReviewerApprovalService {} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalServiceImpl.java index f7a4365b24..e0bb356aad 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/RoughDraftApprovalServiceImpl.java @@ -1,70 +1,74 @@ -package se.su.dsv.scipro.reviewing; - -import com.google.common.eventbus.EventBus; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileService; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.misc.DaysService; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.util.Either; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.Date; -import java.util.Optional; - -public class RoughDraftApprovalServiceImpl extends AbstractReviewerApprovalServiceImpl implements RoughDraftApprovalService { - - private final DaysService daysService; - private final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService; - - @Inject - public RoughDraftApprovalServiceImpl( - final Provider em, - final EventBus eventBus, - final FileService fileDescriptionService, - final DaysService daysService, - final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService) - { - super(em, RoughDraftApproval.class, QRoughDraftApproval.roughDraftApproval, eventBus, fileDescriptionService); - this.daysService = daysService; - this.reviewerDeadlineSettingsService = reviewerDeadlineSettingsService; - } - - @Override - @Transactional - public Either requestApproval(final Project project, FileUpload thesis, final String comment) { - final FileReference storedThesis = fileDescriptionService.storeFile(thesis); - - final Either roughDraftApproval = findBy(project) - .map(earlier -> addNewRequest(comment, storedThesis, earlier)) - .orElseGet(() -> Either.right(newApproval(project, storedThesis, comment))); - - final Either persisted = - roughDraftApproval.map(this::save); - persisted.foreach(rda -> eventBus.post(new RoughDraftApprovalRequestedEvent(rda))); - return persisted; - } - - private RoughDraftApproval newApproval(Project project, FileReference storedThesis, String comment) { - Date deadline = getDeadline(new Date()); - if (project.getReviewer() == null) { - // Ugly hack to stop sending reminders before a reviewer is assigned - deadline = new Date(1583668380000L); - } - return new RoughDraftApproval(project, storedThesis, comment, deadline); - } - - @Override - protected Date getDeadline(final Date requested) { - final ReviewerDeadlineSettings reviewerDeadlineSettings = reviewerDeadlineSettingsService.getInstance(); - return daysService.workDaysAfter(requested, reviewerDeadlineSettings.getRoughDraftApproval()); - } - - @Override - public Optional findBy(Project project) { - return Optional.ofNullable(findOne(QRoughDraftApproval.roughDraftApproval.project.eq(project))); - } -} +package se.su.dsv.scipro.reviewing; + +import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import java.util.Date; +import java.util.Optional; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileService; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.misc.DaysService; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.util.Either; + +public class RoughDraftApprovalServiceImpl + extends AbstractReviewerApprovalServiceImpl + implements RoughDraftApprovalService { + + private final DaysService daysService; + private final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService; + + @Inject + public RoughDraftApprovalServiceImpl( + final Provider em, + final EventBus eventBus, + final FileService fileDescriptionService, + final DaysService daysService, + final ReviewerDeadlineSettingsService reviewerDeadlineSettingsService + ) { + super(em, RoughDraftApproval.class, QRoughDraftApproval.roughDraftApproval, eventBus, fileDescriptionService); + this.daysService = daysService; + this.reviewerDeadlineSettingsService = reviewerDeadlineSettingsService; + } + + @Override + @Transactional + public Either requestApproval( + final Project project, + FileUpload thesis, + final String comment + ) { + final FileReference storedThesis = fileDescriptionService.storeFile(thesis); + + final Either roughDraftApproval = findBy(project) + .map(earlier -> addNewRequest(comment, storedThesis, earlier)) + .orElseGet(() -> Either.right(newApproval(project, storedThesis, comment))); + + final Either persisted = roughDraftApproval.map(this::save); + persisted.foreach(rda -> eventBus.post(new RoughDraftApprovalRequestedEvent(rda))); + return persisted; + } + + private RoughDraftApproval newApproval(Project project, FileReference storedThesis, String comment) { + Date deadline = getDeadline(new Date()); + if (project.getReviewer() == null) { + // Ugly hack to stop sending reminders before a reviewer is assigned + deadline = new Date(1583668380000L); + } + return new RoughDraftApproval(project, storedThesis, comment, deadline); + } + + @Override + protected Date getDeadline(final Date requested) { + final ReviewerDeadlineSettings reviewerDeadlineSettings = reviewerDeadlineSettingsService.getInstance(); + return daysService.workDaysAfter(requested, reviewerDeadlineSettings.getRoughDraftApproval()); + } + + @Override + public Optional findBy(Project project) { + return Optional.ofNullable(findOne(QRoughDraftApproval.roughDraftApproval.project.eq(project))); + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/reviewing/Status.java b/core/src/main/java/se/su/dsv/scipro/reviewing/Status.java index 15a14a4758..fd29454405 100644 --- a/core/src/main/java/se/su/dsv/scipro/reviewing/Status.java +++ b/core/src/main/java/se/su/dsv/scipro/reviewing/Status.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.reviewing; public enum Status { - APPROVED, REJECTED, UNDECIDED + APPROVED, + REJECTED, + UNDECIDED, } diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/AuthenticationServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/security/auth/AuthenticationServiceImpl.java index b213680052..1a6ebcb0de 100644 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/AuthenticationServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/AuthenticationServiceImpl.java @@ -4,6 +4,7 @@ import jakarta.inject.Inject; import java.util.Set; public class AuthenticationServiceImpl implements AuthenticationService { + private final Set authenticationProviders; @Inject diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/Authorization.java b/core/src/main/java/se/su/dsv/scipro/security/auth/Authorization.java index 51b2deaaef..73ed100bf2 100755 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/Authorization.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/Authorization.java @@ -1,16 +1,13 @@ package se.su.dsv.scipro.security.auth; -import se.su.dsv.scipro.security.auth.roles.Roles; - import java.lang.annotation.*; +import se.su.dsv.scipro.security.auth.roles.Roles; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface Authorization { + boolean requiresLoggedInUser() default true; - boolean requiresLoggedInUser() default true; - - Roles[] authorizedRoles() default {Roles.SYSADMIN}; - + Roles[] authorizedRoles() default { Roles.SYSADMIN }; } diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/Credentials.java b/core/src/main/java/se/su/dsv/scipro/security/auth/Credentials.java index 197be44b9b..bb6e748819 100644 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/Credentials.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/Credentials.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.security.auth; public class Credentials { + private final String username; private final char[] password; diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/LocalAuthentication.java b/core/src/main/java/se/su/dsv/scipro/security/auth/LocalAuthentication.java index ae7f3fa8b0..e0ca834721 100644 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/LocalAuthentication.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/LocalAuthentication.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.security.auth; +import jakarta.inject.Inject; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; - public class LocalAuthentication implements AuthenticationProvider { + private final UserService userService; private final PasswordService passwordService; @@ -22,6 +22,6 @@ public class LocalAuthentication implements AuthenticationProvider { } Password password = passwordService.findByUser(user); - return password != null && PasswordHandler.isMatch(credentials.getPassword(), password); + return (password != null && PasswordHandler.isMatch(credentials.getPassword(), password)); } } diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/roles/IRole.java b/core/src/main/java/se/su/dsv/scipro/security/auth/roles/IRole.java index 374ff8dd72..b17d928a43 100755 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/roles/IRole.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/roles/IRole.java @@ -1,6 +1,6 @@ package se.su.dsv.scipro.security.auth.roles; public interface IRole { - boolean authorizedForRole(Roles role); + boolean authorizedForRole(Roles role); boolean isActualRole(Roles role); } diff --git a/core/src/main/java/se/su/dsv/scipro/security/auth/roles/Roles.java b/core/src/main/java/se/su/dsv/scipro/security/auth/roles/Roles.java index 3366f3490a..9945aa22c7 100755 --- a/core/src/main/java/se/su/dsv/scipro/security/auth/roles/Roles.java +++ b/core/src/main/java/se/su/dsv/scipro/security/auth/roles/Roles.java @@ -4,9 +4,11 @@ import java.util.Collection; import java.util.EnumSet; public enum Roles implements IRole { - AUTHOR { + AUTHOR { @Override - Collection authorizedFor() { return EnumSet.of(AUTHOR); } + Collection authorizedFor() { + return EnumSet.of(AUTHOR); + } }, SUPERVISOR { @Override @@ -46,7 +48,9 @@ public enum Roles implements IRole { }, BETA { @Override - Collection authorizedFor() { return EnumSet.of(BETA); } + Collection authorizedFor() { + return EnumSet.of(BETA); + } }; @Override diff --git a/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/SupervisorProjectNoteDisplay.java b/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/SupervisorProjectNoteDisplay.java index 1a6c45d452..4681a2463f 100644 --- a/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/SupervisorProjectNoteDisplay.java +++ b/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/SupervisorProjectNoteDisplay.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.settings.dataobjects; public enum SupervisorProjectNoteDisplay { - COMPACT, FULL + COMPACT, + FULL, } diff --git a/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/UserProfile.java b/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/UserProfile.java index e88c4b289b..c0e1b3b588 100644 --- a/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/UserProfile.java +++ b/core/src/main/java/se/su/dsv/scipro/settings/dataobjects/UserProfile.java @@ -1,10 +1,5 @@ package se.su.dsv.scipro.settings.dataobjects; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Objects; - import jakarta.persistence.Basic; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; @@ -20,7 +15,10 @@ import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; +import java.util.Objects; import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.ProjectTeamMemberRoles; import se.su.dsv.scipro.security.auth.roles.Roles; @@ -60,22 +58,29 @@ public class UserProfile extends DomainObject { @ElementCollection @Enumerated(EnumType.STRING) - @CollectionTable(name = "user_profile_default_project_status_filter", - joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id")) + @CollectionTable( + name = "user_profile_default_project_status_filter", + joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id") + ) @Column(name = "default_project_status_filter") private Collection defaultProjectStatusFilter = EnumSet.of(ProjectStatus.ACTIVE); @ElementCollection @Enumerated(EnumType.STRING) - @CollectionTable(name = "user_profile_default_project_team_member_roles_filter", - joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id")) + @CollectionTable( + name = "user_profile_default_project_team_member_roles_filter", + joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id") + ) @Column(name = "default_project_team_member_roles_filter") - private Collection defaultProjectTeamMemberRolesFilter = EnumSet.of(ProjectTeamMemberRoles.CO_SUPERVISOR); + private Collection defaultProjectTeamMemberRolesFilter = EnumSet.of( + ProjectTeamMemberRoles.CO_SUPERVISOR + ); @ManyToMany - @JoinTable(name = "user_profile_project_type", - joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "project_type_id", referencedColumnName = "id") + @JoinTable( + name = "user_profile_project_type", + joinColumns = @JoinColumn(name = "user_profile_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "project_type_id", referencedColumnName = "id") ) private Collection defaultProjectTypeFilter = new ArrayList<>(); @@ -157,7 +162,9 @@ public class UserProfile extends DomainObject { this.defaultProjectStatusFilter = defaultProjectStatusFilter; } - public void setDefaultProjectTeamMemberRolesFilter(Collection defaultProjectTeamMemberRolesFilter) { + public void setDefaultProjectTeamMemberRolesFilter( + Collection defaultProjectTeamMemberRolesFilter + ) { this.defaultProjectTeamMemberRolesFilter = defaultProjectTeamMemberRolesFilter; } @@ -183,7 +190,31 @@ public class UserProfile extends DomainObject { @Override public String toString() { - return "UserProfile(id=" + this.getId() + ", user=" + this.getUser() + ", skypeId=" + this.getSkypeId() + ", phoneNumber=" + this.getPhoneNumber() + ", otherInfo=" + this.getOtherInfo() + ", mailCompilation=" + this.isMailCompilation() + ", defaultProjectStatusFilter=" + this.getDefaultProjectStatusFilter() + ", defaultProjectTeamMemberRolesFilter=" + this.getDefaultProjectTeamMemberRolesFilter() + ", defaultSupervisorFilter=" + this.isDefaultSupervisorFilter() + ", defaultProjectTypeFilter=" + this.getDefaultProjectTypeFilter() + ", selectedRole=" + this.getSelectedRole() + ")"; + return ( + "UserProfile(id=" + + this.getId() + + ", user=" + + this.getUser() + + ", skypeId=" + + this.getSkypeId() + + ", phoneNumber=" + + this.getPhoneNumber() + + ", otherInfo=" + + this.getOtherInfo() + + ", mailCompilation=" + + this.isMailCompilation() + + ", defaultProjectStatusFilter=" + + this.getDefaultProjectStatusFilter() + + ", defaultProjectTeamMemberRolesFilter=" + + this.getDefaultProjectTeamMemberRolesFilter() + + ", defaultSupervisorFilter=" + + this.isDefaultSupervisorFilter() + + ", defaultProjectTypeFilter=" + + this.getDefaultProjectTypeFilter() + + ", selectedRole=" + + this.getSelectedRole() + + ")" + ); } @Override @@ -191,8 +222,7 @@ public class UserProfile extends DomainObject { if (o == this) return true; if (!(o instanceof UserProfile)) return false; final UserProfile other = (UserProfile) o; - return other.canEqual(this) - && Objects.equals(this.getUser(), other.getUser()); + return (other.canEqual(this) && Objects.equals(this.getUser(), other.getUser())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImpl.java index 99f2f30753..bd853a63e9 100755 --- a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImpl.java @@ -3,20 +3,19 @@ package se.su.dsv.scipro.springdata.serviceimpls; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.JPAExpressions; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.match.ApplicationPeriod; -import se.su.dsv.scipro.match.QTarget; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.springdata.services.SupervisorService; -import se.su.dsv.scipro.system.*; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Collection; import java.util.List; +import se.su.dsv.scipro.match.ApplicationPeriod; +import se.su.dsv.scipro.match.QTarget; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.springdata.services.SupervisorService; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; -public class SupervisorServiceImpl extends AbstractServiceImpl implements SupervisorService { +public class SupervisorServiceImpl extends AbstractServiceImpl implements SupervisorService { @Inject public SupervisorServiceImpl(Provider em) { @@ -59,15 +58,15 @@ public class SupervisorServiceImpl extends AbstractServiceImpl implem bb.and(areaFilter(params.getResearchArea())); } - if (params.getLanguages()!=null){ - if (params.getLanguages().isEmpty()){ + if (params.getLanguages() != null) { + if (params.getLanguages().isEmpty()) { bb.and(QUser.user.languages.any().isNull()); } else { bb.and(languageFilter(params.getLanguages())); } } - if (params.getHasTargetsInApplicationPeriod()!=null){ + if (params.getHasTargetsInApplicationPeriod() != null) { bb.and(hasTargetsInApplicationPeriod(params.getHasTargetsInApplicationPeriod())); } @@ -83,7 +82,7 @@ public class SupervisorServiceImpl extends AbstractServiceImpl implem } private BooleanExpression unitFilter(Unit unit) { - return QUser.user.unit.eq(unit); + return QUser.user.unit.eq(unit); } private BooleanExpression areaFilter(ResearchArea area) { @@ -95,11 +94,14 @@ public class SupervisorServiceImpl extends AbstractServiceImpl implem } private BooleanExpression supervisorIs(User supervisor) { - return QUser.user.eq(supervisor); + return QUser.user.eq(supervisor); } - private BooleanExpression hasTargetsInApplicationPeriod(ApplicationPeriod applicationPeriod){ - return QUser.user.in(JPAExpressions.select(QTarget.target1.user).from(QTarget.target1).where(QTarget.target1.applicationPeriod.eq(applicationPeriod).and(QTarget.target1.target.notIn(0)))); + private BooleanExpression hasTargetsInApplicationPeriod(ApplicationPeriod applicationPeriod) { + return QUser.user.in( + JPAExpressions.select(QTarget.target1.user) + .from(QTarget.target1) + .where(QTarget.target1.applicationPeriod.eq(applicationPeriod).and(QTarget.target1.target.notIn(0))) + ); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UnitServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UnitServiceImpl.java index a8d949d61f..620dbb7729 100755 --- a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UnitServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UnitServiceImpl.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.springdata.serviceimpls; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.AbstractServiceImpl; import se.su.dsv.scipro.system.QUnit; import se.su.dsv.scipro.system.Unit; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; +public class UnitServiceImpl extends AbstractServiceImpl implements UnitService { -public class UnitServiceImpl extends AbstractServiceImpl implements UnitService { @Inject public UnitServiceImpl(Provider em) { super(em, Unit.class, QUnit.unit); @@ -19,5 +19,4 @@ public class UnitServiceImpl extends AbstractServiceImpl implements U public Unit findByIdentifier(Integer identifier) { return findOne(QUnit.unit.identifier.eq(identifier)); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImpl.java index 992aa54888..3d339c5905 100644 --- a/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImpl.java @@ -1,22 +1,21 @@ package se.su.dsv.scipro.springdata.serviceimpls; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; +import java.util.List; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.settings.dataobjects.QUserProfile; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.util.List; - public class UserProfileServiceImpl extends AbstractServiceImpl implements UserProfileService { + @Inject public UserProfileServiceImpl(Provider em) { super(em, UserProfile.class, QUserProfile.userProfile); - } @Override @@ -34,7 +33,10 @@ public class UserProfileServiceImpl extends AbstractServiceImpl findUsersWithMailCompilation() { - return createQuery().where(QUserProfile.userProfile.mailCompilation.isTrue()).select(QUserProfile.userProfile.user).fetch(); + return createQuery() + .where(QUserProfile.userProfile.mailCompilation.isTrue()) + .select(QUserProfile.userProfile.user) + .fetch(); } @Override @@ -54,7 +56,7 @@ public class UserProfileServiceImpl extends AbstractServiceImpl getDefaultProjectTypes() { QProjectType projectType = QProjectType.projectType; return from(projectType) - .where(projectType.degreeType.in(List.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))) - .fetch(); + .where(projectType.degreeType.in(List.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/springdata/services/SupervisorService.java b/core/src/main/java/se/su/dsv/scipro/springdata/services/SupervisorService.java index 01b9638ff7..2484984c0d 100755 --- a/core/src/main/java/se/su/dsv/scipro/springdata/services/SupervisorService.java +++ b/core/src/main/java/se/su/dsv/scipro/springdata/services/SupervisorService.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.springdata.services; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.match.ApplicationPeriod; -import se.su.dsv.scipro.system.*; - import java.io.Serializable; import java.util.Collection; +import se.su.dsv.scipro.match.ApplicationPeriod; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Pageable; -public interface SupervisorService extends FilteredService { +public interface SupervisorService extends FilteredService { Iterable findByResearchArea(ResearchArea area, Pageable pageable); Long countByResearchArea(ResearchArea area); class FilterParams implements Serializable { + private Unit unit; private ResearchArea researchArea; private User supervisor; diff --git a/core/src/main/java/se/su/dsv/scipro/springdata/services/UserProfileService.java b/core/src/main/java/se/su/dsv/scipro/springdata/services/UserProfileService.java index 76a0f8c5d7..9a93066c34 100644 --- a/core/src/main/java/se/su/dsv/scipro/springdata/services/UserProfileService.java +++ b/core/src/main/java/se/su/dsv/scipro/springdata/services/UserProfileService.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.springdata.services; +import java.util.List; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.system.GenericService; import se.su.dsv.scipro.system.User; -import java.util.List; - public interface UserProfileService extends GenericService { UserProfile findByUser(User user); diff --git a/core/src/main/java/se/su/dsv/scipro/sukat/LDAP.java b/core/src/main/java/se/su/dsv/scipro/sukat/LDAP.java index 2d564dd4b1..e451b695aa 100644 --- a/core/src/main/java/se/su/dsv/scipro/sukat/LDAP.java +++ b/core/src/main/java/se/su/dsv/scipro/sukat/LDAP.java @@ -1,21 +1,25 @@ package se.su.dsv.scipro.sukat; -import se.su.dsv.scipro.system.Username; - +import java.util.Hashtable; +import java.util.Optional; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.*; -import java.util.Hashtable; -import java.util.Optional; +import se.su.dsv.scipro.system.Username; public class LDAP implements Sukat { + @Override public Optional email(final Username username) { try (CloseableDirContext context = createContext()) { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - final NamingEnumeration results = context.wrapped.search("dc=su,dc=se", "uid=" + getUid(username), searchControls); + final NamingEnumeration results = context.wrapped.search( + "dc=su,dc=se", + "uid=" + getUid(username), + searchControls + ); while (results.hasMore()) { final SearchResult result = results.next(); final Attribute mail = result.getAttributes().get("mail"); @@ -43,6 +47,7 @@ public class LDAP implements Sukat { } private static class CloseableDirContext implements AutoCloseable { + private final DirContext wrapped; private CloseableDirContext(final DirContext wrapped) { diff --git a/core/src/main/java/se/su/dsv/scipro/sukat/Sukat.java b/core/src/main/java/se/su/dsv/scipro/sukat/Sukat.java index d0b0e5924c..643d9bcee6 100644 --- a/core/src/main/java/se/su/dsv/scipro/sukat/Sukat.java +++ b/core/src/main/java/se/su/dsv/scipro/sukat/Sukat.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.sukat; -import se.su.dsv.scipro.system.Username; - import java.util.Optional; +import se.su.dsv.scipro.system.Username; public interface Sukat { Optional email(Username username); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/Question.java b/core/src/main/java/se/su/dsv/scipro/survey/Question.java index 4c2d6e4a73..f6726f209d 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/Question.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/Question.java @@ -11,7 +11,6 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.Table; - import java.io.Serializable; import java.util.LinkedList; import java.util.List; @@ -19,7 +18,13 @@ import java.util.List; @Entity @Table(name = "question") public class Question implements Serializable { - public enum Type { TEXT, SINGLE_CHOICE, MULTIPLE_CHOICE, GROUP_HEADING } + + public enum Type { + TEXT, + SINGLE_CHOICE, + MULTIPLE_CHOICE, + GROUP_HEADING, + } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -32,8 +37,10 @@ public class Question implements Serializable { private String text; @ElementCollection(fetch = FetchType.EAGER) - @CollectionTable(name = "question_choices", - joinColumns = @JoinColumn(name = "question_id", referencedColumnName = "id")) + @CollectionTable( + name = "question_choices", + joinColumns = @JoinColumn(name = "question_id", referencedColumnName = "id") + ) @Column(name = "choices") private List choices = new LinkedList<>(); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepository.java b/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepository.java index 90ff58ea5d..abe8e4af4f 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepository.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.survey; import se.su.dsv.scipro.system.JpaRepository; -public interface QuestionRepository extends JpaRepository { -} +public interface QuestionRepository extends JpaRepository {} diff --git a/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepositoryImpl.java index 9bc4f51e9a..8c71eaea97 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/QuestionRepositoryImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.survey; -import se.su.dsv.scipro.system.GenericRepo; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.GenericRepo; public class QuestionRepositoryImpl extends GenericRepo implements QuestionRepository { + @Inject public QuestionRepositoryImpl(final Provider em) { super(em, Question.class, QQuestion.question); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/Survey.java b/core/src/main/java/se/su/dsv/scipro/survey/Survey.java index 9c9621ec02..abbb81d80e 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/Survey.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/Survey.java @@ -9,16 +9,16 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.LinkedList; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; @Entity @Table(name = "survey") public class Survey implements Serializable { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/core/src/main/java/se/su/dsv/scipro/survey/SurveyAnswer.java b/core/src/main/java/se/su/dsv/scipro/survey/SurveyAnswer.java index f8d94e7ab9..1cb47ab28b 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/SurveyAnswer.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/SurveyAnswer.java @@ -8,6 +8,7 @@ import java.util.TreeSet; @Entity @Table(name = "survey_answer") public class SurveyAnswer implements Serializable { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -21,8 +22,10 @@ public class SurveyAnswer implements Serializable { private String answer; @ElementCollection(fetch = FetchType.EAGER) - @CollectionTable(name = "survey_answer_multiple_answers", - joinColumns = @JoinColumn(name = "survey_answer_id", referencedColumnName = "id")) + @CollectionTable( + name = "survey_answer_multiple_answers", + joinColumns = @JoinColumn(name = "survey_answer_id", referencedColumnName = "id") + ) @Column(name = "multiple_answers") private Set multipleAnswers = new TreeSet<>(); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepository.java b/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepository.java index 3b4cd92ff3..14f23b0c2d 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepository.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.survey; -import se.su.dsv.scipro.system.JpaRepository; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - import java.util.Optional; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.JpaRepository; +import se.su.dsv.scipro.system.User; public interface SurveyRepository extends JpaRepository { Optional getSurvey(Project project, User author); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepositoryImpl.java b/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepositoryImpl.java index 0ad67d6a8e..fec6ff6687 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepositoryImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/SurveyRepositoryImpl.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.survey; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.GenericRepo; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Optional; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.GenericRepo; +import se.su.dsv.scipro.system.User; public class SurveyRepositoryImpl extends GenericRepo implements SurveyRepository { + @Inject public SurveyRepositoryImpl(final Provider em) { super(em, Survey.class, QSurvey.survey); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/SurveyService.java b/core/src/main/java/se/su/dsv/scipro/survey/SurveyService.java index 5092474985..4473777207 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/SurveyService.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/SurveyService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.survey; +import java.util.List; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.List; - public interface SurveyService { void submit(Survey modelObject); diff --git a/core/src/main/java/se/su/dsv/scipro/survey/SurveyServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/survey/SurveyServiceImpl.java index 386c771880..da11f93cb2 100644 --- a/core/src/main/java/se/su/dsv/scipro/survey/SurveyServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/survey/SurveyServiceImpl.java @@ -1,14 +1,7 @@ package se.su.dsv.scipro.survey; -import jakarta.transaction.Transactional; -import se.su.dsv.scipro.finalthesis.FinalThesisService; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.reflection.ReflectionService; -import se.su.dsv.scipro.system.User; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; @@ -18,6 +11,12 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; +import se.su.dsv.scipro.finalthesis.FinalThesisService; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.reflection.ReflectionService; +import se.su.dsv.scipro.system.User; public class SurveyServiceImpl implements SurveyService { @@ -29,12 +28,12 @@ public class SurveyServiceImpl implements SurveyService { @Inject public SurveyServiceImpl( - final SurveyRepository surveyRepository, - final QuestionRepository questionRepository, - final FinalThesisService finalThesisService, - final GeneralSystemSettingsService generalSystemSettingsService, - ReflectionService reflectionService) - { + final SurveyRepository surveyRepository, + final QuestionRepository questionRepository, + final FinalThesisService finalThesisService, + final GeneralSystemSettingsService generalSystemSettingsService, + ReflectionService reflectionService + ) { this.surveyRepository = surveyRepository; this.questionRepository = questionRepository; this.finalThesisService = finalThesisService; @@ -51,8 +50,7 @@ public class SurveyServiceImpl implements SurveyService { @Override public Survey getSurvey(final Project project, final User author) { - return surveyRepository.getSurvey(project, author) - .orElseGet(() -> generateSurvey(project, author)); + return surveyRepository.getSurvey(project, author).orElseGet(() -> generateSurvey(project, author)); } @Override @@ -62,8 +60,12 @@ public class SurveyServiceImpl implements SurveyService { final boolean hasFinalThesis = finalThesisService.hasFinalThesis(project); final Optional survey = surveyRepository.getSurvey(project, user); final boolean submittedSurvey = survey.isPresent() && survey.get().isSubmitted(); - final boolean surveyAvailable = generalSystemSettingsService.getGeneralSystemSettingsInstance().isFinalSurveyAvailable(); - return surveyAvailable && hasFinalThesis && !submittedSurvey && !questions.isEmpty() && !hasToFillInReflection; + final boolean surveyAvailable = generalSystemSettingsService + .getGeneralSystemSettingsInstance() + .isFinalSurveyAvailable(); + return ( + surveyAvailable && hasFinalThesis && !submittedSurvey && !questions.isEmpty() && !hasToFillInReflection + ); } @Override @@ -78,11 +80,7 @@ public class SurveyServiceImpl implements SurveyService { public void saveQuestion(final Question question) { if (question.getOrder() == 0) { // New question - final int order = questionRepository.findAll() - .stream() - .mapToInt(Question::getOrder) - .max() - .orElse(0); + final int order = questionRepository.findAll().stream().mapToInt(Question::getOrder).max().orElse(0); question.setOrder(order + 1); // Move last / 1-index } questionRepository.save(question); @@ -93,14 +91,15 @@ public class SurveyServiceImpl implements SurveyService { public void deleteQuestion(final Question question) { final int gap = question.getOrder(); questionRepository.delete(question); - questionRepository.findAll() - .stream() - .filter(remainingQuestion -> remainingQuestion.getOrder() > gap) - .forEach(remainingQuestion -> { - // Move up - remainingQuestion.setOrder(remainingQuestion.getOrder() - 1); - questionRepository.save(remainingQuestion); - }); + questionRepository + .findAll() + .stream() + .filter(remainingQuestion -> remainingQuestion.getOrder() > gap) + .forEach(remainingQuestion -> { + // Move up + remainingQuestion.setOrder(remainingQuestion.getOrder() - 1); + questionRepository.save(remainingQuestion); + }); } @Override @@ -118,11 +117,12 @@ public class SurveyServiceImpl implements SurveyService { } private void swapToOrder(final Question question, final int targetOrder) { - questionRepository.findAll() - .stream() - .filter(otherQuestion -> otherQuestion.getOrder() == targetOrder) - .findAny() - .ifPresent(otherQuestion -> swap(question, otherQuestion)); + questionRepository + .findAll() + .stream() + .filter(otherQuestion -> otherQuestion.getOrder() == targetOrder) + .findAny() + .ifPresent(otherQuestion -> swap(question, otherQuestion)); } private void swap(final Question question, final Question otherQuestion) { @@ -141,42 +141,43 @@ public class SurveyServiceImpl implements SurveyService { @Override @Transactional public void setAvailability(final boolean availability) { - final GeneralSystemSettings generalSystemSettings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); + final GeneralSystemSettings generalSystemSettings = + generalSystemSettingsService.getGeneralSystemSettingsInstance(); generalSystemSettings.setFinalSurveyAvailable(availability); generalSystemSettingsService.save(generalSystemSettings); } @Override public SurveyStatistics getStatistics(Filter filter) { - List surveys = surveyRepository.findAll() - .stream() - .filter(applyFilter(filter)) - .toList(); + List surveys = surveyRepository.findAll().stream().filter(applyFilter(filter)).toList(); List questions = getQuestions(); - Map> m = surveys.stream() - .map(Survey::getAnswers) - .flatMap(Collection::stream) - .collect(Collectors.groupingBy(SurveyAnswer::getQuestion)); + Map> m = surveys + .stream() + .map(Survey::getAnswers) + .flatMap(Collection::stream) + .collect(Collectors.groupingBy(SurveyAnswer::getQuestion)); ArrayList questionStatistics = new ArrayList<>(); for (Question question : questions) { final List surveyAnswers = m.getOrDefault(question, List.of()); switch (question.getType()) { case TEXT -> { - List answers = surveyAnswers.stream() - .map(SurveyAnswer::getAnswer) - .filter(Objects::nonNull) - .filter(Predicate.not(String::isBlank)) - .toList(); + List answers = surveyAnswers + .stream() + .map(SurveyAnswer::getAnswer) + .filter(Objects::nonNull) + .filter(Predicate.not(String::isBlank)) + .toList(); questionStatistics.add(new SurveyStatistics.Question.Text(question.getText(), answers)); } case SINGLE_CHOICE -> { ArrayList choices = new ArrayList<>(); for (String choice : question.getChoices()) { - long answers = surveyAnswers.stream() - .map(SurveyAnswer::getAnswer) - .filter(choice::equals) - .count(); + long answers = surveyAnswers + .stream() + .map(SurveyAnswer::getAnswer) + .filter(choice::equals) + .count(); choices.add(new SurveyStatistics.Question.Choice(choice, answers)); } questionStatistics.add(new SurveyStatistics.Question.Single(question.getText(), choices)); @@ -184,16 +185,16 @@ public class SurveyServiceImpl implements SurveyService { case MULTIPLE_CHOICE -> { ArrayList choices = new ArrayList<>(); for (String choice : question.getChoices()) { - long answers = surveyAnswers.stream() - .map(SurveyAnswer::getMultipleAnswers) - .filter(a -> a.contains(choice)) - .count(); + long answers = surveyAnswers + .stream() + .map(SurveyAnswer::getMultipleAnswers) + .filter(a -> a.contains(choice)) + .count(); choices.add(new SurveyStatistics.Question.Choice(choice, answers)); } questionStatistics.add(new SurveyStatistics.Question.Multi(question.getText(), choices)); } - case GROUP_HEADING -> { - } + case GROUP_HEADING -> {} } } return new SurveyStatistics(surveys.size(), questionStatistics); @@ -201,7 +202,10 @@ public class SurveyServiceImpl implements SurveyService { private Predicate applyFilter(Filter filter) { return survey -> { - if (filter.supervisor() != null && !Objects.equals(filter.supervisor(), survey.getProject().getHeadSupervisor())) { + if ( + filter.supervisor() != null && + !Objects.equals(filter.supervisor(), survey.getProject().getHeadSupervisor()) + ) { return false; } return true; @@ -211,14 +215,15 @@ public class SurveyServiceImpl implements SurveyService { private Survey generateSurvey(final Project project, final User author) { final Survey survey = new Survey(); final List questions = getQuestions(); - final List answers = questions.stream() - .map(question -> { - final SurveyAnswer answer = new SurveyAnswer(); - answer.setSurvey(survey); - answer.setQuestion(question); - return answer; - }) - .toList(); + final List answers = questions + .stream() + .map(question -> { + final SurveyAnswer answer = new SurveyAnswer(); + answer.setSurvey(survey); + answer.setQuestion(question); + return answer; + }) + .toList(); survey.setProject(project); survey.setUser(author); survey.setAnswers(answers); diff --git a/core/src/main/java/se/su/dsv/scipro/system/AbstractRepository.java b/core/src/main/java/se/su/dsv/scipro/system/AbstractRepository.java index 1eb4166edc..313e30e57e 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/AbstractRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/system/AbstractRepository.java @@ -1,9 +1,7 @@ package se.su.dsv.scipro.system; - import com.querydsl.core.types.EntityPath; import com.querydsl.jpa.impl.JPAQuery; - import jakarta.inject.Provider; import jakarta.persistence.EntityManager; diff --git a/core/src/main/java/se/su/dsv/scipro/system/AbstractServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/AbstractServiceImpl.java index f6d52a414b..4f7cbf6db5 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/AbstractServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/AbstractServiceImpl.java @@ -1,22 +1,24 @@ package se.su.dsv.scipro.system; -import jakarta.transaction.Transactional; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.EntityPathBase; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.StringPath; import com.querydsl.jpa.impl.JPAQuery; - import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.io.Serializable; import java.util.List; -public class AbstractServiceImpl extends AbstractRepository implements GenericService { +public class AbstractServiceImpl + extends AbstractRepository + implements GenericService { + private final Class clazz; private final EntityPathBase path; - protected AbstractServiceImpl(Provider em, Class clazz, EntityPathBase path) { + protected AbstractServiceImpl(Provider em, Class clazz, EntityPathBase path) { super(em); this.clazz = clazz; this.path = path; @@ -49,7 +51,7 @@ public class AbstractServiceImpl extends AbstractRep @Override public long count(Predicate predicate) { - return createQuery().where(predicate).select(path.count()).fetchFirst(); + return createQuery().where(predicate).select(path.count()).fetchFirst(); } @Override @@ -73,8 +75,7 @@ public class AbstractServiceImpl extends AbstractRep EntityManager entityManager = em(); if (entityManager.contains(entity)) { return entityManager.merge(entity); - } - else { + } else { entityManager.persist(entity); return entity; } @@ -82,8 +83,8 @@ public class AbstractServiceImpl extends AbstractRep @Override public T findOne(ID id) { - return em().find(clazz, id); - } + return em().find(clazz, id); + } @Override public List findAll() { @@ -97,14 +98,14 @@ public class AbstractServiceImpl extends AbstractRep @Override public long count() { - return createQuery().select(path.count()).fetchFirst(); - } + return createQuery().select(path.count()).fetchFirst(); + } @Override @Transactional - public void delete(ID id) { - delete(em().getReference(clazz, id)); - } + public void delete(ID id) { + delete(em().getReference(clazz, id)); + } @Override @Transactional diff --git a/core/src/main/java/se/su/dsv/scipro/system/AggregateUserSearch.java b/core/src/main/java/se/su/dsv/scipro/system/AggregateUserSearch.java index 400776d582..907cef2e18 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/AggregateUserSearch.java +++ b/core/src/main/java/se/su/dsv/scipro/system/AggregateUserSearch.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.system; -import se.su.dsv.scipro.security.auth.roles.Roles; - import jakarta.inject.Inject; import java.util.Collection; import java.util.Comparator; import java.util.Set; +import se.su.dsv.scipro.security.auth.roles.Roles; public class AggregateUserSearch implements UserSearchService { + private final Set userSearchProviders; private final UserService userService; @@ -19,12 +19,13 @@ public class AggregateUserSearch implements UserSearchService { @Override public Collection search(String term, Set role, long maxResults) { - return userSearchProviders.stream() - .sorted(Comparator.comparing(UserSearchProvider::priority).reversed()) - .map(provider -> provider.search(term, role, maxResults)) - .flatMap(Collection::stream) - .limit(maxResults) - .toList(); + return userSearchProviders + .stream() + .sorted(Comparator.comparing(UserSearchProvider::priority).reversed()) + .map(provider -> provider.search(term, role, maxResults)) + .flatMap(Collection::stream) + .limit(maxResults) + .toList(); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/system/DomainObject.java b/core/src/main/java/se/su/dsv/scipro/system/DomainObject.java index ebcdbb5627..b9f56bf3df 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/DomainObject.java +++ b/core/src/main/java/se/su/dsv/scipro/system/DomainObject.java @@ -16,25 +16,25 @@ public abstract class DomainObject implements Serializable { @Version @Column(nullable = false) - private int version=0; + private int version = 0; public abstract Long getId(); @PreUpdate @PrePersist - public void updateTimeStamps() { - lastModified = new Date(); - } + public void updateTimeStamps() { + lastModified = new Date(); + } @Override public boolean equals(Object obj) { - if(this == obj) { + if (this == obj) { return true; } - if(obj == null) { + if (obj == null) { return false; } - if(this.getClass() != obj.getClass()) { + if (this.getClass() != obj.getClass()) { return false; } final DomainObject other = (DomainObject) obj; @@ -46,7 +46,7 @@ public abstract class DomainObject implements Serializable { @Override public int hashCode() { int result = 17; - result = 31 * result + (getId()==null?0:getId().hashCode()); + result = 31 * result + (getId() == null ? 0 : getId().hashCode()); return result; } @@ -68,6 +68,14 @@ public abstract class DomainObject implements Serializable { @Override public String toString() { - return "DomainObject(dateCreated=" + this.getDateCreated() + ", lastModified=" + this.getLastModified() + ", version=" + this.version + ")"; + return ( + "DomainObject(dateCreated=" + + this.getDateCreated() + + ", lastModified=" + + this.getLastModified() + + ", version=" + + this.version + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/Event.java b/core/src/main/java/se/su/dsv/scipro/system/Event.java index be417ccb9a..f91f0eced4 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/Event.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Event.java @@ -5,13 +5,13 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import java.io.Serializable; import java.util.Objects; @Entity @Table(name = "event") public class Event implements Serializable { + // ---------------------------------------------------------------------------------- // Basic JPA-mappings // ---------------------------------------------------------------------------------- @@ -25,8 +25,7 @@ public class Event implements Serializable { // ---------------------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------------------- - protected Event() { - } + protected Event() {} // ---------------------------------------------------------------------------------- // Properties (Getters) @@ -51,8 +50,7 @@ public class Event implements Serializable { if (o == this) return true; if (!(o instanceof Event)) return false; final Event other = (Event) o; - return other.canEqual(this) - && Objects.equals(this.getName(), other.getName()); + return (other.canEqual(this) && Objects.equals(this.getName(), other.getName())); } @Override @@ -62,7 +60,6 @@ public class Event implements Serializable { @Override public String toString() { - return "Event(name=" + this.getName() + ", description=" + - this.getDescription() + ")"; + return ("Event(name=" + this.getName() + ", description=" + this.getDescription() + ")"); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/EventServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/EventServiceImpl.java index 3fbcbc485e..8723f47fb9 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/EventServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/EventServiceImpl.java @@ -7,6 +7,7 @@ import jakarta.persistence.EntityManager; @Named public class EventServiceImpl extends AbstractServiceImpl implements EventService { + @Inject public EventServiceImpl(Provider em) { super(em, Event.class, QEvent.event); diff --git a/core/src/main/java/se/su/dsv/scipro/system/ExternalResource.java b/core/src/main/java/se/su/dsv/scipro/system/ExternalResource.java index 008e47babe..e631939f91 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/ExternalResource.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ExternalResource.java @@ -8,12 +8,12 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - import java.util.Objects; @Entity @Table(name = "external_resource") public class ExternalResource { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -67,11 +67,13 @@ public class ExternalResource { if (o == this) return true; if (!(o instanceof ExternalResource)) return false; final ExternalResource other = (ExternalResource) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getLabel(), other.getLabel()) - && Objects.equals(this.getUrl(), other.getUrl()) - && Objects.equals(this.getRelevantFor(), other.getRelevantFor()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getLabel(), other.getLabel()) && + Objects.equals(this.getUrl(), other.getUrl()) && + Objects.equals(this.getRelevantFor(), other.getRelevantFor()) + ); } protected boolean canEqual(final Object other) { @@ -85,6 +87,16 @@ public class ExternalResource { @Override public String toString() { - return "ExternalResource(id=" + this.getId() + ", label=" + this.getLabel() + ", url=" + this.getUrl() + ", relevantFor=" + this.getRelevantFor() + ")"; + return ( + "ExternalResource(id=" + + this.getId() + + ", label=" + + this.getLabel() + + ", url=" + + this.getUrl() + + ", relevantFor=" + + this.getRelevantFor() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/ExternalResourceServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/ExternalResourceServiceImpl.java index 22e90d4d9c..b216cdb158 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/ExternalResourceServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ExternalResourceServiceImpl.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.system; import com.querydsl.jpa.impl.JPAQuery; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; public class ExternalResourceServiceImpl implements ExternalResourceService { + private final Provider em; @Inject @@ -18,8 +18,8 @@ public class ExternalResourceServiceImpl implements ExternalResourceService { @Override public List findBy(final ProjectType projectType) { return new JPAQuery(em.get()) - .from(QExternalResource.externalResource) - .where(QExternalResource.externalResource.relevantFor.eq(projectType)) - .fetch(); + .from(QExternalResource.externalResource) + .where(QExternalResource.externalResource.relevantFor.eq(projectType)) + .fetch(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterAddress.java b/core/src/main/java/se/su/dsv/scipro/system/FooterAddress.java index 64ba066d7b..96d0bb83eb 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterAddress.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterAddress.java @@ -6,7 +6,7 @@ import java.util.Objects; @Entity @Cacheable @Table(name = "footer_address") -public class FooterAddress extends DomainObject{ +public class FooterAddress extends DomainObject { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -45,7 +45,9 @@ public class FooterAddress extends DomainObject{ @Override public String toString() { - return "FooterAddress(id=" + this.getId() + ", title=" + this.getTitle() + ", address=" + this.getAddress() + ")"; + return ( + "FooterAddress(id=" + this.getId() + ", title=" + this.getTitle() + ", address=" + this.getAddress() + ")" + ); } @Override @@ -53,8 +55,7 @@ public class FooterAddress extends DomainObject{ if (o == this) return true; if (!(o instanceof FooterAddress)) return false; final FooterAddress other = (FooterAddress) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepo.java b/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepo.java index b326a9c967..abdcb45039 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepo.java @@ -3,5 +3,5 @@ package se.su.dsv.scipro.system; import jakarta.transaction.Transactional; @Transactional -public interface FooterAddressRepo extends JpaRepository, QueryDslPredicateExecutor { -} +public interface FooterAddressRepo + extends JpaRepository, QueryDslPredicateExecutor {} diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepoImpl.java index cb10abb4a2..6925c06f26 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterAddressRepoImpl.java @@ -5,6 +5,7 @@ import jakarta.inject.Provider; import jakarta.persistence.EntityManager; public class FooterAddressRepoImpl extends GenericRepo implements FooterAddressRepo { + @Inject public FooterAddressRepoImpl(Provider em) { super(em, FooterAddress.class, QFooterAddress.footerAddress); diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterColumn.java b/core/src/main/java/se/su/dsv/scipro/system/FooterColumn.java index bf43f08152..5d3d777e94 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterColumn.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterColumn.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.system; - public enum FooterColumn { FIRST, SECOND, THIRD, - FOURTH + FOURTH, } diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterLink.java b/core/src/main/java/se/su/dsv/scipro/system/FooterLink.java index 68a84f622f..7620a5e821 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterLink.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterLink.java @@ -69,7 +69,19 @@ public class FooterLink extends DomainObject { @Override public String toString() { - return "FooterLink(id=" + this.getId() + ", footerColumn=" + this.getFooterColumn() + ", title=" + this.getTitle() + ", url=" + this.getUrl() + ", order=" + this.getOrder() + ")"; + return ( + "FooterLink(id=" + + this.getId() + + ", footerColumn=" + + this.getFooterColumn() + + ", title=" + + this.getTitle() + + ", url=" + + this.getUrl() + + ", order=" + + this.getOrder() + + ")" + ); } @Override @@ -77,8 +89,7 @@ public class FooterLink extends DomainObject { if (o == this) return true; if (!(o instanceof FooterLink)) return false; final FooterLink other = (FooterLink) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -89,4 +100,4 @@ public class FooterLink extends DomainObject { public int hashCode() { return Objects.hashCode(this.getId()); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepo.java b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepo.java index 8994ba19ae..c236e49890 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepo.java @@ -1,7 +1,6 @@ package se.su.dsv.scipro.system; import jakarta.transaction.Transactional; - import java.util.List; import java.util.Optional; diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepoImpl.java index 382a24185e..e319e8d1c1 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkRepoImpl.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Optional; public class FooterLinkRepoImpl extends GenericRepo implements FooterLinkRepo { + @Inject public FooterLinkRepoImpl(Provider em) { super(em, FooterLink.class, QFooterLink.footerLink); @@ -15,14 +16,15 @@ public class FooterLinkRepoImpl extends GenericRepo implements @Override public List getLinks(final FooterColumn column) { return createQuery() - .where(QFooterLink.footerLink.footerColumn.eq(column)) - .orderBy(QFooterLink.footerLink.order.asc()) - .fetch(); + .where(QFooterLink.footerLink.footerColumn.eq(column)) + .orderBy(QFooterLink.footerLink.order.asc()) + .fetch(); } @Override public Optional findByColumnAndOrder(final FooterColumn column, final int order) { - return Optional.ofNullable(findOne( - QFooterLink.footerLink.footerColumn.eq(column).and(QFooterLink.footerLink.order.eq(order)))); + return Optional.ofNullable( + findOne(QFooterLink.footerLink.footerColumn.eq(column).and(QFooterLink.footerLink.order.eq(order))) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkServiceImpl.java index 901a487f84..23ecad256c 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/FooterLinkServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/FooterLinkServiceImpl.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.system; -import jakarta.transaction.Transactional; - import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import java.util.List; public class FooterLinkServiceImpl implements FooterLinkService { @@ -27,8 +26,7 @@ public class FooterLinkServiceImpl implements FooterLinkService { } private void swapToOrder(FooterLink link, int targetOrder) { - repository.findByColumnAndOrder(link.getFooterColumn(), targetOrder) - .ifPresent(other -> swap(link, other)); + repository.findByColumnAndOrder(link.getFooterColumn(), targetOrder).ifPresent(other -> swap(link, other)); } private void swap(FooterLink link, FooterLink other) { @@ -62,4 +60,4 @@ public class FooterLinkServiceImpl implements FooterLinkService { public FooterLink save(FooterLink link) { return repository.save(applyOrder(link)); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/GenericRepo.java b/core/src/main/java/se/su/dsv/scipro/system/GenericRepo.java index 07ae33135f..71676486e8 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/GenericRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/system/GenericRepo.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.system; -import jakarta.transaction.Transactional; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.EntityPathBase; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.StringPath; import com.querydsl.jpa.impl.JPAQuery; - import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import java.io.Serializable; import java.util.List; @@ -44,8 +43,7 @@ public class GenericRepo implements QueryDslPredicat private JPAQuery sorted(JPAQuery query, Sort sort) { if (sort == null) { return query; - } - else { + } else { StringPath property = Expressions.stringPath(path, sort.getProperty()); return query.orderBy(sort.isAscending() ? property.asc() : property.desc()); } diff --git a/core/src/main/java/se/su/dsv/scipro/system/GenericService.java b/core/src/main/java/se/su/dsv/scipro/system/GenericService.java index 31efa33888..bdab81bb15 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/GenericService.java +++ b/core/src/main/java/se/su/dsv/scipro/system/GenericService.java @@ -1,18 +1,16 @@ package se.su.dsv.scipro.system; import com.querydsl.core.types.Predicate; - import java.io.Serializable; import java.util.List; public interface GenericService { - S save(S entity); - T findOne(ID id); - void delete(ID id); + T findOne(ID id); + void delete(ID id); void delete(T entity); - long count(); + long count(); List findAll(); List findAll(Pageable pageable); diff --git a/core/src/main/java/se/su/dsv/scipro/system/JpaRepository.java b/core/src/main/java/se/su/dsv/scipro/system/JpaRepository.java index 1d6165771b..7a2199c2da 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/JpaRepository.java +++ b/core/src/main/java/se/su/dsv/scipro/system/JpaRepository.java @@ -51,5 +51,4 @@ public interface JpaRepository { * @throws IllegalArgumentException in case the given entity is (@literal null}. */ void delete(T entity); - -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/Language.java b/core/src/main/java/se/su/dsv/scipro/system/Language.java index 8ea02a4884..ebff05a55c 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/Language.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Language.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.system; public enum Language { - SWEDISH, ENGLISH + SWEDISH, + ENGLISH, } diff --git a/core/src/main/java/se/su/dsv/scipro/system/LazyDeletableDomainObject.java b/core/src/main/java/se/su/dsv/scipro/system/LazyDeletableDomainObject.java index 0c108dc1c4..cae38dc7ed 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/LazyDeletableDomainObject.java +++ b/core/src/main/java/se/su/dsv/scipro/system/LazyDeletableDomainObject.java @@ -4,6 +4,7 @@ import jakarta.persistence.MappedSuperclass; @MappedSuperclass public abstract class LazyDeletableDomainObject extends DomainObject { + private boolean deleted = false; public void setDeleted(boolean deleted) { diff --git a/core/src/main/java/se/su/dsv/scipro/system/LocalUserSearch.java b/core/src/main/java/se/su/dsv/scipro/system/LocalUserSearch.java index 90a2cc05f8..5272d03583 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/LocalUserSearch.java +++ b/core/src/main/java/se/su/dsv/scipro/system/LocalUserSearch.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.system; -import se.su.dsv.scipro.security.auth.roles.Roles; - import jakarta.inject.Inject; import java.util.Collection; import java.util.Set; +import se.su.dsv.scipro.security.auth.roles.Roles; public class LocalUserSearch implements UserSearchProvider { + private final UserRepo userRepo; @Inject diff --git a/core/src/main/java/se/su/dsv/scipro/system/MergeServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/MergeServiceImpl.java index e14516ffb9..3fb6b6bb9a 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/MergeServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/MergeServiceImpl.java @@ -1,18 +1,15 @@ package se.su.dsv.scipro.system; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; -import jakarta.inject.Inject; - public class MergeServiceImpl implements MergeService { + private final UserNameService userNameService; private final UserService userService; @Inject - public MergeServiceImpl( - final UserNameService userNameService, - final UserService userService) - { + public MergeServiceImpl(final UserNameService userNameService, final UserService userService) { this.userNameService = userNameService; this.userService = userService; } diff --git a/core/src/main/java/se/su/dsv/scipro/system/Page.java b/core/src/main/java/se/su/dsv/scipro/system/Page.java index dea8356db4..2b84fbe1d7 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/Page.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Page.java @@ -2,7 +2,8 @@ package se.su.dsv.scipro.system; public interface Page { enum Direction { - ASCENDING, DESCENDING + ASCENDING, + DESCENDING, } record Sort(S sortBy, Direction direction) {} diff --git a/core/src/main/java/se/su/dsv/scipro/system/PageRequest.java b/core/src/main/java/se/su/dsv/scipro/system/PageRequest.java index 6d7ca6d6c2..cd20043c41 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/PageRequest.java +++ b/core/src/main/java/se/su/dsv/scipro/system/PageRequest.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.system; import java.util.Objects; public class PageRequest implements Pageable { + private final long offset; private final long limit; private final Sort sort; @@ -37,10 +38,12 @@ public class PageRequest implements Pageable { if (o == this) return true; if (!(o instanceof PageRequest)) return false; final PageRequest other = (PageRequest) o; - return other.canEqual(this) - && this.getOffset() == other.getOffset() - && this.getLimit() == other.getLimit() - && Objects.equals(this.getSort(), other.getSort()); + return ( + other.canEqual(this) && + this.getOffset() == other.getOffset() && + this.getLimit() == other.getLimit() && + Objects.equals(this.getSort(), other.getSort()) + ); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/system/Password.java b/core/src/main/java/se/su/dsv/scipro/system/Password.java index 8cc600ed24..46377a3706 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/Password.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Password.java @@ -7,13 +7,13 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.util.Arrays; import java.util.Objects; @Entity @Table(name = "password") public class Password extends LazyDeletableDomainObject { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -27,9 +27,7 @@ public class Password extends LazyDeletableDomainObject { @Column private byte[] salt; - public Password() { - - } + public Password() {} @Override public Long getId() { @@ -58,12 +56,18 @@ public class Password extends LazyDeletableDomainObject { @Override public String toString() { - return "Password{" + - "id=" + id + - ", user=" + user + - ", hash=" + Arrays.toString(hash) + - ", salt=" + Arrays.toString(salt) + - '}'; + return ( + "Password{" + + "id=" + + id + + ", user=" + + user + + ", hash=" + + Arrays.toString(hash) + + ", salt=" + + Arrays.toString(salt) + + '}' + ); } @Override @@ -71,12 +75,14 @@ public class Password extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof Password)) return false; final Password other = (Password) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.user, other.user) - && Arrays.equals(this.getHash(), other.getHash()) - && Arrays.equals(this.getSalt(), other.getSalt()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.user, other.user) && + Arrays.equals(this.getHash(), other.getHash()) && + Arrays.equals(this.getSalt(), other.getSalt()) + ); } protected boolean canEqual(final Object other) { @@ -85,6 +91,12 @@ public class Password extends LazyDeletableDomainObject { @Override public int hashCode() { - return Objects.hash(super.hashCode(), this.getId(), this.user, Arrays.hashCode(this.getHash()), Arrays.hashCode(this.getSalt())); + return Objects.hash( + super.hashCode(), + this.getId(), + this.user, + Arrays.hashCode(this.getHash()), + Arrays.hashCode(this.getSalt()) + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/PasswordHandler.java b/core/src/main/java/se/su/dsv/scipro/system/PasswordHandler.java index 9bd1150feb..6f600d69c5 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/PasswordHandler.java +++ b/core/src/main/java/se/su/dsv/scipro/system/PasswordHandler.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.system; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; /** * Class for generating password hashes, and for checking password matches. @@ -14,14 +13,14 @@ import java.security.spec.KeySpec; * @author Arian Jafari */ public final class PasswordHandler { + private static final int ITERATION_COUNT = 65536; private static final int KEY_LENGTH = 128; private static final int SALT_LENGTH = 32; private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; private static final SecureRandom RANDOM = new SecureRandom(); - private PasswordHandler() { - } + private PasswordHandler() {} public static byte[] generateSalt() { byte[] salt = new byte[SALT_LENGTH]; diff --git a/core/src/main/java/se/su/dsv/scipro/system/PasswordRepo.java b/core/src/main/java/se/su/dsv/scipro/system/PasswordRepo.java index 53dfe5d7a8..bbd1d88a80 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/PasswordRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/system/PasswordRepo.java @@ -2,8 +2,7 @@ package se.su.dsv.scipro.system; import jakarta.transaction.Transactional; - @Transactional public interface PasswordRepo extends JpaRepository, QueryDslPredicateExecutor { Password findByUser(User user); -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/PasswordRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/system/PasswordRepoImpl.java index 59c34eb5c5..ba0504618b 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/PasswordRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/PasswordRepoImpl.java @@ -5,6 +5,7 @@ import jakarta.inject.Provider; import jakarta.persistence.EntityManager; public class PasswordRepoImpl extends GenericRepo implements PasswordRepo { + @Inject public PasswordRepoImpl(Provider em) { super(em, Password.class, QPassword.password); diff --git a/core/src/main/java/se/su/dsv/scipro/system/Program.java b/core/src/main/java/se/su/dsv/scipro/system/Program.java index f2aba4587d..8a30933658 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/Program.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Program.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.system; -import java.util.Objects; - import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; +import java.util.Objects; @Entity @Table(name = "program") @@ -73,7 +72,19 @@ public class Program extends DomainObject { @Override public String toString() { - return "Program(id=" + this.getId() + ", externalId=" + this.getExternalId() + ", name=" + this.getName() + ", nameEn=" + this.getNameEn() + ", code=" + this.getCode() + ")"; + return ( + "Program(id=" + + this.getId() + + ", externalId=" + + this.getExternalId() + + ", name=" + + this.getName() + + ", nameEn=" + + this.getNameEn() + + ", code=" + + this.getCode() + + ")" + ); } @Override @@ -81,8 +92,7 @@ public class Program extends DomainObject { if (o == this) return true; if (!(o instanceof Program)) return false; final Program other = (Program) o; - return other.canEqual(this) - && Objects.equals(this.getExternalId(), other.getExternalId()); + return (other.canEqual(this) && Objects.equals(this.getExternalId(), other.getExternalId())); } protected boolean canEqual(final Object other) { @@ -93,4 +103,4 @@ public class Program extends DomainObject { public int hashCode() { return Objects.hashCode(this.getExternalId()); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/ProjectType.java b/core/src/main/java/se/su/dsv/scipro/system/ProjectType.java index b3f8849870..a83fb7b8f7 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/ProjectType.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ProjectType.java @@ -1,9 +1,5 @@ package se.su.dsv.scipro.system; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; - import jakarta.persistence.Basic; import jakarta.persistence.Cacheable; import jakarta.persistence.CascadeType; @@ -20,62 +16,66 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.Lob; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; @Entity @Cacheable(true) @Table(name = "project_type") public class ProjectType extends LazyDeletableDomainObject { - public static final DegreeType MASTER = DegreeType.MASTER; - public static final DegreeType BACHELOR = DegreeType.BACHELOR; - public static final DegreeType MAGISTER = DegreeType.MAGISTER; - public static final DegreeType UNKNOWN = DegreeType.NONE; + + public static final DegreeType MASTER = DegreeType.MASTER; + public static final DegreeType BACHELOR = DegreeType.BACHELOR; + public static final DegreeType MAGISTER = DegreeType.MAGISTER; + public static final DegreeType UNKNOWN = DegreeType.NONE; public static final int HP_30 = 30; public static final int HP_15 = 15; @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Basic(optional=false) - private String name; + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @OneToOne(mappedBy= "projectType", orphanRemoval = true, cascade = CascadeType.ALL) - private ProjectTypeSettings projectTypeSettings = new ProjectTypeSettings(this); + @Basic(optional = false) + private String name; + + @OneToOne(mappedBy = "projectType", orphanRemoval = true, cascade = CascadeType.ALL) + private ProjectTypeSettings projectTypeSettings = new ProjectTypeSettings(this); @Enumerated(EnumType.STRING) @Column(name = "degree_type", nullable = false) private DegreeType degreeType = DegreeType.NONE; - - @Lob - private String description; + + @Lob + private String description; @ElementCollection @Enumerated(EnumType.STRING) - @CollectionTable(name = "project_type_project_module", - joinColumns = @JoinColumn(name = "project_type_id", referencedColumnName = "id")) + @CollectionTable( + name = "project_type_project_module", + joinColumns = @JoinColumn(name = "project_type_id", referencedColumnName = "id") + ) @Column(name = "project_module") private Set projectModules = EnumSet.allOf(ProjectModule.class); @Basic(optional = false) private boolean reviewed = true; - public ProjectType() { + public ProjectType() {} - } - - public ProjectType(DegreeType degreeType, String name, String description) { + public ProjectType(DegreeType degreeType, String name, String description) { this.degreeType = degreeType; this.name = name; this.description = description; } - public int getMaxOpponents() { - return projectTypeSettings.getMaxOpponentsOnFinalSeminar(); - } - - public int getMaxActiveParticipants() { - return projectTypeSettings.getMaxFinalSeminarActiveParticipation(); - } + public int getMaxOpponents() { + return projectTypeSettings.getMaxOpponentsOnFinalSeminar(); + } + + public int getMaxActiveParticipants() { + return projectTypeSettings.getMaxFinalSeminarActiveParticipation(); + } public int getMinAuthors() { return projectTypeSettings.getMinAuthors(); @@ -162,10 +162,12 @@ public class ProjectType extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof ProjectType)) return false; final ProjectType other = (ProjectType) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getName(), other.getName()); + return ( + other.canEqual(this) && + super.equals(o) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getName(), other.getName()) + ); } protected boolean canEqual(final Object other) { @@ -174,11 +176,23 @@ public class ProjectType extends LazyDeletableDomainObject { @Override public int hashCode() { - return Objects.hash(this.getId(), this.getName()); + return Objects.hash(this.getId(), this.getName()); } @Override public String toString() { - return "ProjectType(id=" + this.getId() + ", name=" + this.getName() + ", degreeType=" + this.getDegreeType() + ", description=" + this.getDescription() + ", reviewed=" + this.isReviewed() + ")"; + return ( + "ProjectType(id=" + + this.getId() + + ", name=" + + this.getName() + + ", degreeType=" + + this.getDegreeType() + + ", description=" + + this.getDescription() + + ", reviewed=" + + this.isReviewed() + + ")" + ); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeServiceImpl.java index d631c86db9..7152e11d3a 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeServiceImpl.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.system; -import com.querydsl.core.types.dsl.BooleanExpression; -import se.su.dsv.scipro.project.QProject; +import static com.querydsl.core.types.dsl.Expressions.allOf; +import static com.querydsl.core.types.dsl.Expressions.anyOf; +import com.querydsl.core.types.dsl.BooleanExpression; import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Collection; import java.util.List; +import se.su.dsv.scipro.project.QProject; -import static com.querydsl.core.types.dsl.Expressions.allOf; -import static com.querydsl.core.types.dsl.Expressions.anyOf; - -public class ProjectTypeServiceImpl extends AbstractServiceImpl implements ProjectTypeService { +public class ProjectTypeServiceImpl extends AbstractServiceImpl implements ProjectTypeService { @Inject public ProjectTypeServiceImpl(Provider em) { @@ -43,12 +42,16 @@ public class ProjectTypeServiceImpl extends AbstractServiceImpl findBySupervisorProjects(User supervisor) { final QProject project = QProject.project; return from(project) - .select(project.projectType) - .distinct() - .where(anyOf(project.headSupervisor.eq(supervisor), - project.reviewers.any().eq(supervisor), - project.coSupervisors.any().eq(supervisor))) - .fetch(); + .select(project.projectType) + .distinct() + .where( + anyOf( + project.headSupervisor.eq(supervisor), + project.reviewers.any().eq(supervisor), + project.coSupervisors.any().eq(supervisor) + ) + ) + .fetch(); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeSettings.java b/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeSettings.java index 2c64d6629d..bcf67d378a 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeSettings.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ProjectTypeSettings.java @@ -9,209 +9,232 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.util.Objects; @Entity @Cacheable(true) -@Table(name="project_type_settings") +@Table(name = "project_type_settings") public class ProjectTypeSettings extends DomainObject { - public static final int DEFAULT_NUM_DAYS_BETWEEN_REVIEWS_ON_SAME_PROJECT = 7; - public static final int DEFAULT_NUM_DAYS_TO_SUBMIT_PEER_REVIEW = 3; - public static final int DEFAULT_NUM_DAYS_BEFORE_CANCELLED_PEERS = 90; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + public static final int DEFAULT_NUM_DAYS_BETWEEN_REVIEWS_ON_SAME_PROJECT = 7; + public static final int DEFAULT_NUM_DAYS_TO_SUBMIT_PEER_REVIEW = 3; + public static final int DEFAULT_NUM_DAYS_BEFORE_CANCELLED_PEERS = 90; - @OneToOne(optional = false) - @JoinColumn(name = "project_type_id") - private ProjectType projectType; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - /* - * Defines the time span between reviews on the same project - */ - @Column(name = "num_days_between_peer_reviews_on_same_project", nullable = false) - private int numDaysBetweenPeerReviewsOnSameProject = DEFAULT_NUM_DAYS_BETWEEN_REVIEWS_ON_SAME_PROJECT; + @OneToOne(optional = false) + @JoinColumn(name = "project_type_id") + private ProjectType projectType; - /* - * Defines the number of days between accepting a review and the deadline for review submission - */ - @Column(name = "num_days_to_submit_peer_review", nullable = false) - private int numDaysToSubmitPeerReview = DEFAULT_NUM_DAYS_TO_SUBMIT_PEER_REVIEW; + /* + * Defines the time span between reviews on the same project + */ + @Column(name = "num_days_between_peer_reviews_on_same_project", nullable = false) + private int numDaysBetweenPeerReviewsOnSameProject = DEFAULT_NUM_DAYS_BETWEEN_REVIEWS_ON_SAME_PROJECT; - /* - * Defines the number of days between accepting a review and the deadline for review submission - */ - @Column(name = "num_days_before_peer_gets_cancelled", nullable = false) - private int numDaysBeforePeerGetsCancelled = DEFAULT_NUM_DAYS_BEFORE_CANCELLED_PEERS; + /* + * Defines the number of days between accepting a review and the deadline for review submission + */ + @Column(name = "num_days_to_submit_peer_review", nullable = false) + private int numDaysToSubmitPeerReview = DEFAULT_NUM_DAYS_TO_SUBMIT_PEER_REVIEW; - @Column(name = "min_authors", nullable = false) - private int minAuthors = 1; + /* + * Defines the number of days between accepting a review and the deadline for review submission + */ + @Column(name = "num_days_before_peer_gets_cancelled", nullable = false) + private int numDaysBeforePeerGetsCancelled = DEFAULT_NUM_DAYS_BEFORE_CANCELLED_PEERS; - @Column(name = "max_authors", nullable = false) - private int maxAuthors = 2; + @Column(name = "min_authors", nullable = false) + private int minAuthors = 1; - @Column(name = "max_final_seminar_active_participation", nullable = false) - private int maxFinalSeminarActiveParticipation; + @Column(name = "max_authors", nullable = false) + private int maxAuthors = 2; - @Column(name = "max_opponents_on_final_seminar", nullable = false) - private int maxOpponentsOnFinalSeminar; + @Column(name = "max_final_seminar_active_participation", nullable = false) + private int maxFinalSeminarActiveParticipation; - @Column(name = "min_final_seminar_active_participation", nullable = false) - private int minFinalSeminarActiveParticipation; + @Column(name = "max_opponents_on_final_seminar", nullable = false) + private int maxOpponentsOnFinalSeminar; - @Column(name = "min_opponents_on_final_seminar", nullable = false) - private int minOpponentsOnFinalSeminar; + @Column(name = "min_final_seminar_active_participation", nullable = false) + private int minFinalSeminarActiveParticipation; - @Column(name = "min_oppositions_to_be_graded") - private int minOppositionsToBeGraded = 0; + @Column(name = "min_opponents_on_final_seminar", nullable = false) + private int minOpponentsOnFinalSeminar; - @Column(name = "min_active_participations_to_be_graded") - private int minActiveParticipationsToBeGraded = 0; + @Column(name = "min_oppositions_to_be_graded") + private int minOppositionsToBeGraded = 0; - @Column(name = "review_process_information_url_for_supervisor") - private String reviewProcessInformationUrl; + @Column(name = "min_active_participations_to_be_graded") + private int minActiveParticipationsToBeGraded = 0; - public ProjectTypeSettings(){} + @Column(name = "review_process_information_url_for_supervisor") + private String reviewProcessInformationUrl; - public ProjectTypeSettings(ProjectType projectType){ - this.projectType = projectType; - } + public ProjectTypeSettings() {} - @Override - public Long getId() { - return this.id; - } + public ProjectTypeSettings(ProjectType projectType) { + this.projectType = projectType; + } - public ProjectType getProjectType() { - return this.projectType; - } + @Override + public Long getId() { + return this.id; + } - public int getMinAuthors() { - return this.minAuthors; - } + public ProjectType getProjectType() { + return this.projectType; + } - public int getMaxAuthors() { - return this.maxAuthors; - } + public int getMinAuthors() { + return this.minAuthors; + } - public int getMaxFinalSeminarActiveParticipation() { - return this.maxFinalSeminarActiveParticipation; - } + public int getMaxAuthors() { + return this.maxAuthors; + } - public int getMaxOpponentsOnFinalSeminar() { - return this.maxOpponentsOnFinalSeminar; - } + public int getMaxFinalSeminarActiveParticipation() { + return this.maxFinalSeminarActiveParticipation; + } - public int getMinFinalSeminarActiveParticipation() { - return this.minFinalSeminarActiveParticipation; - } + public int getMaxOpponentsOnFinalSeminar() { + return this.maxOpponentsOnFinalSeminar; + } - public int getMinOpponentsOnFinalSeminar() { - return this.minOpponentsOnFinalSeminar; - } + public int getMinFinalSeminarActiveParticipation() { + return this.minFinalSeminarActiveParticipation; + } - public int getNumDaysBetweenPeerReviewsOnSameProject() { - return this.numDaysBetweenPeerReviewsOnSameProject; - } + public int getMinOpponentsOnFinalSeminar() { + return this.minOpponentsOnFinalSeminar; + } - public int getNumDaysToSubmitPeerReview() { - return this.numDaysToSubmitPeerReview; - } + public int getNumDaysBetweenPeerReviewsOnSameProject() { + return this.numDaysBetweenPeerReviewsOnSameProject; + } - public int getNumDaysBeforePeerGetsCancelled() { - return this.numDaysBeforePeerGetsCancelled; - } + public int getNumDaysToSubmitPeerReview() { + return this.numDaysToSubmitPeerReview; + } - public void setId(Long id) { - this.id = id; - } + public int getNumDaysBeforePeerGetsCancelled() { + return this.numDaysBeforePeerGetsCancelled; + } - public void setProjectType(ProjectType projectType) { - this.projectType = projectType; - } + public void setId(Long id) { + this.id = id; + } - public void setMinAuthors(int minAuthors) { - this.minAuthors = minAuthors; - } + public void setProjectType(ProjectType projectType) { + this.projectType = projectType; + } - public void setMaxAuthors(int maxAuthors) { - this.maxAuthors = maxAuthors; - } + public void setMinAuthors(int minAuthors) { + this.minAuthors = minAuthors; + } - public void setMaxFinalSeminarActiveParticipation(int maxFinalSeminarActiveParticipation) { - this.maxFinalSeminarActiveParticipation = maxFinalSeminarActiveParticipation; - } + public void setMaxAuthors(int maxAuthors) { + this.maxAuthors = maxAuthors; + } - public void setMaxOpponentsOnFinalSeminar(int maxOpponentsOnFinalSeminar) { - this.maxOpponentsOnFinalSeminar = maxOpponentsOnFinalSeminar; - } + public void setMaxFinalSeminarActiveParticipation(int maxFinalSeminarActiveParticipation) { + this.maxFinalSeminarActiveParticipation = maxFinalSeminarActiveParticipation; + } - public void setMinFinalSeminarActiveParticipation(int minFinalSeminarActiveParticipation) { - this.minFinalSeminarActiveParticipation = minFinalSeminarActiveParticipation; - } + public void setMaxOpponentsOnFinalSeminar(int maxOpponentsOnFinalSeminar) { + this.maxOpponentsOnFinalSeminar = maxOpponentsOnFinalSeminar; + } - public void setMinOpponentsOnFinalSeminar(int minOpponentsOnFinalSeminar) { - this.minOpponentsOnFinalSeminar = minOpponentsOnFinalSeminar; - } + public void setMinFinalSeminarActiveParticipation(int minFinalSeminarActiveParticipation) { + this.minFinalSeminarActiveParticipation = minFinalSeminarActiveParticipation; + } - public void setNumDaysBetweenPeerReviewsOnSameProject(int numDaysBetweenPeerReviewsOnSameProject) { - this.numDaysBetweenPeerReviewsOnSameProject = numDaysBetweenPeerReviewsOnSameProject; - } + public void setMinOpponentsOnFinalSeminar(int minOpponentsOnFinalSeminar) { + this.minOpponentsOnFinalSeminar = minOpponentsOnFinalSeminar; + } - public void setNumDaysToSubmitPeerReview(int numDaysToSubmitPeerReview) { - this.numDaysToSubmitPeerReview = numDaysToSubmitPeerReview; - } + public void setNumDaysBetweenPeerReviewsOnSameProject(int numDaysBetweenPeerReviewsOnSameProject) { + this.numDaysBetweenPeerReviewsOnSameProject = numDaysBetweenPeerReviewsOnSameProject; + } - public void setNumDaysBeforePeerGetsCancelled(int numDaysBeforePeerGetsCancelled) { - this.numDaysBeforePeerGetsCancelled = numDaysBeforePeerGetsCancelled; - } + public void setNumDaysToSubmitPeerReview(int numDaysToSubmitPeerReview) { + this.numDaysToSubmitPeerReview = numDaysToSubmitPeerReview; + } - public int getMinOppositionsToBeGraded() { - return minOppositionsToBeGraded; - } + public void setNumDaysBeforePeerGetsCancelled(int numDaysBeforePeerGetsCancelled) { + this.numDaysBeforePeerGetsCancelled = numDaysBeforePeerGetsCancelled; + } - public void setMinOppositionsToBeGraded(int minimumOppositionsToBeGraded) { - this.minOppositionsToBeGraded = minimumOppositionsToBeGraded; - } + public int getMinOppositionsToBeGraded() { + return minOppositionsToBeGraded; + } - public int getMinActiveParticipationsToBeGraded() { - return minActiveParticipationsToBeGraded; - } + public void setMinOppositionsToBeGraded(int minimumOppositionsToBeGraded) { + this.minOppositionsToBeGraded = minimumOppositionsToBeGraded; + } - public void setMinActiveParticipationsToBeGraded(int minimumActiveParticipationsToBeGraded) { - this.minActiveParticipationsToBeGraded = minimumActiveParticipationsToBeGraded; - } + public int getMinActiveParticipationsToBeGraded() { + return minActiveParticipationsToBeGraded; + } - public String getReviewProcessInformationUrl() { - return reviewProcessInformationUrl; - } + public void setMinActiveParticipationsToBeGraded(int minimumActiveParticipationsToBeGraded) { + this.minActiveParticipationsToBeGraded = minimumActiveParticipationsToBeGraded; + } - public void setReviewProcessInformationUrl(String reviewProcessInformationUrl) { - this.reviewProcessInformationUrl = reviewProcessInformationUrl; - } + public String getReviewProcessInformationUrl() { + return reviewProcessInformationUrl; + } - @Override - public String toString() { - return "ProjectTypeSettings(id=" + this.getId() + ", projectType=" + this.getProjectType() + ", minAuthors=" + this.getMinAuthors() + ", maxAuthors=" + this.getMaxAuthors() + ", maxFinalSeminarActiveParticipation=" + this.getMaxFinalSeminarActiveParticipation() + ", maxOpponentsOnFinalSeminar=" + this.getMaxOpponentsOnFinalSeminar() + ", minFinalSeminarActiveParticipation=" + this.getMinFinalSeminarActiveParticipation() + ", minOpponentsOnFinalSeminar=" + this.getMinOpponentsOnFinalSeminar() + ", numDaysBetweenPeerReviewsOnSameProject=" + this.getNumDaysBetweenPeerReviewsOnSameProject() + ", numDaysToSubmitPeerReview=" + this.getNumDaysToSubmitPeerReview() + ", numDaysBeforePeerGetsCancelled=" + this.getNumDaysBeforePeerGetsCancelled() + ")"; - } + public void setReviewProcessInformationUrl(String reviewProcessInformationUrl) { + this.reviewProcessInformationUrl = reviewProcessInformationUrl; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof ProjectTypeSettings)) return false; - final ProjectTypeSettings other = (ProjectTypeSettings) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); - } + @Override + public String toString() { + return ( + "ProjectTypeSettings(id=" + + this.getId() + + ", projectType=" + + this.getProjectType() + + ", minAuthors=" + + this.getMinAuthors() + + ", maxAuthors=" + + this.getMaxAuthors() + + ", maxFinalSeminarActiveParticipation=" + + this.getMaxFinalSeminarActiveParticipation() + + ", maxOpponentsOnFinalSeminar=" + + this.getMaxOpponentsOnFinalSeminar() + + ", minFinalSeminarActiveParticipation=" + + this.getMinFinalSeminarActiveParticipation() + + ", minOpponentsOnFinalSeminar=" + + this.getMinOpponentsOnFinalSeminar() + + ", numDaysBetweenPeerReviewsOnSameProject=" + + this.getNumDaysBetweenPeerReviewsOnSameProject() + + ", numDaysToSubmitPeerReview=" + + this.getNumDaysToSubmitPeerReview() + + ", numDaysBeforePeerGetsCancelled=" + + this.getNumDaysBeforePeerGetsCancelled() + + ")" + ); + } - protected boolean canEqual(final Object other) { - return other instanceof ProjectTypeSettings; - } + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof ProjectTypeSettings)) return false; + final ProjectTypeSettings other = (ProjectTypeSettings) o; + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); + } - @Override - public int hashCode() { - return Objects.hashCode(this.getId()); - } + protected boolean canEqual(final Object other) { + return other instanceof ProjectTypeSettings; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.getId()); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/QueryDslPredicateExecutor.java b/core/src/main/java/se/su/dsv/scipro/system/QueryDslPredicateExecutor.java index b85aef63c1..495d93896c 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/QueryDslPredicateExecutor.java +++ b/core/src/main/java/se/su/dsv/scipro/system/QueryDslPredicateExecutor.java @@ -1,7 +1,6 @@ package se.su.dsv.scipro.system; import com.querydsl.core.types.Predicate; - import java.util.List; public interface QueryDslPredicateExecutor { diff --git a/core/src/main/java/se/su/dsv/scipro/system/ResearchArea.java b/core/src/main/java/se/su/dsv/scipro/system/ResearchArea.java index 01e994645b..2376a281d2 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/ResearchArea.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ResearchArea.java @@ -8,13 +8,13 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; - import java.util.Objects; @Entity @Table(name = "research_area") @Cacheable(true) public class ResearchArea extends LazyDeletableDomainObject { + public static final int STRING_MAX_LENGTH = 255; @Id @@ -55,7 +55,15 @@ public class ResearchArea extends LazyDeletableDomainObject { @Override public String toString() { - return "ResearchArea(id=" + this.getId() + ", identifier=" + this.getIdentifier() + ", title=" + this.getTitle() + ")"; + return ( + "ResearchArea(id=" + + this.getId() + + ", identifier=" + + this.getIdentifier() + + ", title=" + + this.getTitle() + + ")" + ); } @Override @@ -63,8 +71,7 @@ public class ResearchArea extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof ResearchArea)) return false; final ResearchArea other = (ResearchArea) o; - return other.canEqual(this) - && Objects.equals(this.getIdentifier(), other.getIdentifier()); + return (other.canEqual(this) && Objects.equals(this.getIdentifier(), other.getIdentifier())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/system/ResearchAreaServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/ResearchAreaServiceImpl.java index 3c75c66915..76bc207cdd 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/ResearchAreaServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/ResearchAreaServiceImpl.java @@ -4,11 +4,11 @@ import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; - import java.util.Comparator; import java.util.List; -public class ResearchAreaServiceImpl extends AbstractServiceImpl implements ResearchAreaService { +public class ResearchAreaServiceImpl extends AbstractServiceImpl implements ResearchAreaService { + @Inject public ResearchAreaServiceImpl(Provider em) { super(em, ResearchArea.class, QResearchArea.researchArea); @@ -34,8 +34,8 @@ public class ResearchAreaServiceImpl extends AbstractServiceImpl findNotDeleted() { return findAll(QResearchArea.researchArea.deleted.isFalse()) - .stream() - .sorted(Comparator.comparing(ResearchArea::getTitle)) - .toList(); + .stream() + .sorted(Comparator.comparing(ResearchArea::getTitle)) + .toList(); } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/Sort.java b/core/src/main/java/se/su/dsv/scipro/system/Sort.java index 8ed0486e92..bfb3e5c364 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/Sort.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Sort.java @@ -3,11 +3,11 @@ package se.su.dsv.scipro.system; import java.util.Objects; public class Sort { + private final Direction desc; private final String property; public Sort(Direction desc, String property) { - this.desc = desc; this.property = property; } @@ -25,9 +25,11 @@ public class Sort { if (o == this) return true; if (!(o instanceof Sort)) return false; final Sort other = (Sort) o; - return other.canEqual(this) - && Objects.equals(this.desc, other.desc) - && Objects.equals(this.getProperty(), other.getProperty()); + return ( + other.canEqual(this) && + Objects.equals(this.desc, other.desc) && + Objects.equals(this.getProperty(), other.getProperty()) + ); } protected boolean canEqual(final Object other) { @@ -39,5 +41,8 @@ public class Sort { return Objects.hash(this.desc, this.getProperty()); } - public enum Direction { ASC, DESC } + public enum Direction { + ASC, + DESC, + } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/SystemModule.java b/core/src/main/java/se/su/dsv/scipro/system/SystemModule.java index 34ae7b80de..297dbb5251 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/SystemModule.java +++ b/core/src/main/java/se/su/dsv/scipro/system/SystemModule.java @@ -1,5 +1,5 @@ package se.su.dsv.scipro.system; public enum SystemModule { - GROUP + GROUP, } diff --git a/core/src/main/java/se/su/dsv/scipro/system/Unit.java b/core/src/main/java/se/su/dsv/scipro/system/Unit.java index 404baee063..d0022fc4a5 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/Unit.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Unit.java @@ -7,7 +7,6 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; - import java.util.Objects; @Entity @@ -34,7 +33,7 @@ public class Unit extends DomainObject { return matchResponsible; } - public void setMatchResponsible(String matchResponsible){ + public void setMatchResponsible(String matchResponsible) { this.matchResponsible = matchResponsible; } @@ -65,7 +64,17 @@ public class Unit extends DomainObject { @Override public String toString() { - return "Unit(id=" + this.getId() + ", identifier=" + this.getIdentifier() + ", title=" + this.getTitle() + ", matchResponsible=" + this.getMatchResponsible() + ")"; + return ( + "Unit(id=" + + this.getId() + + ", identifier=" + + this.getIdentifier() + + ", title=" + + this.getTitle() + + ", matchResponsible=" + + this.getMatchResponsible() + + ")" + ); } @Override @@ -73,8 +82,7 @@ public class Unit extends DomainObject { if (o == this) return true; if (!(o instanceof Unit)) return false; final Unit other = (Unit) o; - return other.canEqual(this) - && Objects.equals(this.getIdentifier(), other.getIdentifier()); + return (other.canEqual(this) && Objects.equals(this.getIdentifier(), other.getIdentifier())); } protected boolean canEqual(final Object other) { diff --git a/core/src/main/java/se/su/dsv/scipro/system/User.java b/core/src/main/java/se/su/dsv/scipro/system/User.java index 9addbde052..7c8b374ed8 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/User.java +++ b/core/src/main/java/se/su/dsv/scipro/system/User.java @@ -18,14 +18,12 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; - import java.io.Serializable; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Objects; import java.util.Set; - import se.su.dsv.scipro.security.auth.roles.Roles; @Entity @@ -94,9 +92,11 @@ public class User extends LazyDeletableDomainObject { private Set languages = EnumSet.noneOf(Language.class); @ManyToMany - @JoinTable(name = "user_research_area", - joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), - inverseJoinColumns = @JoinColumn(name = "research_area_id", referencedColumnName = "id")) + @JoinTable( + name = "user_research_area", + joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "research_area_id", referencedColumnName = "id") + ) private Set researchAreas = new HashSet<>(); @OneToOne(optional = true) @@ -274,8 +274,7 @@ public class User extends LazyDeletableDomainObject { if (o == this) return true; if (!(o instanceof User)) return false; final User other = (User) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()); + return (other.canEqual(this) && Objects.equals(this.getId(), other.getId())); } protected boolean canEqual(final Object other) { @@ -289,7 +288,23 @@ public class User extends LazyDeletableDomainObject { @Override public String toString() { - return "User(id=" + this.getId() + ", identifier=" + this.getIdentifier() + ", firstName=" + this.getFirstName() + ", lastName=" + this.getLastName() + ", emailAddress=" + this.getEmailAddress() + ", deceased=" + this.isDeceased() + ", degreeType=" + this.getDegreeType() + ")"; + return ( + "User(id=" + + this.getId() + + ", identifier=" + + this.getIdentifier() + + ", firstName=" + + this.getFirstName() + + ", lastName=" + + this.getLastName() + + ", emailAddress=" + + this.getEmailAddress() + + ", deceased=" + + this.isDeceased() + + ", degreeType=" + + this.getDegreeType() + + ")" + ); } public interface IFirstName { @@ -308,7 +323,6 @@ public class User extends LazyDeletableDomainObject { * These are the rest. */ public interface IBuild { - IBuild identifier(Integer identifier); IBuild roles(Set roles); @@ -317,6 +331,7 @@ public class User extends LazyDeletableDomainObject { } private static class Builder implements IFirstName, ILastName, IEmailAddress, IBuild { + private final User instance = new User(); @Override @@ -360,11 +375,9 @@ public class User extends LazyDeletableDomainObject { @Override public int compare(User o1, User o2) { int i = o1.getLastName().compareTo(o2.getLastName()); - if (i == 0) - i = o1.getFirstName().compareTo(o2.getFirstName()); - if (i == 0) - i = o1.getId().compareTo(o2.getId()); + if (i == 0) i = o1.getFirstName().compareTo(o2.getFirstName()); + if (i == 0) i = o1.getId().compareTo(o2.getId()); return i; } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserImportService.java b/core/src/main/java/se/su/dsv/scipro/system/UserImportService.java index 8b24d4b6c5..20aedef539 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/UserImportService.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserImportService.java @@ -15,6 +15,7 @@ public interface UserImportService { Set importResearchAreasForSupervisor(User supervisor); class ImportableUser implements Serializable { + private final String firstName; private final String lastName; private final String email; diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserNameService.java b/core/src/main/java/se/su/dsv/scipro/system/UserNameService.java index a7a829022e..607c5041e8 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/UserNameService.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserNameService.java @@ -2,4 +2,4 @@ package se.su.dsv.scipro.system; public interface UserNameService extends GenericService { Username findByUsername(String username); -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserNameServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/UserNameServiceImpl.java index 537dbfce81..33314571b1 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/UserNameServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserNameServiceImpl.java @@ -5,6 +5,7 @@ import jakarta.inject.Provider; import jakarta.persistence.EntityManager; public class UserNameServiceImpl extends AbstractServiceImpl implements UserNameService { + @Inject public UserNameServiceImpl(Provider em) { super(em, Username.class, QUsername.username1); @@ -14,4 +15,4 @@ public class UserNameServiceImpl extends AbstractServiceImpl imp public Username findByUsername(String username) { return findOne(QUsername.username1.username.eq(username)); } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserRepo.java b/core/src/main/java/se/su/dsv/scipro/system/UserRepo.java index 9831c44da1..f49e504010 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/UserRepo.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserRepo.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.system; import jakarta.transaction.Transactional; -import se.su.dsv.scipro.security.auth.roles.Roles; - import java.util.Collection; import java.util.Set; +import se.su.dsv.scipro.security.auth.roles.Roles; @Transactional public interface UserRepo extends JpaRepository, QueryDslPredicateExecutor { diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserRepoImpl.java b/core/src/main/java/se/su/dsv/scipro/system/UserRepoImpl.java index 35c53085f8..86edca5d9e 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/UserRepoImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserRepoImpl.java @@ -1,18 +1,18 @@ package se.su.dsv.scipro.system; -import com.querydsl.jpa.JPAExpressions; -import se.su.dsv.scipro.security.auth.roles.Roles; +import static com.querydsl.core.types.dsl.Expressions.allOf; +import static com.querydsl.core.types.dsl.Expressions.anyOf; +import com.querydsl.jpa.JPAExpressions; import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.Collection; import java.util.Set; - -import static com.querydsl.core.types.dsl.Expressions.allOf; -import static com.querydsl.core.types.dsl.Expressions.anyOf; +import se.su.dsv.scipro.security.auth.roles.Roles; public class UserRepoImpl extends GenericRepo implements UserRepo { + @Inject public UserRepoImpl(Provider em) { super(em, User.class, QUser.user); @@ -21,18 +21,21 @@ public class UserRepoImpl extends GenericRepo implements UserRepo { @Override public Collection findByNameIncludes(String term, Set roles, Pageable pageable) { QUser user = QUser.user; - return findAll(allOf( + return findAll( + allOf( user.deleted.isFalse(), user.roles.any().in(roles), anyOf( - user.firstName.concat(" ").concat(user.lastName).contains(term), - user.emailAddress.contains(term), - user.in(JPAExpressions - .select(QUsername.username1.user) - .from(QUsername.username1) - .where(QUsername.username1.username.contains(term))) + user.firstName.concat(" ").concat(user.lastName).contains(term), + user.emailAddress.contains(term), + user.in( + JPAExpressions.select(QUsername.username1.user) + .from(QUsername.username1) + .where(QUsername.username1.username.contains(term)) + ) ) - ), pageable); + ), + pageable + ); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserSearchProvider.java b/core/src/main/java/se/su/dsv/scipro/system/UserSearchProvider.java index 2be043160a..3047bce6d5 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/UserSearchProvider.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserSearchProvider.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.system; -import se.su.dsv.scipro.security.auth.roles.Roles; - import java.util.Collection; import java.util.Set; +import se.su.dsv.scipro.security.auth.roles.Roles; public interface UserSearchProvider { /** diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserSearchService.java b/core/src/main/java/se/su/dsv/scipro/system/UserSearchService.java index fcb9230ba9..7b0ffe942a 100644 --- a/core/src/main/java/se/su/dsv/scipro/system/UserSearchService.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserSearchService.java @@ -1,9 +1,8 @@ package se.su.dsv.scipro.system; -import se.su.dsv.scipro.security.auth.roles.Roles; - import java.util.Collection; import java.util.Set; +import se.su.dsv.scipro.security.auth.roles.Roles; public interface UserSearchService { Collection search(String term, Set role, long maxResults); diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserService.java b/core/src/main/java/se/su/dsv/scipro/system/UserService.java index 0969165adf..f2a2d9ee8c 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/UserService.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserService.java @@ -1,21 +1,21 @@ package se.su.dsv.scipro.system; -import se.su.dsv.scipro.security.auth.roles.Roles; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.security.auth.roles.Roles; -public interface UserService extends GenericService ,FilteredService { +public interface UserService extends GenericService, FilteredService { User findByUsername(String username); User findByExternalIdentifier(Integer externalIdentifier); List findActiveReviewers(); class Filter implements Serializable { + private Collection roles = EnumSet.allOf(Roles.class); private String name; @@ -45,9 +45,11 @@ public interface UserService extends GenericService ,FilteredService if (o == this) return true; if (!(o instanceof Filter)) return false; final Filter other = (Filter) o; - return other.canEqual(this) - && Objects.equals(this.getRoles(), other.getRoles()) - && Objects.equals(this.getName(), other.getName()); + return ( + other.canEqual(this) && + Objects.equals(this.getRoles(), other.getRoles()) && + Objects.equals(this.getName(), other.getName()) + ); } protected boolean canEqual(final Object other) { @@ -61,7 +63,7 @@ public interface UserService extends GenericService ,FilteredService @Override public String toString() { - return "UserService.Filter(roles=" + this.getRoles() + ", name=" + this.getName() + ")"; + return ("UserService.Filter(roles=" + this.getRoles() + ", name=" + this.getName() + ")"); } } } diff --git a/core/src/main/java/se/su/dsv/scipro/system/UserServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/system/UserServiceImpl.java index ee1392b194..46d6783e33 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/UserServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/system/UserServiceImpl.java @@ -1,18 +1,16 @@ package se.su.dsv.scipro.system; -import com.querydsl.core.BooleanBuilder; -import com.querydsl.core.types.Predicate; - -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import se.su.dsv.scipro.security.auth.roles.Roles; - -import java.util.List; - import static com.querydsl.core.types.dsl.Expressions.anyOf; -public class UserServiceImpl extends AbstractServiceImpl implements UserService { +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.util.List; +import se.su.dsv.scipro.security.auth.roles.Roles; + +public class UserServiceImpl extends AbstractServiceImpl implements UserService { @Inject public UserServiceImpl(Provider em) { @@ -48,15 +46,16 @@ public class UserServiceImpl extends AbstractServiceImpl implements U BooleanBuilder booleanBuilder = new BooleanBuilder(); if (!filter.getRoles().isEmpty()) { booleanBuilder.and(QUser.user.roles.any().in(filter.getRoles())); - } - else { + } else { booleanBuilder.and(QUser.user.roles.size().eq(0)); } if (filter.getName() != null && !filter.getName().isEmpty()) { - booleanBuilder.and(anyOf( + booleanBuilder.and( + anyOf( QUser.user.firstName.concat(" ").concat(QUser.user.lastName).containsIgnoreCase(filter.getName()), QUser.user.emailAddress.containsIgnoreCase(filter.getName()) - )); + ) + ); } return booleanBuilder; } diff --git a/core/src/main/java/se/su/dsv/scipro/system/Username.java b/core/src/main/java/se/su/dsv/scipro/system/Username.java index 5da461d2b6..700f91e543 100755 --- a/core/src/main/java/se/su/dsv/scipro/system/Username.java +++ b/core/src/main/java/se/su/dsv/scipro/system/Username.java @@ -9,68 +9,67 @@ import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; - import java.util.Objects; @Entity -@Table(name="username", uniqueConstraints={@UniqueConstraint(name = "uk_username", columnNames={"username"})}) +@Table(name = "username", uniqueConstraints = { @UniqueConstraint(name = "uk_username", columnNames = { "username" }) }) @Cacheable(true) public class Username extends DomainObject { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(name = "username", nullable = false) - private String username; - - @ManyToOne(optional=false) - private User user; - @Override - public Long getId() { - return this.id; - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - public String getUsername() { - return this.username; - } + @Column(name = "username", nullable = false) + private String username; - public User getUser() { - return this.user; - } + @ManyToOne(optional = false) + private User user; - public void setId(Long id) { - this.id = id; - } + @Override + public Long getId() { + return this.id; + } - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return this.username; + } - public void setUser(User user) { - this.user = user; - } + public User getUser() { + return this.user; + } - @Override - public String toString() { - return "Username(id=" + this.getId() + ", username=" + this.getUsername() + ", user=" + this.getUser() + ")"; - } + public void setId(Long id) { + this.id = id; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof Username)) return false; - final Username other = (Username) o; - return other.canEqual(this) - && Objects.equals(this.getUsername(), other.getUsername()); - } + public void setUsername(String username) { + this.username = username; + } - protected boolean canEqual(final Object other) { - return other instanceof Username; - } + public void setUser(User user) { + this.user = user; + } - @Override - public int hashCode() { - return Objects.hashCode(this.getUsername()); - } + @Override + public String toString() { + return ("Username(id=" + this.getId() + ", username=" + this.getUsername() + ", user=" + this.getUser() + ")"); + } + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof Username)) return false; + final Username other = (Username) o; + return (other.canEqual(this) && Objects.equals(this.getUsername(), other.getUsername())); + } + + protected boolean canEqual(final Object other) { + return other instanceof Username; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.getUsername()); + } } diff --git a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLink.java b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLink.java index ee96eb8884..d560854009 100644 --- a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLink.java +++ b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLink.java @@ -9,12 +9,11 @@ import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; +import java.util.Objects; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.User; -import java.util.Objects; - @Entity @Table(name = "external_link") public class ExternalLink extends DomainObject { @@ -103,12 +102,14 @@ public class ExternalLink extends DomainObject { if (o == this) return true; if (!(o instanceof ExternalLink)) return false; final ExternalLink other = (ExternalLink) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getProject(), other.getProject()) - && Objects.equals(this.getUrl(), other.getUrl()) - && Objects.equals(this.getUser(), other.getUser()) - && Objects.equals(this.getDescription(), other.getDescription()); + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getProject(), other.getProject()) && + Objects.equals(this.getUrl(), other.getUrl()) && + Objects.equals(this.getUser(), other.getUser()) && + Objects.equals(this.getDescription(), other.getDescription()) + ); } @Override @@ -118,9 +119,19 @@ public class ExternalLink extends DomainObject { @Override public String toString() { - return "ExternalLink(id=" + this.getId() + ", project=" + this.getProject() + - ", url=" + this.getUrl() + ", user=" + this.getUser() + ", description=" + - this.getDescription() + ")"; + return ( + "ExternalLink(id=" + + this.getId() + + ", project=" + + this.getProject() + + ", url=" + + this.getUrl() + + ", user=" + + this.getUser() + + ", description=" + + this.getDescription() + + ")" + ); } // ---------------------------------------------------------------------------------- @@ -134,6 +145,7 @@ public class ExternalLink extends DomainObject { // Nested types // ---------------------------------------------------------------------------------- private static class Builder implements IProject, IURL, IUser, IBuild { + private ExternalLink instance = new ExternalLink(); @Override diff --git a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkService.java b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkService.java index ece56a3a6d..0fdf6a81d4 100755 --- a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkService.java +++ b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkService.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.thesislink; +import java.util.List; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.GenericService; -import java.util.List; - public interface ExternalLinkService extends GenericService { List findByProject(final Project project); } diff --git a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkServiceImpl.java index 7c43a97286..86006bcdb1 100755 --- a/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkServiceImpl.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.thesislink; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import java.util.List; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.AbstractServiceImpl; -public class ExternalLinkServiceImpl extends AbstractServiceImpl implements ExternalLinkService { +public class ExternalLinkServiceImpl extends AbstractServiceImpl implements ExternalLinkService { @Inject public ExternalLinkServiceImpl(Provider em) { diff --git a/core/src/main/java/se/su/dsv/scipro/util/Either.java b/core/src/main/java/se/su/dsv/scipro/util/Either.java index c46dfd8226..fa5ec7909d 100644 --- a/core/src/main/java/se/su/dsv/scipro/util/Either.java +++ b/core/src/main/java/se/su/dsv/scipro/util/Either.java @@ -19,6 +19,7 @@ import java.util.function.Function; * has no need to actually extend {@code Exception}. */ public abstract class Either { + /** * Construct an {@code Either} by putting an {@code E} on the left. */ @@ -68,9 +69,12 @@ public abstract class Either { * @return the value on the right side if this is a {@code Right}, otherwise throws {@code UnsupportedOperationException} */ public A right() { - return fold(error -> { - throw new UnsupportedOperationException("Can not call right() on a Left"); - }, Function.identity()); + return fold( + error -> { + throw new UnsupportedOperationException("Can not call right() on a Left"); + }, + Function.identity() + ); } /** @@ -88,15 +92,18 @@ public abstract class Either { * Prefer using other methods if at all possible. */ public void foreach(Consumer sideEffect) { - fold(e -> null, a -> { sideEffect.accept(a); return null; }); + fold( + e -> null, + a -> { + sideEffect.accept(a); + return null; + } + ); } @Override public String toString() { - return fold( - error -> "Left(" + error.toString() + ")", - a -> "Right(" + a.toString() + ")" - ); + return fold(error -> "Left(" + error.toString() + ")", a -> "Right(" + a.toString() + ")"); } @Override @@ -108,6 +115,7 @@ public abstract class Either { } private static final class Right extends Either { + private final A a; Right(final A a) { @@ -130,6 +138,7 @@ public abstract class Either { } private static final class Left extends Either { + private final E error; public Left(final E error) { diff --git a/core/src/main/java/se/su/dsv/scipro/util/Pair.java b/core/src/main/java/se/su/dsv/scipro/util/Pair.java index 74d457f079..860194e994 100755 --- a/core/src/main/java/se/su/dsv/scipro/util/Pair.java +++ b/core/src/main/java/se/su/dsv/scipro/util/Pair.java @@ -28,8 +28,7 @@ public class Pair { Pair pair = (Pair) o; - return Objects.equals(head, pair.head) && Objects.equals(tail, pair.tail); - + return (Objects.equals(head, pair.head) && Objects.equals(tail, pair.tail)); } @Override diff --git a/core/src/main/java/se/su/dsv/scipro/util/PropsUtils.java b/core/src/main/java/se/su/dsv/scipro/util/PropsUtils.java index 4233bff81d..f17499bf2b 100755 --- a/core/src/main/java/se/su/dsv/scipro/util/PropsUtils.java +++ b/core/src/main/java/se/su/dsv/scipro/util/PropsUtils.java @@ -5,8 +5,8 @@ import java.io.InputStream; import java.util.Properties; public final class PropsUtils { - private PropsUtils() { - } + + private PropsUtils() {} /** * Load a properties file from the classpath @@ -23,4 +23,4 @@ public final class PropsUtils { properties.load(in); return properties; } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/war/PluginConfiguration.java b/core/src/main/java/se/su/dsv/scipro/war/PluginConfiguration.java index a111714130..a5559260c4 100644 --- a/core/src/main/java/se/su/dsv/scipro/war/PluginConfiguration.java +++ b/core/src/main/java/se/su/dsv/scipro/war/PluginConfiguration.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.war; -public interface PluginConfiguration { -} +public interface PluginConfiguration {} diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/AbstractWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/AbstractWorker.java index 5c721b2ffe..9c97efdb03 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/AbstractWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/AbstractWorker.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.workerthreads; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityTransaction; import java.util.Date; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Subclasses must be annotated with @Component or similar annotation in order for autowiring of dependencies to work @@ -27,8 +26,7 @@ public abstract class AbstractWorker implements Worker { /** * Subclasses must be annotated with @Component or similar annotation in order for autowiring of dependencies to work */ - public AbstractWorker() { - } + public AbstractWorker() {} @Inject public void setWorkerDataService(WorkerDataService workerDataService) { @@ -56,18 +54,16 @@ public abstract class AbstractWorker implements Worker { wd.setLastRun(startedWorkingDate); saveWorkerData(); - /* + /* * Do manually transaction-handled work - */ + */ try { doWork(); - } - catch (RuntimeException ex) { + } catch (RuntimeException ex) { LOGGER.info("Worker {} threw an exception", getClass().getSimpleName()); LOGGER.error("Worker failed", ex); setSuccessfulWorker(false); - } - finally { + } finally { txManager.rollbackIfActive(); } @@ -79,7 +75,6 @@ public abstract class AbstractWorker implements Worker { wd.setLastSuccessfulRun(startedWorkingDate); } saveWorkerData(); - } finally { txManager.rollbackIfActive(); } @@ -141,5 +136,4 @@ public abstract class AbstractWorker implements Worker { protected void rollbackTransaction() { txManager.rollback(); } - } diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/DailySchedule.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/DailySchedule.java index 346669ba77..9fc15cc1c4 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/DailySchedule.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/DailySchedule.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.workerthreads; import com.google.common.annotations.VisibleForTesting; - import java.util.Calendar; import java.util.concurrent.TimeUnit; class DailySchedule extends Schedule { + private static final long MINUTES_PER_HOUR = TimeUnit.HOURS.toMinutes(1); private static final long MINUTES_PER_DAY = TimeUnit.DAYS.toMinutes(1); @@ -43,7 +43,7 @@ class DailySchedule extends Schedule { @VisibleForTesting static long minutesUntil(int targetHour, int targetMinute, int currentHour, int currentMinute) { if (currentHour > targetHour || (currentHour == targetHour && currentMinute > targetMinute)) { - return MINUTES_PER_DAY - minutesUntil(currentHour, currentMinute, targetHour, targetMinute); + return (MINUTES_PER_DAY - minutesUntil(currentHour, currentMinute, targetHour, targetMinute)); } int hx = targetHour - currentHour; diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/GradeFinalSeminarParticipantReminderWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/GradeFinalSeminarParticipantReminderWorker.java index b5603d84f0..69c1975a93 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/GradeFinalSeminarParticipantReminderWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/GradeFinalSeminarParticipantReminderWorker.java @@ -1,13 +1,5 @@ package se.su.dsv.scipro.workerthreads; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.finalseminar.FinalSeminar; -import se.su.dsv.scipro.finalseminar.FinalSeminarService; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; -import se.su.dsv.scipro.mail.MailEvent; -import se.su.dsv.scipro.mail.MailEventService; - import jakarta.inject.Inject; import java.time.LocalDate; import java.time.ZoneId; @@ -15,6 +7,13 @@ import java.time.ZonedDateTime; import java.util.Collections; import java.util.Date; import java.util.List; +import se.su.dsv.scipro.finalseminar.FinalSeminar; +import se.su.dsv.scipro.finalseminar.FinalSeminarService; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; +import se.su.dsv.scipro.mail.MailEvent; +import se.su.dsv.scipro.mail.MailEventService; +import se.su.dsv.scipro.system.PageRequest; public class GradeFinalSeminarParticipantReminderWorker extends AbstractWorker { @@ -26,10 +25,10 @@ public class GradeFinalSeminarParticipantReminderWorker extends AbstractWorker { @Inject public GradeFinalSeminarParticipantReminderWorker( - final FinalSeminarService finalSeminarService, - final MailEventService mailEventService, - final GeneralSystemSettingsService generalSystemSettingsService) - { + final FinalSeminarService finalSeminarService, + final MailEventService mailEventService, + final GeneralSystemSettingsService generalSystemSettingsService + ) { this.finalSeminarService = finalSeminarService; this.mailEventService = mailEventService; this.generalSystemSettingsService = generalSystemSettingsService; @@ -41,9 +40,10 @@ public class GradeFinalSeminarParticipantReminderWorker extends AbstractWorker { final ZoneId zone = ZoneId.systemDefault(); final List finalSeminars = finalSeminarService.findUnfinishedSeminars( - toDate(seminarDate.atStartOfDay(zone)), - toDate(seminarDate.atTime(23, 59).atZone(zone)), - new PageRequest(0, 100)); + toDate(seminarDate.atStartOfDay(zone)), + toDate(seminarDate.atTime(23, 59).atZone(zone)), + new PageRequest(0, 100) + ); for (FinalSeminar finalSeminar : finalSeminars) { if (!finalSeminar.isCancelled() && !finalSeminar.isDeleted()) { @@ -62,19 +62,28 @@ public class GradeFinalSeminarParticipantReminderWorker extends AbstractWorker { mailEvent.setSubject("Final seminar participants needs to be graded"); final GeneralSystemSettings settings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); - final String body = "The project " + - '\'' + finalSeminar.getProjectTitle() + '\'' + - " recently had a final seminar but it seems you may" + - " have forgotten to grade some of the participants." + - '\n' + - '\n' + - "Please log in to SciPro at " + - settings.getSciproURL() + - '/' + "supervisor" + - '/' + "project" + - '/' + "finalseminar" + - '?' + "pid" + '=' + finalSeminar.getProject().getId() + - " to grade them."; + final String body = + "The project " + + '\'' + + finalSeminar.getProjectTitle() + + '\'' + + " recently had a final seminar but it seems you may" + + " have forgotten to grade some of the participants." + + '\n' + + '\n' + + "Please log in to SciPro at " + + settings.getSciproURL() + + '/' + + "supervisor" + + '/' + + "project" + + '/' + + "finalseminar" + + '?' + + "pid" + + '=' + + finalSeminar.getProject().getId() + + " to grade them."; mailEvent.setMessageBody(body); diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/IdeaExportWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/IdeaExportWorker.java index b804974c12..0eba229f57 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/IdeaExportWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/IdeaExportWorker.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.workerthreads; +import static se.su.dsv.scipro.match.IdeaExport.Result.FAIL; +import static se.su.dsv.scipro.match.IdeaExport.Result.SUCCESS; + import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.text.MessageFormat; +import java.time.*; +import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.firstmeeting.FirstMeetingService; @@ -12,14 +19,6 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.text.MessageFormat; -import java.time.*; -import java.util.*; - -import static se.su.dsv.scipro.match.IdeaExport.Result.FAIL; -import static se.su.dsv.scipro.match.IdeaExport.Result.SUCCESS; - public class IdeaExportWorker extends AbstractWorker { private static final Logger LOGGER = LoggerFactory.getLogger(IdeaExportWorker.class); @@ -32,13 +31,14 @@ public class IdeaExportWorker extends AbstractWorker { private final FirstMeetingService firstMeetingService; @Inject - public IdeaExportWorker(final IdeaService ideaService, - final MailEventService mailService, - final ProjectService projectService, - final IdeaCreationJudge ideaCreationJudge, - final EventBus eventBus, - final FirstMeetingService firstMeetingService) - { + public IdeaExportWorker( + final IdeaService ideaService, + final MailEventService mailService, + final ProjectService projectService, + final IdeaCreationJudge ideaCreationJudge, + final EventBus eventBus, + final FirstMeetingService firstMeetingService + ) { this.ideaService = ideaService; this.mailService = mailService; this.projectService = projectService; @@ -77,7 +77,6 @@ public class IdeaExportWorker extends AbstractWorker { return ideaCreationJudge.ruling(idea); } - private void allow(final Idea idea) { store(idea, "", SUCCESS); } @@ -99,13 +98,13 @@ public class IdeaExportWorker extends AbstractWorker { beginTransaction(); LOGGER.info("Exporting idea: {}", idea); Project project = Project.builder() - .title(idea.getTitle()) - .projectType(idea.getProjectType()) - .startDate(getCourseStartDate(idea)) - .headSupervisor(idea.getMatch().getSupervisor()) - .projectParticipants(getAuthors(idea)) - .identifier(identifier) - .build(); + .title(idea.getTitle()) + .projectType(idea.getProjectType()) + .startDate(getCourseStartDate(idea)) + .headSupervisor(idea.getMatch().getSupervisor()) + .projectParticipants(getAuthors(idea)) + .identifier(identifier) + .build(); project.setExpectedEndDate(idea.getApplicationPeriod().getCourseEndDate()); project.setResearchArea(idea.getResearchArea()); @@ -118,9 +117,7 @@ public class IdeaExportWorker extends AbstractWorker { } private LocalDate getCourseStartDate(final Idea idea) { - return idea.getApplicationPeriod() - .getCourseStartDateTime() - .toLocalDate(); + return idea.getApplicationPeriod().getCourseStartDateTime().toLocalDate(); } private void createFirstMeetingEvent(Idea idea, Project project) { @@ -128,10 +125,12 @@ public class IdeaExportWorker extends AbstractWorker { return; } final FirstMeeting firstMeeting = idea.getFirstMeeting(); - firstMeetingService.schedule(project, - firstMeeting.getFirstMeetingDate(), - firstMeeting.getRoom(), - firstMeeting.getDescription()); + firstMeetingService.schedule( + project, + firstMeeting.getFirstMeetingDate(), + firstMeeting.getRoom(), + firstMeeting.getDescription() + ); } private void addCompletedMatch(final Idea idea) { @@ -156,12 +155,7 @@ public class IdeaExportWorker extends AbstractWorker { String subjectFormat = "[SciPro] Automatic idea exporting {0, date}"; String prefix = "The following {0, choice, 1#idea|1<{0, number} ideas} failed to export into Daisy.\n\n"; String suffix = "***DO NOT REPLY TO THIS MESSAGE!*** This is an automated message from SciPro."; - String ideaFormat = - "{0}\n" + - "Error: {1}\n" + - " - Supervisor: {2}\n" + - " - Authors: {3}\n\n"; - + String ideaFormat = "{0}\n" + "Error: {1}\n" + " - Supervisor: {2}\n" + " - Authors: {3}\n\n"; Collection failedIdeas; String subject; @@ -215,7 +209,7 @@ public class IdeaExportWorker extends AbstractWorker { private String getAuthors(Idea idea) { StringBuilder authors = new StringBuilder(); - for (Iterator iterator = idea.getIdeaParticipations().iterator(); iterator.hasNext(); ) { + for (Iterator iterator = idea.getIdeaParticipations().iterator(); iterator.hasNext();) { authors.append(iterator.next().getUser().getFullName()); if (iterator.hasNext()) { authors.append(", "); diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/ManualMatchRemindWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/ManualMatchRemindWorker.java index 87d4ebe639..78cdf622c6 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/ManualMatchRemindWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/ManualMatchRemindWorker.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.workerthreads; +import jakarta.inject.Inject; +import java.time.Clock; +import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.mail.MailEvent; import se.su.dsv.scipro.mail.MailEventService; @@ -9,12 +14,6 @@ import se.su.dsv.scipro.match.Idea; import se.su.dsv.scipro.match.IdeaService; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.LocalDate; -import java.util.Collections; -import java.util.HashSet; - public class ManualMatchRemindWorker extends AbstractWorker { private final ApplicationPeriodService applicationPeriodService; @@ -24,11 +23,13 @@ public class ManualMatchRemindWorker extends AbstractWorker { private final Clock clock; @Inject - public ManualMatchRemindWorker(final ApplicationPeriodService applicationPeriodService, - final MailEventService mailService, - final GeneralSystemSettingsService generalSystemSettingsService, - final IdeaService ideaService, - final Clock clock) { + public ManualMatchRemindWorker( + final ApplicationPeriodService applicationPeriodService, + final MailEventService mailService, + final GeneralSystemSettingsService generalSystemSettingsService, + final IdeaService ideaService, + final Clock clock + ) { this.applicationPeriodService = applicationPeriodService; this.mailService = mailService; this.generalSystemSettingsService = generalSystemSettingsService; @@ -38,14 +39,15 @@ public class ManualMatchRemindWorker extends AbstractWorker { @Override protected void doWork() { + String matchResponsibleMail = generalSystemSettingsService + .getGeneralSystemSettingsInstance() + .getMatchResponsibleMail(); - String matchResponsibleMail = generalSystemSettingsService.getGeneralSystemSettingsInstance().getMatchResponsibleMail(); - - if (matchResponsibleMail==null || matchResponsibleMail.isEmpty()){ + if (matchResponsibleMail == null || matchResponsibleMail.isEmpty()) { return; } - for (ApplicationPeriod applicationPeriod : applicationPeriodService.findAll()){ + for (ApplicationPeriod applicationPeriod : applicationPeriodService.findAll()) { if (LocalDate.now(clock).equals(applicationPeriod.getEndDate())) { MailEvent mailEvent = new MailEvent(); mailEvent.setNonUserRecipients(new HashSet<>(Collections.singletonList(matchResponsibleMail))); @@ -58,22 +60,27 @@ public class ManualMatchRemindWorker extends AbstractWorker { sb.append("End date: ").append(applicationPeriod.getEndDate()).append('\n'); sb.append("Course start date: ").append(applicationPeriod.getCourseStartDate()).append('\n'); - for (ProjectType projectType : applicationPeriod.getProjectTypes()){ - + for (ProjectType projectType : applicationPeriod.getProjectTypes()) { IdeaService.Filter params = new IdeaService.Filter(); params.setLevels(Collections.singletonList(projectType)); params.setStatuses(Collections.singletonList(Idea.Status.UNMATCHED)); params.setTypes(Collections.singletonList(Idea.Type.STUDENT)); - sb.append(projectType.getName()).append(" ideas to match: ").append(ideaService.countByApplicationPeriod(applicationPeriod, params)).append('\n'); + sb + .append(projectType.getName()) + .append(" ideas to match: ") + .append(ideaService.countByApplicationPeriod(applicationPeriod, params)) + .append('\n'); } - sb.append("Total no of ideas in application period: ").append(ideaService.countByApplicationPeriod(applicationPeriod, new IdeaService.Filter())).append('\n'); + sb + .append("Total no of ideas in application period: ") + .append(ideaService.countByApplicationPeriod(applicationPeriod, new IdeaService.Filter())) + .append('\n'); mailEvent.setMessageBody(sb.toString()); mailService.save(mailEvent); - } } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorker.java index d92764fa0b..27d96f8626 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorker.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.workerthreads; +import jakarta.inject.Inject; +import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; @@ -15,23 +17,25 @@ import se.su.dsv.scipro.notifications.settings.service.DeliveryConfigurationServ import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class NotificationCompilationWorker extends AbstractWorker { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationCompilationWorker.class); @Inject NotificationService notificationService; + @Inject NotificationMailFormatter notificationMailFormatter; + @Inject MailEventService mailEventService; + @Inject GeneralSystemSettingsService systemSettingsService; + @Inject DeliveryConfigurationService deliveryConfiguration; + @Inject UserProfileService userProfileService; @@ -40,7 +44,7 @@ public class NotificationCompilationWorker extends AbstractWorker { LOGGER.info("Starting NotificationCompilationWorker.."); Map> notifications = getUserListMap(); - for(Map.Entry> entry : notifications.entrySet()) { + for (Map.Entry> entry : notifications.entrySet()) { sendNotifications(entry.getKey(), entry.getValue()); } @@ -48,7 +52,11 @@ public class NotificationCompilationWorker extends AbstractWorker { for (List notificationList : notifications.values()) { notificationCount += notificationList.size(); } - LOGGER.info("Sent notification compilation to {} users covering {} notifications.", notifications.size(), notificationCount); + LOGGER.info( + "Sent notification compilation to {} users covering {} notifications.", + notifications.size(), + notificationCount + ); } private void sendNotifications(User user, List notifications) { @@ -88,7 +96,14 @@ public class NotificationCompilationWorker extends AbstractWorker { User user = notification.getUser(); - if (deliveryConfiguration.isDelivery(notification.getType(), notification.getEvent(), DeliveryMethod.MAIL, Optional.ofNullable(user))) { + if ( + deliveryConfiguration.isDelivery( + notification.getType(), + notification.getEvent(), + DeliveryMethod.MAIL, + Optional.ofNullable(user) + ) + ) { notifications.putIfAbsent(user, new LinkedList<>()); notifications.get(user).add(notification); } diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/RepeatingSchedule.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/RepeatingSchedule.java index 1b577c98a9..9498491356 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/RepeatingSchedule.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/RepeatingSchedule.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.workerthreads; import java.util.concurrent.TimeUnit; class RepeatingSchedule extends Schedule { + private final long period; private final TimeUnit timeUnit; diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/Schedule.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/Schedule.java index 45f797d049..0a3ac9d0d8 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/Schedule.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/Schedule.java @@ -3,8 +3,11 @@ package se.su.dsv.scipro.workerthreads; import java.util.concurrent.TimeUnit; public abstract class Schedule { + public abstract long getDelay(); + public abstract long getPeriod(); + public abstract TimeUnit getTimeUnit(); static Schedule every(final long delay, final TimeUnit timeUnit) { diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/Task.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/Task.java index 3e5f06a700..01815b10e2 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/Task.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/Task.java @@ -5,6 +5,7 @@ import java.io.Serializable; import java.util.Comparator; public class Task { + private final Provider worker; private final String description; private final Schedule schedule; @@ -32,6 +33,7 @@ public class Task { } public static class ByDescriptionComparator implements Comparator, Serializable { + @Override public int compare(Task o1, Task o2) { return o1.description.compareTo(o2.description); diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/TemporaryWorkerScheduler.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/TemporaryWorkerScheduler.java index caab359a7f..5b98019b51 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/TemporaryWorkerScheduler.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/TemporaryWorkerScheduler.java @@ -1,41 +1,56 @@ package se.su.dsv.scipro.workerthreads; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import java.util.concurrent.TimeUnit; import se.su.dsv.scipro.mail.MailEventWorker; import se.su.dsv.scipro.plagiarism.PlagiarismSubmitter; import se.su.dsv.scipro.plagiarism.urkund.StatusPollingWorker; import se.su.dsv.scipro.projectpartner.RemoveFulfilledPartnerAdsWorker; import se.su.dsv.scipro.reviewing.ReviewerDecisionReminderWorker; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import java.util.concurrent.TimeUnit; - public class TemporaryWorkerScheduler { + @Inject public TemporaryWorkerScheduler( - Scheduler scheduler, - Provider mailEventWorker, - Provider notificationCompilationWorker, - Provider ideaExportWorker, - Provider thesisUploadReminderWorker, - Provider thesisUploadDeadlineWorker, - Provider manualMatchRemindWorkerProvider, - Provider reviewerDecisionReminderWorker, - Provider plagiarismSubmitter, - Provider urkundPoller, - Provider removeFulfilledPartnerAds, - Provider gradeFinalSeminarParticipantReminderWorkerProvider) - { + Scheduler scheduler, + Provider mailEventWorker, + Provider notificationCompilationWorker, + Provider ideaExportWorker, + Provider thesisUploadReminderWorker, + Provider thesisUploadDeadlineWorker, + Provider manualMatchRemindWorkerProvider, + Provider reviewerDecisionReminderWorker, + Provider plagiarismSubmitter, + Provider urkundPoller, + Provider removeFulfilledPartnerAds, + Provider gradeFinalSeminarParticipantReminderWorkerProvider + ) { scheduler.schedule("Mail-event-worker").runBy(mailEventWorker).every(1, TimeUnit.MINUTES); scheduler.schedule("Check-plagiarism-event-worker").runBy(plagiarismSubmitter).every(10, TimeUnit.MINUTES); - scheduler.schedule("Send out summary mails for all unread notifications").runBy(notificationCompilationWorker).dailyAt(15, 0); + scheduler + .schedule("Send out summary mails for all unread notifications") + .runBy(notificationCompilationWorker) + .dailyAt(15, 0); scheduler.schedule("Export eligible ideas").runBy(ideaExportWorker).dailyAt(1, 0); - scheduler.schedule("Warn about expiring thesis upload deadline").runBy(thesisUploadReminderWorker).dailyAt(4, 0); - scheduler.schedule("Final seminar upload deadline cancel worker").runBy(thesisUploadDeadlineWorker).every(10, TimeUnit.MINUTES); - scheduler.schedule("Remind match responsible to manually match ideas").runBy(manualMatchRemindWorkerProvider).dailyAt(4, 0); + scheduler + .schedule("Warn about expiring thesis upload deadline") + .runBy(thesisUploadReminderWorker) + .dailyAt(4, 0); + scheduler + .schedule("Final seminar upload deadline cancel worker") + .runBy(thesisUploadDeadlineWorker) + .every(10, TimeUnit.MINUTES); + scheduler + .schedule("Remind match responsible to manually match ideas") + .runBy(manualMatchRemindWorkerProvider) + .dailyAt(4, 0); scheduler.schedule("Reviewer decision reminders").runBy(reviewerDecisionReminderWorker).dailyAt(11, 45); scheduler.schedule("Poll URKUND for status").runBy(urkundPoller).every(15, TimeUnit.MINUTES); - scheduler.schedule("Remind supervisors to grade seminar participants").runBy(gradeFinalSeminarParticipantReminderWorkerProvider).dailyAt(7, 0); + scheduler + .schedule("Remind supervisors to grade seminar participants") + .runBy(gradeFinalSeminarParticipantReminderWorkerProvider) + .dailyAt(7, 0); scheduler.schedule("Remove fulfilled partner ads").runBy(removeFulfilledPartnerAds).every(1, TimeUnit.HOURS); } } diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadDeadlineWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadDeadlineWorker.java index 98e9d14f53..490e394bfa 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadDeadlineWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadDeadlineWorker.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.workerthreads; -import se.su.dsv.scipro.finalseminar.FinalSeminar; -import se.su.dsv.scipro.finalseminar.FinalSeminarService; - import jakarta.inject.Inject; import java.time.Instant; import java.time.LocalDate; import java.time.Month; import java.time.ZoneId; import java.util.*; +import se.su.dsv.scipro.finalseminar.FinalSeminar; +import se.su.dsv.scipro.finalseminar.FinalSeminarService; public class ThesisUploadDeadlineWorker extends AbstractWorker { @@ -24,10 +23,9 @@ public class ThesisUploadDeadlineWorker extends AbstractWorker { /** * Feature should not look at seminars held before this date */ - Date validFrom = Date.from(Instant.now() - .atZone(ZoneId.systemDefault()) - .with(LocalDate.of(2013, Month.AUGUST, 8)) - .toInstant()); + Date validFrom = Date.from( + Instant.now().atZone(ZoneId.systemDefault()).with(LocalDate.of(2013, Month.AUGUST, 8)).toInstant() + ); try { FinalSeminarService.Filter params = new FinalSeminarService.Filter(); diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadReminderWorker.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadReminderWorker.java index 9c16bd7196..9f17a5fbc9 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadReminderWorker.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/ThesisUploadReminderWorker.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.workerthreads; +import jakarta.inject.Inject; +import java.text.SimpleDateFormat; +import java.util.Date; import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.finalseminar.FinalSeminar; import se.su.dsv.scipro.finalseminar.FinalSeminarService; @@ -10,17 +13,17 @@ import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.SeminarEvent; import se.su.dsv.scipro.reusable.SciProUtilities; -import jakarta.inject.Inject; -import java.text.SimpleDateFormat; -import java.util.Date; - public class ThesisUploadReminderWorker extends AbstractWorker { + @Inject FinalSeminarSettingsService service; + @Inject FinalSeminarService finalSeminarService; + @Inject NotificationController notificationController; + @Inject DaysService daysService; @@ -29,9 +32,7 @@ public class ThesisUploadReminderWorker extends AbstractWorker { this.beginTransaction(); try { - for (final FinalSeminar fs : finalSeminarService.findByStartDateAfter(new Date())) { - /** * Take the deadline */ @@ -58,10 +59,11 @@ public class ThesisUploadReminderWorker extends AbstractWorker { /** * If the remind date is today, then remind */ - if ((fs.getDocument()==null || - fs.getDocument().getId()==null) && - remindDate.after(todayStart) && - remindDate.before(todayEnd)) { + if ( + (fs.getDocument() == null || fs.getDocument().getId() == null) && + remindDate.after(todayStart) && + remindDate.before(todayEnd) + ) { final NotificationSource source = new NotificationSource(); source.setMessage(new SimpleDateFormat(DateStyle.DATETIME.getFormat()).format(uploadDeadline)); notificationController.notifySeminar(fs, SeminarEvent.Event.THESIS_UPLOAD_REMIND, source); @@ -74,4 +76,4 @@ public class ThesisUploadReminderWorker extends AbstractWorker { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerData.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerData.java index 59fefc8d63..0598cbc57d 100755 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerData.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerData.java @@ -1,96 +1,108 @@ package se.su.dsv.scipro.workerthreads; -import se.su.dsv.scipro.system.DomainObject; - import jakarta.persistence.*; import java.util.Date; import java.util.Objects; +import se.su.dsv.scipro.system.DomainObject; @Entity @Table(name = "worker_data") @Cacheable(true) public class WorkerData extends DomainObject { - public WorkerData() { - lastSuccessfulRun = new Date(0); - } - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(unique = true, nullable = false) - private String name; - - @Column(nullable = false, name = "last_run") - private Date lastRun = new Date(); - - @Column(nullable = false, name = "last_successful_run") - private Date lastSuccessfulRun; - - @PreUpdate - @PrePersist - public void updatelastSuccessfulRun() { - if( lastSuccessfulRun == null ) { - lastSuccessfulRun = new Date(0); - } - } + public WorkerData() { + lastSuccessfulRun = new Date(0); + } - @Override - public Long getId() { - return this.id; - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - public String getName() { - return this.name; - } + @Column(unique = true, nullable = false) + private String name; - public Date getLastRun() { - return this.lastRun; - } + @Column(nullable = false, name = "last_run") + private Date lastRun = new Date(); - public Date getLastSuccessfulRun() { - return this.lastSuccessfulRun; - } + @Column(nullable = false, name = "last_successful_run") + private Date lastSuccessfulRun; - public void setId(Long id) { - this.id = id; - } + @PreUpdate + @PrePersist + public void updatelastSuccessfulRun() { + if (lastSuccessfulRun == null) { + lastSuccessfulRun = new Date(0); + } + } - public void setName(String name) { - this.name = name; - } + @Override + public Long getId() { + return this.id; + } - public void setLastRun(Date lastRun) { - this.lastRun = lastRun; - } + public String getName() { + return this.name; + } - public void setLastSuccessfulRun(Date lastSuccessfulRun) { - this.lastSuccessfulRun = lastSuccessfulRun; - } + public Date getLastRun() { + return this.lastRun; + } - @Override - public String toString() { - return "WorkerData(id=" + this.getId() + ", name=" + this.getName() + ", lastRun=" + this.getLastRun() + ", lastSuccessfulRun=" + this.getLastSuccessfulRun() + ")"; - } + public Date getLastSuccessfulRun() { + return this.lastSuccessfulRun; + } - @Override - public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof WorkerData)) return false; - final WorkerData other = (WorkerData) o; - return other.canEqual(this) - && Objects.equals(this.getId(), other.getId()) - && Objects.equals(this.getName(), other.getName()) - && Objects.equals(this.getLastRun(), other.getLastRun()) - && Objects.equals(this.getLastSuccessfulRun(), other.getLastSuccessfulRun()); - } + public void setId(Long id) { + this.id = id; + } - protected boolean canEqual(final Object other) { - return other instanceof WorkerData; - } + public void setName(String name) { + this.name = name; + } - @Override - public int hashCode() { - return Objects.hash(this.getId(), this.getName(), this.getLastRun(), this.getLastSuccessfulRun()); - } -} \ No newline at end of file + public void setLastRun(Date lastRun) { + this.lastRun = lastRun; + } + + public void setLastSuccessfulRun(Date lastSuccessfulRun) { + this.lastSuccessfulRun = lastSuccessfulRun; + } + + @Override + public String toString() { + return ( + "WorkerData(id=" + + this.getId() + + ", name=" + + this.getName() + + ", lastRun=" + + this.getLastRun() + + ", lastSuccessfulRun=" + + this.getLastSuccessfulRun() + + ")" + ); + } + + @Override + public boolean equals(final Object o) { + if (o == this) return true; + if (!(o instanceof WorkerData)) return false; + final WorkerData other = (WorkerData) o; + return ( + other.canEqual(this) && + Objects.equals(this.getId(), other.getId()) && + Objects.equals(this.getName(), other.getName()) && + Objects.equals(this.getLastRun(), other.getLastRun()) && + Objects.equals(this.getLastSuccessfulRun(), other.getLastSuccessfulRun()) + ); + } + + protected boolean canEqual(final Object other) { + return other instanceof WorkerData; + } + + @Override + public int hashCode() { + return Objects.hash(this.getId(), this.getName(), this.getLastRun(), this.getLastSuccessfulRun()); + } +} diff --git a/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImpl.java b/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImpl.java index 23dccfd75e..7b80062c92 100644 --- a/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImpl.java +++ b/core/src/main/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImpl.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.workerthreads; -import se.su.dsv.scipro.system.AbstractServiceImpl; - import jakarta.inject.Inject; import jakarta.inject.Provider; import jakarta.persistence.EntityManager; +import se.su.dsv.scipro.system.AbstractServiceImpl; + +public class WorkerDataServiceImpl extends AbstractServiceImpl implements WorkerDataService { -public class WorkerDataServiceImpl extends AbstractServiceImpl implements WorkerDataService { @Inject public WorkerDataServiceImpl(Provider em) { super(em, WorkerData.class, QWorkerData.workerData); diff --git a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTest.java index 0ccd31f5a2..f759f3ff87 100644 --- a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTest.java @@ -1,11 +1,16 @@ package se.su.dsv.scipro.activityplan; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.checklist.ChecklistTemplateService; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; @@ -14,33 +19,34 @@ import se.su.dsv.scipro.file.ProjectFileService; import se.su.dsv.scipro.misc.DaysService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { + private static final Pageable ALL = new PageRequest(0, Long.MAX_VALUE); @Mock private EventBus eventBus; + @Mock private ChecklistTemplateService checklistTemplateService; + @Mock private ProjectFileService projectFileService; + @Inject private ActivityService activityService; + @Inject private ActivityPlanService activityPlanService; + @Inject private DaysService daysService; + @Inject private FileService fileService; @@ -55,7 +61,13 @@ public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { @BeforeEach public void setUp() throws Exception { - activityPlanFacade = new ActivityPlanFacadeImpl(eventBus, projectFileService, checklistTemplateService, daysService, fileService); + activityPlanFacade = new ActivityPlanFacadeImpl( + eventBus, + projectFileService, + checklistTemplateService, + daysService, + fileService + ); activityPlanFacade.activityService = activityService; activityPlanFacade.activityPlanService = activityPlanService; project = createProject(); @@ -76,13 +88,28 @@ public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { //create events Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, 1); - Activity pse1 = Activity.builder().activityPlan(activityPlan).date(cal.getTime()).name("").description("").build(); + Activity pse1 = Activity.builder() + .activityPlan(activityPlan) + .date(cal.getTime()) + .name("") + .description("") + .build(); cal.set(Calendar.MONTH, 6); - Activity pse2 = Activity.builder().activityPlan(activityPlan).date(cal.getTime()).name("").description("").build(); + Activity pse2 = Activity.builder() + .activityPlan(activityPlan) + .date(cal.getTime()) + .name("") + .description("") + .build(); cal.set(Calendar.MONTH, 12); - Activity pse3 = Activity.builder().activityPlan(activityPlan).date(cal.getTime()).name("").description("").build(); + Activity pse3 = Activity.builder() + .activityPlan(activityPlan) + .date(cal.getTime()) + .name("") + .description("") + .build(); final FileDescription fileDescription = new FileDescription(); final FileReference fileReference = new FileReference(); fileReference.setFileDescription(fileDescription); @@ -105,7 +132,6 @@ public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { assertEquals(0, activityPlan.getActivities().size()); } - @Test public void findEventsByProjectShortHand() { List expectedList = Collections.singletonList(newActivity()); @@ -168,13 +194,12 @@ public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { return save(project); } - private ActivityPlan createActivityPlan(Project project){ + private ActivityPlan createActivityPlan(Project project) { ActivityPlan activityPlan = ActivityPlan.builder().project(project).build(); activityPlan.setProject(project); return save(activityPlan); } - private Activity newActivity() { return newActivity(today); } @@ -186,7 +211,7 @@ public class ActivityPlanFacadeImplIntegrationTest extends IntegrationTest { return save(activity); } - private User createUser(){ + private User createUser() { return save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTestChecklistMethods.java b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTestChecklistMethods.java index 33c717a87e..00de8adc3d 100644 --- a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTestChecklistMethods.java +++ b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplIntegrationTestChecklistMethods.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.activityplan; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.checklist.Checklist; @@ -11,14 +18,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ActivityPlanFacadeImplIntegrationTestChecklistMethods extends IntegrationTest { private static final String SOME_NAME = "checklist"; @@ -32,19 +31,18 @@ public class ActivityPlanFacadeImplIntegrationTestChecklistMethods extends Integ @BeforeEach public void startTransaction() { - employee1 = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); employee1 = save(employee1); ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor degree thesis project"); bachelor = save(bachelor); - Project project = Project.builder(). - title("project"). - projectType(bachelor). - startDate(LocalDate.now()). - headSupervisor(employee1). - build(); + Project project = Project.builder() + .title("project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(employee1) + .build(); project = save(project); List checklistAnswers = new ArrayList<>(); @@ -66,15 +64,15 @@ public class ActivityPlanFacadeImplIntegrationTestChecklistMethods extends Integ @Test public void testStuff() { assertTrue( - checklist.getQuestions() != null - && !checklist.getQuestions().isEmpty() - && checklist.getQuestions().get(0) != null - && checklist.getQuestions().get(0).getAnswers() != null - && !checklist.getQuestions().get(0).getAnswers().isEmpty() - && checklist.getQuestions().get(0).getAnswers().get(0) != null - && checklist.getQuestions().get(0).getAnswers().get(0).getAnswer() != null - && checklist.getQuestions().get(0).getAnswers().get(0).getAnswer().equals(ChecklistAnswerEnum.GREEN) - && checklist.getUserLastOpenDate().get(employee1) == null + checklist.getQuestions() != null && + !checklist.getQuestions().isEmpty() && + checklist.getQuestions().get(0) != null && + checklist.getQuestions().get(0).getAnswers() != null && + !checklist.getQuestions().get(0).getAnswers().isEmpty() && + checklist.getQuestions().get(0).getAnswers().get(0) != null && + checklist.getQuestions().get(0).getAnswers().get(0).getAnswer() != null && + checklist.getQuestions().get(0).getAnswers().get(0).getAnswer().equals(ChecklistAnswerEnum.GREEN) && + checklist.getUserLastOpenDate().get(employee1) == null ); } @@ -83,7 +81,6 @@ public class ActivityPlanFacadeImplIntegrationTestChecklistMethods extends Integ */ @Test public void testupdateUserLastOpenDate2() { - checklist = activityPlanFacade.updateUserLastOpenDate(checklist, employee1); Date oldDate = checklist.getUserLastOpenDate().get(employee1); @@ -98,4 +95,4 @@ public class ActivityPlanFacadeImplIntegrationTestChecklistMethods extends Integ assertTrue(oldDate.before(newDate)); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplTest.java b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplTest.java index 5be15d7bb1..4469562215 100644 --- a/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanFacadeImplTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.activityplan; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; +import java.time.LocalDate; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,43 +31,49 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class ActivityPlanFacadeImplTest { static final ProjectType PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bach", "bach"); - static final Project SOME_PROJECT = Project.builder().title("title").projectType(PROJECT_TYPE).startDate(LocalDate.now()).build(); + static final Project SOME_PROJECT = Project.builder() + .title("title") + .projectType(PROJECT_TYPE) + .startDate(LocalDate.now()) + .build(); static final ChecklistTemplate SOME_TEMPLATE = new ChecklistTemplate("name", new UserBuilder().create()); static final String SOME_NAME = "someName"; static final String SOME_TITLE = "someTitle"; @Mock private ChecklistService checklistService; + @Mock private ChecklistTemplateService checklistTemplateService; + @Mock private ChecklistQuestionRepo checklistQuestionRepo; + @Mock private ProjectService projectService; + @Mock private EventBus eventBus; + @Mock private ProjectFileService projectFileService; + @Mock private ActivityService activityService; + @Mock private DaysService daysService; + @Mock private FileService fileService; + @InjectMocks private ActivityPlanFacadeImpl activityPlanFacade; + private User user; private Checklist checklist; private ChecklistAnswer answer; @@ -69,9 +82,8 @@ public class ActivityPlanFacadeImplTest { @BeforeEach public void setUp() throws Exception { activityPlanFacade.activityService = activityService; - activityPlanFacade.checklistService = checklistService; - activityPlanFacade.checklistQuestionRepo = checklistQuestionRepo; - + activityPlanFacade.checklistService = checklistService; + activityPlanFacade.checklistQuestionRepo = checklistQuestionRepo; user = new UserBuilder().create(); User userWithoutAnswers = new UserBuilder().create(); @@ -147,4 +159,4 @@ public class ActivityPlanFacadeImplTest { answer.setAnswer(ChecklistAnswerEnum.NO_ANSWER); assertFalse(activityPlanFacade.isCompletedByUser(user, checklist)); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImplTest.java index 82907edc00..9407b77f5b 100644 --- a/core/src/test/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/checklist/ChecklistTemplateServiceImplTest.java @@ -1,26 +1,26 @@ package se.su.dsv.scipro.checklist; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.reusable.SciProUtilities; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.ArrayList; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.ArrayList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.reusable.SciProUtilities; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; + public class ChecklistTemplateServiceImplTest extends IntegrationTest { public static final PageRequest ALL = new PageRequest(0, Long.MAX_VALUE); + @Inject private ChecklistTemplateServiceImpl checklistTemplateService; @@ -91,7 +91,9 @@ public class ChecklistTemplateServiceImplTest extends IntegrationTest { @Test public void find_peer_request_checklists() { ProjectType master = save(new ProjectType(DegreeType.MASTER, "Master", "Master")); - Project project = save(Project.builder().title("Title").projectType(master).startDate(LocalDate.now()).headSupervisor(user).build()); + Project project = save( + Project.builder().title("Title").projectType(master).startDate(LocalDate.now()).headSupervisor(user).build() + ); template.getCategories().add(save(new ChecklistCategory(ChecklistTemplateServiceImpl.PEER))); template.getProjectTypes().add(master); diff --git a/core/src/test/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImplTest.java b/core/src/test/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImplTest.java index f364834af6..44eb67b749 100644 --- a/core/src/test/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/daisyExternal/http/DaisyAPIImplTest.java @@ -1,222 +1,223 @@ package se.su.dsv.scipro.daisyExternal.http; -import com.sun.net.httpserver.HttpServer; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.io.dto.Person; -import se.su.dsv.scipro.io.dto.ProjectParticipant; -import se.su.dsv.scipro.io.dto.Role; - -import jakarta.ws.rs.core.Response; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.InetSocketAddress; -import java.util.*; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; +import com.sun.net.httpserver.HttpServer; +import jakarta.ws.rs.core.Response; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.InetSocketAddress; +import java.util.*; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.io.dto.Person; +import se.su.dsv.scipro.io.dto.ProjectParticipant; +import se.su.dsv.scipro.io.dto.Role; + public class DaisyAPIImplTest { + @Test public void get_contributors_deserialization() throws IOException { - String xml = """ - - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -1 - Bob - Bobbity - bob@example.com - 2018-05-17T10:33:39.413+02:00 - false - - OPPONENT - 15157 - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -2 - Bill - Gates - bill@example.com - 2020-12-21T12:24:40.477+01:00 - false - - OPPONENT - 15091 - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -3 - Elon - Musk - elon@example.com - 2018-02-06T15:25:52.810+01:00 - false - - OPPONENT - 15176 - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -4 - Jeff - Bezos - jeff@example.com - 2019-09-07T00:49:20.447+02:00 - false - - ACTIVE_PARTICIPATION - 15083 - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -5 - Warren - Buffet - warren@example.com - 2018-02-06T15:19:29.480+01:00 - false - - ACTIVE_PARTICIPATION - 15172 - - - - -6 - Steve - Jebs - steve@example.com - 2021-11-09T00:42:40.592+01:00 - false - - EXAMINER - 18342 - - - - -7 - Steve - Ballmer - ballmer@example.com - 2018-02-06T18:00:41.267+01:00 - false - - SUPERVISOR - 13761 - - - - IB015E - 15 - 40633 - FIRST_CYCLE - SU - - - -8 - Donald - Trump - 2017-10-03T05:00:18.787+02:00 - false - - ACTIVE_PARTICIPATION - 15147 - - - - IB617B - 15 - 28530 - FIRST_CYCLE - SU - - - -9 - Barrack - Obama - 2017-11-10T18:48:59.680+01:00 - false - - ACTIVE_PARTICIPATION - 15181 - - - - IB617B - 15 - 28530 - FIRST_CYCLE - SU - - - -10 - Richard - Nixon - nixon@example.com - 2018-02-06T17:50:05.560+01:00 - false - - ACTIVE_PARTICIPATION - 15149 - - - - IB617B - 15 - 28530 - FIRST_CYCLE - SU - - - -11 - Saddam - Hussein - saddam@example.com - 2019-10-16T00:50:02.773+02:00 - false - - ACTIVE_PARTICIPATION - 15148 - - - """; + String xml = + """ + + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -1 + Bob + Bobbity + bob@example.com + 2018-05-17T10:33:39.413+02:00 + false + + OPPONENT + 15157 + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -2 + Bill + Gates + bill@example.com + 2020-12-21T12:24:40.477+01:00 + false + + OPPONENT + 15091 + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -3 + Elon + Musk + elon@example.com + 2018-02-06T15:25:52.810+01:00 + false + + OPPONENT + 15176 + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -4 + Jeff + Bezos + jeff@example.com + 2019-09-07T00:49:20.447+02:00 + false + + ACTIVE_PARTICIPATION + 15083 + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -5 + Warren + Buffet + warren@example.com + 2018-02-06T15:19:29.480+01:00 + false + + ACTIVE_PARTICIPATION + 15172 + + + + -6 + Steve + Jebs + steve@example.com + 2021-11-09T00:42:40.592+01:00 + false + + EXAMINER + 18342 + + + + -7 + Steve + Ballmer + ballmer@example.com + 2018-02-06T18:00:41.267+01:00 + false + + SUPERVISOR + 13761 + + + + IB015E + 15 + 40633 + FIRST_CYCLE + SU + + + -8 + Donald + Trump + 2017-10-03T05:00:18.787+02:00 + false + + ACTIVE_PARTICIPATION + 15147 + + + + IB617B + 15 + 28530 + FIRST_CYCLE + SU + + + -9 + Barrack + Obama + 2017-11-10T18:48:59.680+01:00 + false + + ACTIVE_PARTICIPATION + 15181 + + + + IB617B + 15 + 28530 + FIRST_CYCLE + SU + + + -10 + Richard + Nixon + nixon@example.com + 2018-02-06T17:50:05.560+01:00 + false + + ACTIVE_PARTICIPATION + 15149 + + + + IB617B + 15 + 28530 + FIRST_CYCLE + SU + + + -11 + Saddam + Hussein + saddam@example.com + 2019-10-16T00:50:02.773+02:00 + false + + ACTIVE_PARTICIPATION + 15148 + + + """; HttpServer httpServer = fakeRemoteServerWithXmlResponse(xml); httpServer.start(); DaisyAPIImpl daisyAPI = getDaisyAPI(httpServer); @@ -231,28 +232,29 @@ public class DaisyAPIImplTest { */ @Test public void add_contributor_serialization() throws IOException { - String xml = """ - - - - ... - 12345 - 12345 - SECOND_CYCLE - ... - - - 12345 - ... - ... - ... - 12345 - true - - ASSISTANT_SUPERVISOR - 12345 - - """; + String xml = + """ + + + + ... + 12345 + 12345 + SECOND_CYCLE + ... + + + 12345 + ... + ... + ... + 12345 + true + + ASSISTANT_SUPERVISOR + 12345 + + """; HttpServer httpServer = fakeRemoteServerWithXmlResponse(xml); DaisyAPIImpl daisyAPI = getDaisyAPI(httpServer); httpServer.start(); @@ -289,4 +291,4 @@ public class DaisyAPIImplTest { }); return httpServer; } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/date/DateServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/date/DateServiceImplTest.java index e3ab4fae59..0c3ac19d6d 100644 --- a/core/src/test/java/se/su/dsv/scipro/date/DateServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/date/DateServiceImplTest.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.date; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; - import jakarta.inject.Inject; import java.util.Date; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; public class DateServiceImplTest extends IntegrationTest { @@ -14,13 +13,10 @@ public class DateServiceImplTest extends IntegrationTest { @Test public void testFormat() { - // when String date = service.format(new Date()); // then Assertions.assertNotNull(date); } - - } diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImplIntegrationTest.java index 97bdd1b8e2..9b27323fd4 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarOppositionServiceImplIntegrationTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.finalseminar; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.Month; +import java.util.Date; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -11,17 +17,11 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.Month; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class FinalSeminarOppositionServiceImplIntegrationTest extends IntegrationTest { @Inject private FinalSeminarOppositionServiceImpl finalSeminarOppositionService; + private FinalSeminar finalSeminar; private ProjectType projectType; @@ -53,8 +53,10 @@ public class FinalSeminarOppositionServiceImplIntegrationTest extends Integratio } private GradingReportTemplate createGradingReportTemplate() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(projectType, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + projectType, + LocalDate.of(2024, Month.JANUARY, 1) + ); return save(gradingReportTemplate); } @@ -69,11 +71,11 @@ public class FinalSeminarOppositionServiceImplIntegrationTest extends Integratio private Project createProject(ProjectType projectType) { Project project = Project.builder() - .title("title") - .projectType(projectType) - .startDate(LocalDate.now()) - .headSupervisor(createUser()) - .build(); + .title("title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(createUser()) + .build(); return save(project); } diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImplIntegrationTest.java index aec42c16e9..ef6d059972 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarRespondentServiceImplIntegrationTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.finalseminar; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Date; +import java.util.TreeSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -9,15 +17,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Date; -import java.util.TreeSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class FinalSeminarRespondentServiceImplIntegrationTest extends IntegrationTest { @Inject @@ -57,12 +56,12 @@ public class FinalSeminarRespondentServiceImplIntegrationTest extends Integratio TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Arrays.asList(user, user2)); Project project = Project.builder() - .title("title") - .projectType(projectType) - .startDate(LocalDate.now()) - .projectParticipants(projectParticipants) - .headSupervisor(createUser()) - .build(); + .title("title") + .projectType(projectType) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(createUser()) + .build(); return save(project); } diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarSchedulingTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarSchedulingTest.java index d6d3bd3b69..23ebd8113c 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarSchedulingTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarSchedulingTest.java @@ -1,5 +1,18 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Month; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriod; @@ -15,30 +28,20 @@ import se.su.dsv.scipro.test.MutableFixedClock; import se.su.dsv.scipro.test.StreamingUpload; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Month; -import java.util.Optional; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class FinalSeminarSchedulingTest extends IntegrationTest { @Inject FinalSeminarService finalSeminarService; + @Inject FinalSeminarSettingsService finalSeminarSettingsService; + @Inject MutableFixedClock clock; + @Inject RoughDraftApprovalService roughDraftApprovalService; + @Inject ReviewerDecisionService reviewerDecisionService; @@ -48,17 +51,37 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { @BeforeEach public void setUp() { ProjectType master = save(new ProjectType(DegreeType.MASTER, "Master", "Master")); - User supervisor = save(User.builder().firstName("Hasse").lastName("Handledare").emailAddress("hasse@example.com").build()); - exemptedProject = save(Project.builder().title("Title").projectType(master).startDate(LocalDate.now()).headSupervisor(supervisor).build()); + User supervisor = save( + User.builder().firstName("Hasse").lastName("Handledare").emailAddress("hasse@example.com").build() + ); + exemptedProject = save( + Project.builder() + .title("Title") + .projectType(master) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build() + ); exemptedProject.setFinalSeminarRuleExempted(true); - notExemptedProject = save(Project.builder().title("Title").projectType(master).startDate(LocalDate.now()).headSupervisor(supervisor).build()); + notExemptedProject = save( + Project.builder() + .title("Title") + .projectType(master) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build() + ); } @Test public void exempted_final_seminar_will_always_schedule() { setDaysAheadToCreate(10); final FinalSeminarDetails details = detailsAt(); - Either move = finalSeminarService.schedule(exemptedProject, LocalDateTime.now(clock), details); + Either move = finalSeminarService.schedule( + exemptedProject, + LocalDateTime.now(clock), + details + ); assertTrue(move.isRight()); } @@ -73,11 +96,18 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { LocalDate when = LocalDate.of(2022, Month.OCTOBER, 16); FinalSeminarDetails original = detailsAt(); - Either scheduled = finalSeminarService.schedule(notExemptedProject, when.atStartOfDay(), original); + Either scheduled = finalSeminarService.schedule( + notExemptedProject, + when.atStartOfDay(), + original + ); assertTrue(scheduled.isRight(), "Must schedule correctly to attempt a move"); - Either move = finalSeminarService.move(scheduled.right(), someNonWorkDay.atStartOfDay()); + Either move = finalSeminarService.move( + scheduled.right(), + someNonWorkDay.atStartOfDay() + ); assertThat(move, is(Either.left(new NonWorkDay(someNonWorkDay)))); } @@ -90,7 +120,11 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { LocalDate when = LocalDate.of(2022, Month.OCTOBER, 4); FinalSeminarDetails details = detailsAt(); - Either scheduled = finalSeminarService.schedule(notExemptedProject, when.atStartOfDay(), details); + Either scheduled = finalSeminarService.schedule( + notExemptedProject, + when.atStartOfDay(), + details + ); assertFalse(scheduled.isRight(), "Should fail to schedule"); assertThat(scheduled.left(), instanceOf(NotEnoughWorkDays.class)); @@ -104,7 +138,11 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { LocalDate when = LocalDate.of(2022, Month.OCTOBER, 17); FinalSeminarDetails original = detailsAt(); - Either scheduled = finalSeminarService.schedule(notExemptedProject, when.atStartOfDay(), original); + Either scheduled = finalSeminarService.schedule( + notExemptedProject, + when.atStartOfDay(), + original + ); assertTrue(scheduled.isRight(), "Seminar should be scheduled"); @@ -122,7 +160,11 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { LocalDate when = LocalDate.of(2022, Month.OCTOBER, 15); FinalSeminarDetails finalSeminarDetails = detailsAt(); - Either scheduled = finalSeminarService.schedule(notExemptedProject, when.atStartOfDay(), finalSeminarDetails); + Either scheduled = finalSeminarService.schedule( + notExemptedProject, + when.atStartOfDay(), + finalSeminarDetails + ); assertFalse(scheduled.isRight(), "Scheduling should be stopped"); assertThat(scheduled.left(), instanceOf(RoughDraftNotApproved.class)); @@ -136,7 +178,11 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { LocalDate when = LocalDate.of(2022, Month.OCTOBER, 15); FinalSeminarDetails finalSeminarDetails = detailsAt(); - Either scheduled = finalSeminarService.schedule(exemptedProject, when.atStartOfDay(), finalSeminarDetails); + Either scheduled = finalSeminarService.schedule( + exemptedProject, + when.atStartOfDay(), + finalSeminarDetails + ); assertTrue(scheduled.isRight(), "Scheduling should be allowed on exempted project"); } @@ -161,8 +207,8 @@ public class FinalSeminarSchedulingTest extends IntegrationTest { private void approveRoughDraftApproval(Project project) { ByteArrayInputStream data = new ByteArrayInputStream("a".getBytes(StandardCharsets.UTF_8)); StreamingUpload upload = new StreamingUpload("f.txt", "text/plain", project.getHeadSupervisor(), 1, data); - roughDraftApprovalService.requestApproval(project, upload, "no comment").foreach(approval -> - reviewerDecisionService.approve( - approval, "very nice!", Optional.empty())); + roughDraftApprovalService + .requestApproval(project, upload, "no comment") + .foreach(approval -> reviewerDecisionService.approve(approval, "very nice!", Optional.empty())); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplIntegrationTest.java index a3fc78016c..3cced9804a 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplIntegrationTest.java @@ -1,9 +1,20 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static se.su.dsv.scipro.test.Matchers.isLeft; +import static se.su.dsv.scipro.test.Matchers.isRight; + import com.google.common.collect.Lists; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.project.Project; @@ -11,21 +22,9 @@ import se.su.dsv.scipro.report.GradingReportTemplate; import se.su.dsv.scipro.report.OppositionReport; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZonedDateTime; -import java.util.Date; -import java.util.List; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static se.su.dsv.scipro.test.Matchers.isLeft; -import static se.su.dsv.scipro.test.Matchers.isRight; - public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { @Inject @@ -99,21 +98,30 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { @Test public void can_not_oppose_past_seminar() { - assertThat(finalSeminarService.canOppose(user, pastFinalSeminar, otherProject), isLeft(instanceOf(AlreadyHappened.class))); + assertThat( + finalSeminarService.canOppose(user, pastFinalSeminar, otherProject), + isLeft(instanceOf(AlreadyHappened.class)) + ); } @Test public void can_not_oppose_if_already_opponent() { otherProject.addProjectParticipant(user); finalSeminarService.attemptAddOppositionAsSupervisor(user, futureFinalSeminar, otherProject); - assertThat(finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), isLeft(instanceOf(AlreadyParticipating.class))); + assertThat( + finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), + isLeft(instanceOf(AlreadyParticipating.class)) + ); } @Test public void can_not_oppose_if_participant() { otherProject.addProjectParticipant(user); finalSeminarService.attemptAddActiveParticipationAsSupervisor(user, futureFinalSeminar, otherProject); - assertThat(finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), isLeft(instanceOf(AlreadyParticipating.class))); + assertThat( + finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), + isLeft(instanceOf(AlreadyParticipating.class)) + ); } @Test @@ -123,50 +131,74 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { @Test public void can_not_participate_on_past_seminar() { - assertThat(finalSeminarService.canActiveParticipate(user, pastFinalSeminar), isLeft(instanceOf(ParticipationAlreadyHappened.class))); + assertThat( + finalSeminarService.canActiveParticipate(user, pastFinalSeminar), + isLeft(instanceOf(ParticipationAlreadyHappened.class)) + ); } @Test public void can_not_participate_twice() { otherProject.addProjectParticipant(user); finalSeminarService.attemptAddActiveParticipationAsSupervisor(user, futureFinalSeminar, otherProject); - assertThat(finalSeminarService.canActiveParticipate(user, futureFinalSeminar), isLeft(instanceOf(ParticipationAlreadyParticipating.class))); + assertThat( + finalSeminarService.canActiveParticipate(user, futureFinalSeminar), + isLeft(instanceOf(ParticipationAlreadyParticipating.class)) + ); } @Test public void can_not_oppose_if_max_is_reached() { futureFinalSeminar.setMaxOpponents(0); - assertThat(finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), isLeft(instanceOf(TooManyOpponents.class))); + assertThat( + finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), + isLeft(instanceOf(TooManyOpponents.class)) + ); } @Test public void can_not_participate_if_max_is_reached() { futureFinalSeminar.setMaxParticipants(0); - assertThat(finalSeminarService.canActiveParticipate(user, futureFinalSeminar), isLeft(instanceOf(TooManyParticipants.class))); + assertThat( + finalSeminarService.canActiveParticipate(user, futureFinalSeminar), + isLeft(instanceOf(TooManyParticipants.class)) + ); } @Test public void can_not_oppose_if_is_author() { futureFinalSeminar.getProject().addProjectParticipant(user); - assertThat(finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), isLeft(instanceOf(AlreadyParticipating.class))); + assertThat( + finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), + isLeft(instanceOf(AlreadyParticipating.class)) + ); } @Test public void can_not_participate_if_is_author() { futureFinalSeminar.getProject().addProjectParticipant(user); - assertThat(finalSeminarService.canActiveParticipate(user, futureFinalSeminar), isLeft(instanceOf(ParticipationAlreadyParticipating.class))); + assertThat( + finalSeminarService.canActiveParticipate(user, futureFinalSeminar), + isLeft(instanceOf(ParticipationAlreadyParticipating.class)) + ); } @Test public void can_not_oppose_on_deleted_seminar() { futureFinalSeminar.setDeleted(true); - assertThat(finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), isLeft(instanceOf(FinalSeminarCancelled.class))); + assertThat( + finalSeminarService.canOppose(user, futureFinalSeminar, otherProject), + isLeft(instanceOf(FinalSeminarCancelled.class)) + ); } @Test public void can_not_participate_on_deleted_seminar() { futureFinalSeminar.setDeleted(true); - assertThat(finalSeminarService.canActiveParticipate(user, futureFinalSeminar), isLeft(instanceOf(ParticipationFinalSeminarCancelled.class))); + assertThat( + finalSeminarService.canActiveParticipate(user, futureFinalSeminar), + isLeft(instanceOf(ParticipationFinalSeminarCancelled.class)) + ); } @Test @@ -201,7 +233,7 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { addOpposition(unfinishedTooEarly, null); final Date before = Date.from(ZonedDateTime.now().minusDays(5).toInstant()); - List seminars = finalSeminarService.findUnfinishedSeminars(null, before, new PageRequest(0, 5) ); + List seminars = finalSeminarService.findUnfinishedSeminars(null, before, new PageRequest(0, 5)); assertEquals(1, seminars.size()); assertThat(seminars, hasItem(unfinished)); } @@ -254,7 +286,10 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { setOppositionPriorityDaysTo(8); FinalSeminar finalSeminar = createFutureFinalSeminarSomeDaysAgo(5); - assertThat(finalSeminarService.canOppose(user, finalSeminar, otherProject), isLeft(instanceOf(PriorityForSeminarAuthors.class))); + assertThat( + finalSeminarService.canOppose(user, finalSeminar, otherProject), + isLeft(instanceOf(PriorityForSeminarAuthors.class)) + ); } @Test @@ -317,8 +352,7 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { } private GradingReportTemplate createGradingReportTemplate(ProjectType projectType) { - GradingReportTemplate template = new GradingReportTemplate(projectType, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate template = new GradingReportTemplate(projectType, LocalDate.of(2024, Month.JANUARY, 1)); return save(template); } @@ -360,7 +394,12 @@ public class FinalSeminarServiceImplIntegrationTest extends IntegrationTest { } private Project createProject(User supervisor, ProjectType projectType) { - Project project = Project.builder().title("Some title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + Project project = Project.builder() + .title("Some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); return save(project); } diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplTest.java index a0f5b8c592..8e14741410 100755 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarServiceImplTest.java @@ -1,6 +1,25 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import jakarta.persistence.EntityManager; +import java.lang.reflect.Field; +import java.time.Clock; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZonedDateTime; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -26,26 +45,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.InstanceProvider; -import jakarta.persistence.EntityManager; -import java.lang.reflect.Field; -import java.time.Clock; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class FinalSeminarServiceImplTest { @@ -60,18 +59,25 @@ public class FinalSeminarServiceImplTest { @Mock FileService fileDescriptionService; + @Mock OppositionReportService oppositionReportService; + @Mock AuthorRepository authorRepository; + @Mock FinalSeminarOppositionRepo finalSeminarOppositionRepository; + @Mock FinalSeminarActiveParticipationRepository finalSeminarActiveParticipationRepository; + @Mock FinalSeminarRepository finalSeminarRepository; + @Mock RoughDraftApprovalService roughDraftApprovalService; + private EventBus eventBus; @BeforeEach @@ -80,7 +86,17 @@ public class FinalSeminarServiceImplTest { daysService = mock(DaysService.class); eventBus = mock(EventBus.class); - seminarService = new FinalSeminarServiceImpl(new InstanceProvider<>(em), eventBus, authorRepository, fileDescriptionService, finalSeminarOppositionRepository, finalSeminarActiveParticipationRepository, finalSeminarRepository, Clock.systemDefaultZone(), roughDraftApprovalService); + seminarService = new FinalSeminarServiceImpl( + new InstanceProvider<>(em), + eventBus, + authorRepository, + fileDescriptionService, + finalSeminarOppositionRepository, + finalSeminarActiveParticipationRepository, + finalSeminarRepository, + Clock.systemDefaultZone(), + roughDraftApprovalService + ); seminarService.finalSeminarSettingsService = finalSeminarSettingsService; seminarService.daysService = daysService; seminarService.oppositionReportService = oppositionReportService; @@ -99,8 +115,9 @@ public class FinalSeminarServiceImplTest { finalSeminarSettings.setDaysAheadToUploadThesis(5); when(finalSeminarSettingsService.getInstance()).thenReturn(finalSeminarSettings); - when(daysService.workDaysAhead(finalSeminar.getStartDate(), finalSeminarSettings.getDaysAheadToUploadThesis())).thenReturn(date); - + when( + daysService.workDaysAhead(finalSeminar.getStartDate(), finalSeminarSettings.getDaysAheadToUploadThesis()) + ).thenReturn(date); assertTrue(seminarService.hasDeadlinePassed(finalSeminar)); } @@ -139,8 +156,15 @@ public class FinalSeminarServiceImplTest { FinalSeminarOpposition finalSeminarOpposition = new FinalSeminarOpposition(); DomainObjects.injectId(finalSeminarOpposition, 1L); - finalSeminarOpposition.setOppositionReport(new OppositionReport(new GradingReportTemplate(new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"), - LocalDate.of(2024, Month.JANUARY, 1)), finalSeminarOpposition)); + finalSeminarOpposition.setOppositionReport( + new OppositionReport( + new GradingReportTemplate( + new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"), + LocalDate.of(2024, Month.JANUARY, 1) + ), + finalSeminarOpposition + ) + ); finalSeminar.setOppositions(Collections.singletonList(finalSeminarOpposition)); seminarService.delete(finalSeminar); @@ -153,7 +177,6 @@ public class FinalSeminarServiceImplTest { FinalSeminarDeletedEvent event = captor.getValue(); assertThat(event.getFinalSeminar(), is(finalSeminar)); - } @Test @@ -191,5 +214,4 @@ public class FinalSeminarServiceImplTest { p.setHeadSupervisor(supervisor); return p; } - } diff --git a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImplTest.java b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImplTest.java index c48a49ac0d..d35ed79e58 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarUploadControllerImplTest.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,74 +25,80 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class FinalSeminarUploadControllerImplTest { - @InjectMocks - private FinalSeminarUploadControllerImpl finalSeminarUploadController; + @InjectMocks + private FinalSeminarUploadControllerImpl finalSeminarUploadController; - @Mock - private ProjectService projectService; - @Mock - private FileService fileDescriptionService; - @Mock - private FinalSeminarSettingsService finalSeminarSettingsService; - @Mock - private FinalSeminarService finalSeminarService; - @Mock - private NotificationController notificationController; - @Mock - private FinalSeminarOppositionRepo finalSeminarOppositionRepo; - @Mock - private EventBus eventBus; - @Mock - private ProjectFileService projectFileService; - @Mock - private PlagiarismControl plagiarismControl; - public Project project; - public FinalSeminar seminar; - public User uploader; - public FileDescription fileDescription; + @Mock + private ProjectService projectService; - @BeforeEach - public void setUp() throws Exception { - project = Project.builder().title("title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); - project.setId(812L); - seminar = new FinalSeminar(); - seminar.setId(738L); - seminar.setProject(project); - uploader = new UserBuilder().create(); - project.addProjectParticipant(uploader); + @Mock + private FileService fileDescriptionService; - fileDescription = new FileDescription(); - prepareMocksForSeminarDocumentUpload(project, seminar, fileDescription); - } + @Mock + private FinalSeminarSettingsService finalSeminarSettingsService; - @Test - public void storeSeminarDocument() { + @Mock + private FinalSeminarService finalSeminarService; - FileUpload fileUpload = createFileUpload(); + @Mock + private NotificationController notificationController; + @Mock + private FinalSeminarOppositionRepo finalSeminarOppositionRepo; - finalSeminarUploadController.storeSeminarDocument(fileUpload, seminar); + @Mock + private EventBus eventBus; - verify(fileDescriptionService).storeFile(fileUpload); - verify(finalSeminarService).save(seminar); + @Mock + private ProjectFileService projectFileService; - assertEquals(seminar.getDocument().getFileDescription(), fileDescription); - } + @Mock + private PlagiarismControl plagiarismControl; + + public Project project; + public FinalSeminar seminar; + public User uploader; + public FileDescription fileDescription; + + @BeforeEach + public void setUp() throws Exception { + project = Project.builder() + .title("title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); + project.setId(812L); + seminar = new FinalSeminar(); + seminar.setId(738L); + seminar.setProject(project); + uploader = new UserBuilder().create(); + project.addProjectParticipant(uploader); + + fileDescription = new FileDescription(); + prepareMocksForSeminarDocumentUpload(project, seminar, fileDescription); + } @Test - public void sendsEventWhenFinalThesisUploaded() { - finalSeminarUploadController.storeSeminarDocument(createFileUpload(), seminar); + public void storeSeminarDocument() { + FileUpload fileUpload = createFileUpload(); - verify(eventBus).post(isA(FinalSeminarThesisUploadedEvent.class)); - } + finalSeminarUploadController.storeSeminarDocument(fileUpload, seminar); + + verify(fileDescriptionService).storeFile(fileUpload); + verify(finalSeminarService).save(seminar); + + assertEquals(seminar.getDocument().getFileDescription(), fileDescription); + } + + @Test + public void sendsEventWhenFinalThesisUploaded() { + finalSeminarUploadController.storeSeminarDocument(createFileUpload(), seminar); + + verify(eventBus).post(isA(FinalSeminarThesisUploadedEvent.class)); + } private FileUpload createFileUpload() { FileUpload fileUpload = mock(FileUpload.class); @@ -97,13 +107,17 @@ public class FinalSeminarUploadControllerImplTest { return fileUpload; } - private void prepareMocksForSeminarDocumentUpload(Project project, FinalSeminar seminar, FileDescription fileDescription) { - when(projectService.findOne(anyLong())).thenReturn(project); - when(finalSeminarSettingsService.getInstance()).thenReturn(new FinalSeminarSettings()); - when(finalSeminarService.findOne(anyLong())).thenReturn(seminar); - when(finalSeminarService.save(seminar)).thenReturn(seminar); - final FileReference value = new FileReference(); - value.setFileDescription(fileDescription); - when(fileDescriptionService.storeFile(any())).thenReturn(value); - } + private void prepareMocksForSeminarDocumentUpload( + Project project, + FinalSeminar seminar, + FileDescription fileDescription + ) { + when(projectService.findOne(anyLong())).thenReturn(project); + when(finalSeminarSettingsService.getInstance()).thenReturn(new FinalSeminarSettings()); + when(finalSeminarService.findOne(anyLong())).thenReturn(seminar); + when(finalSeminarService.save(seminar)).thenReturn(seminar); + final FileReference value = new FileReference(); + value.setFileDescription(fileDescription); + when(fileDescriptionService.storeFile(any())).thenReturn(value); + } } diff --git a/core/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImplTest.java index 97eee113b0..433ee9c53a 100644 --- a/core/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisServiceImplTest.java @@ -1,39 +1,38 @@ package se.su.dsv.scipro.finalthesis; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileService; -import se.su.dsv.scipro.file.ProjectFileUpload; -import se.su.dsv.scipro.notifications.dataobject.NotificationSource; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; -import se.su.dsv.scipro.test.StreamingUpload; - -import jakarta.inject.Inject; - -import java.io.InputStream; -import java.time.LocalDate; - import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import jakarta.inject.Inject; +import java.io.InputStream; +import java.time.LocalDate; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileService; +import se.su.dsv.scipro.file.ProjectFileUpload; +import se.su.dsv.scipro.notifications.dataobject.NotificationSource; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; +import se.su.dsv.scipro.test.StreamingUpload; + public class FinalThesisServiceImplTest extends IntegrationTest { public static final String TEXT_PLAIN = "text/plain"; @Inject private FinalThesisServiceImpl finalThesisService; + @Inject private FileService fileService; @@ -46,9 +45,18 @@ public class FinalThesisServiceImplTest extends IntegrationTest { @BeforeEach public void setUp() throws Exception { ProjectType bachelor = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); uploader = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); - project = save(Project.builder().title("Some title").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + project = save( + Project.builder() + .title("Some title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); source = new NotificationSource(); name = "name"; contentType = TEXT_PLAIN; @@ -86,7 +94,10 @@ public class FinalThesisServiceImplTest extends IntegrationTest { uploadThesis(); FinalThesis finalThesis = uploadThesis(); - assertEquals(finalThesis.getDocument().getFileDescription(), finalThesisService.getFinalThesisFileDescription(project)); + assertEquals( + finalThesis.getDocument().getFileDescription(), + finalThesisService.getFinalThesisFileDescription(project) + ); } @Test @@ -159,8 +170,7 @@ public class FinalThesisServiceImplTest extends IntegrationTest { @Test public void get_reject_date_throws_exception() { - assertThrows(RuntimeException.class, () -> - finalThesisService.getRejectedDate(project)); + assertThrows(RuntimeException.class, () -> finalThesisService.getRejectedDate(project)); } @Test diff --git a/core/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorkerTest.java b/core/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorkerTest.java index 881fc72109..a99d60caf8 100644 --- a/core/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorkerTest.java +++ b/core/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingReminderWorkerTest.java @@ -1,10 +1,15 @@ package se.su.dsv.scipro.firstmeeting; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.when; + import java.time.Clock; import java.time.LocalDate; import java.time.Month; import java.util.List; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,48 +27,58 @@ import se.su.dsv.scipro.match.Match; import se.su.dsv.scipro.misc.DaysService; import se.su.dsv.scipro.system.User; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) -public class FirstMeetingReminderWorkerTest{ +public class FirstMeetingReminderWorkerTest { + @Mock private IdeaService ideaService; + @Mock private DaysService daysService; + @Mock private MailEventService mailEventService; + @Mock private GeneralSystemSettingsService generalSystemSettingsService; + @Mock private Clock clock; - + private FirstMeetingReminderWorker worker; @BeforeEach public void setUp() throws Exception { - worker = new FirstMeetingReminderWorker(ideaService, daysService, mailEventService, generalSystemSettingsService, clock); + worker = new FirstMeetingReminderWorker( + ideaService, + daysService, + mailEventService, + generalSystemSettingsService, + clock + ); } - @Test public void should_remind_if_is_same_date() { + @Test + public void should_remind_if_is_same_date() { LocalDate today = LocalDate.now(); Idea idea = newIdea(today); assertTrue(worker.needRemindingToday(idea, today)); } - @Test public void should_not_remind_if_is_different_date() { + @Test + public void should_not_remind_if_is_different_date() { LocalDate date = LocalDate.of(2020, Month.JANUARY, 12); Idea idea = newIdea(date); assertFalse(worker.needRemindingToday(idea, LocalDate.of(2020, Month.JANUARY, 13))); } - @Test public void reminder_should_include_title_of_every_idea() { - when(daysService.workDaysAhead(ArgumentMatchers.any(), anyInt())).then(AdditionalAnswers.returnsFirstArg()); + @Test + public void reminder_should_include_title_of_every_idea() { + when(daysService.workDaysAhead(ArgumentMatchers.any(), anyInt())).then( + AdditionalAnswers.returnsFirstArg() + ); Idea idea = newIdea(LocalDate.now()); @@ -71,8 +86,11 @@ public class FirstMeetingReminderWorkerTest{ assertThat(reminder.getMessageBody(), containsString(idea.getTitle())); } - @Test public void generated_reminder_should_be_sent_to_the_supervisor() { - when(daysService.workDaysAhead(ArgumentMatchers.any(), anyInt())).then(AdditionalAnswers.returnsFirstArg()); + @Test + public void generated_reminder_should_be_sent_to_the_supervisor() { + when(daysService.workDaysAhead(ArgumentMatchers.any(), anyInt())).then( + AdditionalAnswers.returnsFirstArg() + ); Idea idea = newIdea(LocalDate.now()); User supervisor = idea.getMatch().getSupervisor(); @@ -108,4 +126,4 @@ public class FirstMeetingReminderWorkerTest{ supervisorMatch.setIdea(idea); return supervisorMatch; } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/forum/BasicForumServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/forum/BasicForumServiceImplTest.java index 339b24080e..de6288d6f4 100644 --- a/core/src/test/java/se/su/dsv/scipro/forum/BasicForumServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/forum/BasicForumServiceImplTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.forum; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.AdditionalAnswers; @@ -15,25 +22,21 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; -import java.util.Collections; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class BasicForumServiceImplTest { @Mock private AbstractThreadRepository threadRepository; + @Mock private ForumPostReadStateRepository readStateRepository; + @Mock private ForumPostRepository postRepository; + @Mock private EventBus eventBus; + @InjectMocks private BasicForumServiceImpl basicForumService; @@ -190,4 +193,4 @@ public class BasicForumServiceImplTest { verify(eventBus, never()).post(isA(ForumPostReadEvent.class)); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/forum/ForumModuleTest.java b/core/src/test/java/se/su/dsv/scipro/forum/ForumModuleTest.java index 90cc242e77..88888ea92c 100644 --- a/core/src/test/java/se/su/dsv/scipro/forum/ForumModuleTest.java +++ b/core/src/test/java/se/su/dsv/scipro/forum/ForumModuleTest.java @@ -10,12 +10,14 @@ import se.su.dsv.scipro.test.SpringTest; @ExtendWith(MockitoExtension.class) public abstract class ForumModuleTest extends SpringTest { + // TODO: Work towards removing these dependencies. @Mock private DateService dateService; + @Mock private NotificationController notificationController; + @Mock private NotificationService notificationService; - } diff --git a/core/src/test/java/se/su/dsv/scipro/forum/GroupForumServiceTest.java b/core/src/test/java/se/su/dsv/scipro/forum/GroupForumServiceTest.java index 5c6caea2ef..b6b7f62d05 100644 --- a/core/src/test/java/se/su/dsv/scipro/forum/GroupForumServiceTest.java +++ b/core/src/test/java/se/su/dsv/scipro/forum/GroupForumServiceTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.forum; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import jakarta.inject.Inject; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.forum.dataobjects.ForumPost; @@ -8,13 +13,8 @@ import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Collections; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - public class GroupForumServiceTest extends ForumModuleTest { + @Inject private GroupForumService groupForumService; @@ -35,7 +35,13 @@ public class GroupForumServiceTest extends ForumModuleTest { public void create_thread() { final String subject = "Subject"; final String content = "Content"; - final GroupThread groupThread = groupForumService.createThread(group, groupOwner, subject, content, Collections.emptySet()); + final GroupThread groupThread = groupForumService.createThread( + group, + groupOwner, + subject, + content, + Collections.emptySet() + ); assertThat(groupThread.getGroup(), is(group)); ForumThread forumThread = groupThread.getForumThread(); @@ -45,7 +51,13 @@ public class GroupForumServiceTest extends ForumModuleTest { @Test public void reply() { - final GroupThread groupThread = groupForumService.createThread(group, groupOwner, "Subject", "Content", Collections.emptySet()); + final GroupThread groupThread = groupForumService.createThread( + group, + groupOwner, + "Subject", + "Content", + Collections.emptySet() + ); final String content = "Content"; final ForumPost reply = groupForumService.createReply(groupThread, groupOwner, content, Collections.emptySet()); @@ -57,8 +69,14 @@ public class GroupForumServiceTest extends ForumModuleTest { @Test public void find_one() { - final GroupThread groupThread = groupForumService.createThread(group, groupOwner, "Subject", "Content", Collections.emptySet()); + final GroupThread groupThread = groupForumService.createThread( + group, + groupOwner, + "Subject", + "Content", + Collections.emptySet() + ); assertThat(groupForumService.findOne(groupThread.getId()), is(groupThread)); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/forum/ProjectForumServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/forum/ProjectForumServiceImplTest.java index c25abbd10f..3f6a99dba8 100644 --- a/core/src/test/java/se/su/dsv/scipro/forum/ProjectForumServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/forum/ProjectForumServiceImplTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.forum; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.file.FileReference; @@ -12,20 +21,11 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.StreamingUpload; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ProjectForumServiceImplTest extends ForumModuleTest { public static final String SUBJECT = "Subject"; public static final String CONTENT = "Content"; + @Inject ProjectForumService service; @@ -38,8 +38,15 @@ public class ProjectForumServiceImplTest extends ForumModuleTest { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); projectType.addModule(ProjectModule.FORUM); save(projectType); - supervisor = save(User.builder().firstName("Bob").lastName("The Builder").emailAddress("bob@example.com").build()); - project = Project.builder().title("Some title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + supervisor = save( + User.builder().firstName("Bob").lastName("The Builder").emailAddress("bob@example.com").build() + ); + project = Project.builder() + .title("Some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); save(project); author = User.builder().firstName("Stina").lastName("Student").emailAddress("stina@example.com").build(); save(author); @@ -58,7 +65,13 @@ public class ProjectForumServiceImplTest extends ForumModuleTest { final String file = "attachment.txt"; try (var is = ProjectForumServiceImplTest.class.getResourceAsStream(file)) { final StreamingUpload upload = new StreamingUpload(file, "text/plain", author, 2, is); - final ProjectThread thread = service.createThread(project, author, SUBJECT, CONTENT, Set.of(Attachment.newUpload(upload))); + final ProjectThread thread = service.createThread( + project, + author, + SUBJECT, + CONTENT, + Set.of(Attachment.newUpload(upload)) + ); assertNewForumThread(thread, project, author, SUBJECT, CONTENT, file); } @@ -69,7 +82,6 @@ public class ProjectForumServiceImplTest extends ForumModuleTest { final ProjectThread thread = service.createThread(project, author, "subject", "content", Set.of()); final ForumPost reply = service.createReply(thread, author, "reply", Set.of()); - List servicePage = service.getPosts(thread); assertThat(servicePage, hasItem(reply)); @@ -99,7 +111,13 @@ public class ProjectForumServiceImplTest extends ForumModuleTest { } private void assertNewForumThread( - ProjectThread thread, Project project, User user, String subject, String content, String attachmentFileName) { + ProjectThread thread, + Project project, + User user, + String subject, + String content, + String attachmentFileName + ) { assertEquals(project, thread.getProject(), "Thread created for the wrong project"); assertEquals(user, thread.getForumThread().getCreatedBy(), "Thread created by wrong user"); assertEquals(subject, thread.getForumThread().getSubject(), "Thread created with wrong subject"); diff --git a/core/src/test/java/se/su/dsv/scipro/forum/notifications/ForumNotificationsTest.java b/core/src/test/java/se/su/dsv/scipro/forum/notifications/ForumNotificationsTest.java index a30b7f8109..1cd5ca3d62 100644 --- a/core/src/test/java/se/su/dsv/scipro/forum/notifications/ForumNotificationsTest.java +++ b/core/src/test/java/se/su/dsv/scipro/forum/notifications/ForumNotificationsTest.java @@ -1,6 +1,15 @@ package se.su.dsv.scipro.forum.notifications; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.notifications.dataobject.ProjectForumEvent.Event.NEW_FORUM_POST; + import com.google.common.eventbus.EventBus; +import java.util.Collections; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -23,27 +32,21 @@ import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectForumEvent; import se.su.dsv.scipro.system.User; -import java.util.Collections; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.notifications.dataobject.ProjectForumEvent.Event.NEW_FORUM_POST; - @ExtendWith(MockitoExtension.class) public class ForumNotificationsTest { + @InjectMocks private ForumNotifications forumNotifications; @Mock private EventBus eventBus; + @Mock private NotificationController notificationController; + @Mock private ForumNotificationRepository forumNotificationRepository; + @Mock private NotificationService notificationService; @@ -72,7 +75,12 @@ public class ForumNotificationsTest { NewProjectForumReplyEvent forumReplyEvent = new NewProjectForumReplyEvent(projectThread, firstReply); forumNotifications.newProjectForumPost(forumReplyEvent); - verify(notificationController).notifyProjectForum(eq(NEW_FORUM_POST), any(NotificationSource.class), eq(projectThread.getProject()), any(User.class)); + verify(notificationController).notifyProjectForum( + eq(NEW_FORUM_POST), + any(NotificationSource.class), + eq(projectThread.getProject()), + any(User.class) + ); } @Test @@ -84,7 +92,12 @@ public class ForumNotificationsTest { NewGroupForumReplyEvent forumReplyEvent = new NewGroupForumReplyEvent(groupThread, secondReply); forumNotifications.newGroupForumPost(forumReplyEvent); - verify(notificationController).notifyGroup(eq(groupThread.getGroup()), eq(GroupEvent.Event.MESSAGE_THREAD_REPLY), any(NotificationSource.class), any(User.class)); + verify(notificationController).notifyGroup( + eq(groupThread.getGroup()), + eq(GroupEvent.Event.MESSAGE_THREAD_REPLY), + any(NotificationSource.class), + any(User.class) + ); } @Test @@ -93,8 +106,14 @@ public class ForumNotificationsTest { Notification notification = new Notification(); notification.setNotificationEvent(projectForumEvent); - when(notificationController.notifyProjectForum(any(ProjectForumEvent.Event.class), any(NotificationSource.class), any(), any(User.class))) - .thenReturn(Collections.singleton(notification)); + when( + notificationController.notifyProjectForum( + any(ProjectForumEvent.Event.class), + any(NotificationSource.class), + any(), + any(User.class) + ) + ).thenReturn(Collections.singleton(notification)); ProjectThread projectThread = new ProjectThread(); projectThread.setForumThread(forumThread); @@ -116,11 +135,12 @@ public class ForumNotificationsTest { Notification notification = new Notification(); notification.setNotificationEvent(projectForumEvent); - when(forumNotificationRepository.findByForumPost(firstReply)) - .thenReturn(Optional.of(new ForumNotification(firstReply, projectForumEvent))); + when(forumNotificationRepository.findByForumPost(firstReply)).thenReturn( + Optional.of(new ForumNotification(firstReply, projectForumEvent)) + ); forumNotifications.forumPostRead(new ForumPostReadEvent(firstReply, user)); verify(notificationService).setRead(user, projectForumEvent, true); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/group/GroupServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/group/GroupServiceImplTest.java index 4a3e6dc33c..31114269b9 100644 --- a/core/src/test/java/se/su/dsv/scipro/group/GroupServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/group/GroupServiceImplTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.group; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -8,21 +18,11 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Collections; -import java.util.HashSet; - -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class GroupServiceImplTest extends IntegrationTest { @Inject private GroupServiceImpl groupService; + private User author; private User creator; private User reviewer; @@ -37,8 +37,17 @@ public class GroupServiceImplTest extends IntegrationTest { reviewer = saveUser("reviewer", "test", "reviewer@example.com"); cosupervisor = saveUser("cosupervisor", "test", "reviewer@example.com"); projectType = save(new ProjectType(DegreeType.BACHELOR, "b", "b")); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - Project project = save(Project.builder().title("title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + Project project = save( + Project.builder() + .title("title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); project.addProjectParticipant(author); project.addReviewer(reviewer); project.addCoSupervisor(cosupervisor); @@ -108,8 +117,17 @@ public class GroupServiceImplTest extends IntegrationTest { Group another = new Group(); another.setTitle("hi"); another.setUser(creator); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - Project anotherProject = save(Project.builder().title("another").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + Project anotherProject = save( + Project.builder() + .title("another") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); another.setProjects(new HashSet<>(Collections.singletonList(anotherProject))); save(another); GroupService.Filter filter = new GroupService.Filter(); diff --git a/core/src/test/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandlerTest.java b/core/src/test/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandlerTest.java index 27df270d57..cd942ed014 100644 --- a/core/src/test/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandlerTest.java +++ b/core/src/test/java/se/su/dsv/scipro/integration/activityfinalseminar/FinalSeminarActivityHandlerTest.java @@ -1,6 +1,12 @@ package se.su.dsv.scipro.integration.activityfinalseminar; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import java.util.Date; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -14,24 +20,20 @@ import se.su.dsv.scipro.finalseminar.FinalSeminarCreatedEvent; import se.su.dsv.scipro.finalseminar.FinalSeminarDeletedEvent; import se.su.dsv.scipro.project.Project; -import java.util.Date; -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class FinalSeminarActivityHandlerTest { @Mock private ActivityPlanFacade activityPlanFacade; + @Mock private ActivityFinalSeminarRepository activityFinalSeminarRepository; + @Mock private EventBus eventBus; + @InjectMocks - private FinalSeminarActivityHandler finalSeminarActivityHandler; + private FinalSeminarActivityHandler finalSeminarActivityHandler; @Test public void on_create() { @@ -40,8 +42,7 @@ public class FinalSeminarActivityHandlerTest { finalSeminar.setStartDate(new Date()); FinalSeminarCreatedEvent finalSeminarCreatedEvent = new FinalSeminarCreatedEvent(finalSeminar); - when(activityFinalSeminarRepository.findByFinalSeminar(finalSeminar)) - .thenReturn(Optional.empty()); + when(activityFinalSeminarRepository.findByFinalSeminar(finalSeminar)).thenReturn(Optional.empty()); finalSeminarActivityHandler.finalSeminarCreated(finalSeminarCreatedEvent); @@ -80,7 +81,8 @@ public class FinalSeminarActivityHandlerTest { private void mockExistingActivity(final FinalSeminar finalSeminar) { Activity activity = new Activity(); ActivityFinalSeminar finalSeminarActivity = new ActivityFinalSeminar(activity, finalSeminar); - when(activityFinalSeminarRepository.findByFinalSeminar(finalSeminar)) - .thenReturn(Optional.of(finalSeminarActivity)); + when(activityFinalSeminarRepository.findByFinalSeminar(finalSeminar)).thenReturn( + Optional.of(finalSeminarActivity) + ); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForumTest.java b/core/src/test/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForumTest.java index 4b45bf57e8..effc0f54cd 100644 --- a/core/src/test/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForumTest.java +++ b/core/src/test/java/se/su/dsv/scipro/integration/activityforum/PostActivityUploadToForumTest.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.integration.activityforum; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -18,22 +23,21 @@ import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.*; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class PostActivityUploadToForumTest { + @Mock private ProjectForumService projectForumService; + @Mock private ActivityThreadRepository activityThreadRepository; + @Mock private EventBus eventBus; + @InjectMocks private PostActivityUploadToForum integration; + private Activity activity; private FileDescription fileDescription; private ProjectThread thread; @@ -58,7 +62,13 @@ public class PostActivityUploadToForumTest { public void when_uploading_the_first_file_to_an_activity_should_create_thread() { isFirstUpload(); fireEvent(); - verify(projectForumService).createThread(activity.getActivityPlan().getProject(), uploader, activity.getTitle(), activity.getDescription(), attachments); + verify(projectForumService).createThread( + activity.getActivityPlan().getProject(), + uploader, + activity.getTitle(), + activity.getDescription(), + attachments + ); } @Test @@ -70,8 +80,15 @@ public class PostActivityUploadToForumTest { @Test public void creates_connection_if_first_upload() { - when(projectForumService.createThread(activity.getActivityPlan().getProject(), uploader, activity.getTitle(), activity.getDescription(), attachments)) - .thenReturn(thread); + when( + projectForumService.createThread( + activity.getActivityPlan().getProject(), + uploader, + activity.getTitle(), + activity.getDescription(), + attachments + ) + ).thenReturn(thread); isFirstUpload(); fireEvent(); ArgumentCaptor captor = ArgumentCaptor.forClass(ActivityThread.class); @@ -99,4 +116,4 @@ public class PostActivityUploadToForumTest { private void fireEvent() { integration.postActivityUploadToForum(new ActivityFileUploadedEvent(activity, fileDescription)); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/mail/FailureTest.java b/core/src/test/java/se/su/dsv/scipro/mail/FailureTest.java index 02a919b689..12dc1415b2 100644 --- a/core/src/test/java/se/su/dsv/scipro/mail/FailureTest.java +++ b/core/src/test/java/se/su/dsv/scipro/mail/FailureTest.java @@ -1,9 +1,16 @@ package se.su.dsv.scipro.mail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import jakarta.mail.Address; import jakarta.mail.SendFailedException; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeMessage; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -12,22 +19,18 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; -import java.util.*; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.contains; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class FailureTest { + @Mock private Logger logger; + @Mock private MimeMessage message; + @Mock private SendFailedException exception; + @InjectMocks private Failure failure; @@ -36,11 +39,11 @@ public class FailureTest { final InternetAddress delivered = new InternetAddress("bill.gates@microsoft.com"); final InternetAddress failed = new InternetAddress("steve.jobs@apple.com"); final InternetAddress invalid = new InternetAddress("mangledemail@e"); - final Address[] recipients = new Address[]{delivered, failed, invalid}; + final Address[] recipients = new Address[] { delivered, failed, invalid }; when(message.getAllRecipients()).thenReturn(recipients); - when(exception.getInvalidAddresses()).thenReturn(new Address[]{invalid}); - when(exception.getValidSentAddresses()).thenReturn(new Address[]{delivered}); - when(exception.getValidUnsentAddresses()).thenReturn(new Address[]{failed}); + when(exception.getInvalidAddresses()).thenReturn(new Address[] { invalid }); + when(exception.getValidSentAddresses()).thenReturn(new Address[] { delivered }); + when(exception.getValidUnsentAddresses()).thenReturn(new Address[] { failed }); } @Test @@ -75,4 +78,4 @@ public class FailureTest { verify(logger, never()).error(anyString()); verify(logger, never()).warn(anyString()); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/mail/MailEventWorkerTest.java b/core/src/test/java/se/su/dsv/scipro/mail/MailEventWorkerTest.java index bf2bd1df7f..638cda54c3 100644 --- a/core/src/test/java/se/su/dsv/scipro/mail/MailEventWorkerTest.java +++ b/core/src/test/java/se/su/dsv/scipro/mail/MailEventWorkerTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.mail; +import static org.hamcrest.CoreMatchers.everyItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import jakarta.mail.MessagingException; +import java.util.Arrays; +import java.util.Set; +import java.util.TreeSet; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -17,16 +26,6 @@ import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import jakarta.mail.MessagingException; -import java.util.Arrays; -import java.util.Set; -import java.util.TreeSet; - -import static org.hamcrest.CoreMatchers.everyItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class MailEventWorkerTest { @@ -49,14 +48,21 @@ public class MailEventWorkerTest { public void callSendMailUsersOnlyNoFromName() throws Exception { setUpMailEventWithUsersOnlyNoFromName(); worker.doWork(); - verify(mailer).mail(eq(DEFAULT_FROM_NAME), eq(DEFAULT_FROM_EMAIL), eq(RECIPIENTS_MAILS), eq(SUBJECT), eq(MESSAGE_BODY), any()); + verify(mailer).mail( + eq(DEFAULT_FROM_NAME), + eq(DEFAULT_FROM_EMAIL), + eq(RECIPIENTS_MAILS), + eq(SUBJECT), + eq(MESSAGE_BODY), + any() + ); } @Test public void callSendMailUsersAndNonUser() throws Exception { setUpMailEventWithUsersAndNonUser(); worker.doWork(); - String[] mails = {RECIPIENTS_MAILS[0], NON_USER_RECIPIENTS.iterator().next()}; + String[] mails = { RECIPIENTS_MAILS[0], NON_USER_RECIPIENTS.iterator().next() }; verify(mailer).mail(anyString(), anyString(), eq(mails), anyString(), anyString(), any()); } @@ -127,7 +133,9 @@ public class MailEventWorkerTest { } private void mockMailResult(final MailResult result) throws MessagingException { - when(mailer.mail(anyString(), anyString(), any(String[].class), anyString(), anyString(), any())).thenReturn(result); + when(mailer.mail(anyString(), anyString(), any(String[].class), anyString(), anyString(), any())).thenReturn( + result + ); } private void setUpMailEventWithUsersAndNonUser() throws Exception { @@ -156,20 +164,24 @@ public class MailEventWorkerTest { private void mockMailEventService(final MailEvent... mailEvents) throws Exception { when(mailEventService.findUnsent()).thenReturn(Arrays.asList(mailEvents)); - when(mailEventService.findOne(anyLong())).thenAnswer(new Answer() { - - @Override - public MailEvent answer(InvocationOnMock invocation) { - Long id = (Long) invocation.getArguments()[0]; - for(MailEvent event : mailEvents) { - if(event.getId().equals(id)) { - return event; + when(mailEventService.findOne(anyLong())).thenAnswer( + new Answer() { + @Override + public MailEvent answer(InvocationOnMock invocation) { + Long id = (Long) invocation.getArguments()[0]; + for (MailEvent event : mailEvents) { + if (event.getId().equals(id)) { + return event; + } } + return null; } - return null; } - }); + } + ); MailResult successfulResult = createSuccessfulResult("123.abcdefg.987@mail.com"); - lenient().when(mailer.mail(anyString(), anyString(), any(String[].class), anyString(), anyString(), any())).thenReturn(successfulResult); + lenient() + .when(mailer.mail(anyString(), anyString(), any(String[].class), anyString(), anyString(), any())) + .thenReturn(successfulResult); } private MailEvent createMailEventUsersOnlyNoFromName() { @@ -185,6 +197,7 @@ public class MailEventWorkerTest { } class TestMailEventWorker extends MailEventWorker { + private int commits = 0; public int begins = 0; @@ -205,10 +218,7 @@ public class MailEventWorkerTest { private static final Long MAIL_EVENT_ID1 = 999L; private static final Long MAIL_EVENT_ID2 = 1337L; - private static final Long[] mailEventsId = { - MAIL_EVENT_ID1, - MAIL_EVENT_ID2 - }; + private static final Long[] mailEventsId = { MAIL_EVENT_ID1, MAIL_EVENT_ID2 }; private int eventIndex = 0; private static final String FROM_EMAIL = "fromEmail@example.com"; private static final String FROM_NAME = "From Name"; @@ -230,7 +240,7 @@ public class MailEventWorkerTest { add(RECIPIENT_1); } }; - private static final String[] RECIPIENTS_MAILS = {RECIPIENT_1.getEmailAddress()}; + private static final String[] RECIPIENTS_MAILS = { RECIPIENT_1.getEmailAddress() }; private static final User REPLY_USER_1 = new User() { { setFirstName("Reply Firstname"); @@ -254,12 +264,15 @@ public class MailEventWorkerTest { private static final String DEFAULT_FROM_EMAIL = "default@example.com"; private TestMailEventWorker worker; + @Mock private GeneralSystemSettingsService generalSystemSettingsService; + @Mock private Mailer mailer; + @Mock private MailEventService mailEventService; - private GeneralSystemSettings systemSettings; + private GeneralSystemSettings systemSettings; } diff --git a/core/src/test/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStartTest.java b/core/src/test/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStartTest.java index f0af59a1b6..dd547c0e26 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStartTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/AddActivityPlanOnProjectStartTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.time.LocalDate; +import java.util.Date; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -12,16 +19,9 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.Date; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) public class AddActivityPlanOnProjectStartTest { + @Mock private ActivityPlanFacade activityPlanFacade; @@ -67,7 +67,11 @@ public class AddActivityPlanOnProjectStartTest { handler.projectStarted(tuple._2()); - verify(activityPlanFacade, never()).addActivitiesFromTemplate(eq(tuple._1()), any(ActivityPlanTemplate.class), any(Date.class)); + verify(activityPlanFacade, never()).addActivitiesFromTemplate( + eq(tuple._1()), + any(ActivityPlanTemplate.class), + any(Date.class) + ); } private Tuple2 prepareEventWithoutTemplate(final ProjectType projectType) { @@ -78,10 +82,16 @@ public class AddActivityPlanOnProjectStartTest { return prepareEvent(projectType, template); } - private Tuple2 prepareEvent(final ProjectType projectType, final ActivityPlanTemplate activityPlanTemplate) { + private Tuple2 prepareEvent( + final ProjectType projectType, + final ActivityPlanTemplate activityPlanTemplate + ) { Project project = Project.builder().title("Title").projectType(projectType).startDate(LocalDate.now()).build(); ApplicationPeriod applicationPeriod = new ApplicationPeriod(); - ApplicationPeriodProjectType applicationPeriodProjectType = new ApplicationPeriodProjectType(applicationPeriod, projectType); + ApplicationPeriodProjectType applicationPeriodProjectType = new ApplicationPeriodProjectType( + applicationPeriod, + projectType + ); applicationPeriodProjectType.setActivityPlanTemplate(activityPlanTemplate); applicationPeriod.getApplicationPeriodProjectTypes().add(applicationPeriodProjectType); Idea idea = new Idea(); @@ -92,6 +102,7 @@ public class AddActivityPlanOnProjectStartTest { } private static class Tuple2 { + private final A a; private final B b; @@ -108,4 +119,4 @@ public class AddActivityPlanOnProjectStartTest { return b; } } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImplTest.java index de318612eb..d825183b5b 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/ApplicationPeriodServiceImplTest.java @@ -1,11 +1,6 @@ package se.su.dsv.scipro.match; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; +import static org.junit.jupiter.api.Assertions.*; import jakarta.inject.Inject; import java.time.LocalDate; @@ -13,13 +8,18 @@ import java.time.LocalDateTime; import java.util.Collections; import java.util.HashSet; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; public class ApplicationPeriodServiceImplTest extends IntegrationTest { @Inject private ApplicationPeriodServiceImpl applicationPeriodService; + private ProjectType projectType; private User student; @@ -51,7 +51,11 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { List actualList = applicationPeriodService.getCurrentStudentPeriods(student); assertTrue(actualList.contains(new OpenPeriod(current, Collections.emptyList()))); - assertTrue(actualList.contains(new ExemptedPeriod(exempted, List.of(ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA)))); + assertTrue( + actualList.contains( + new ExemptedPeriod(exempted, List.of(ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA)) + ) + ); } @Test @@ -147,7 +151,9 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { @Test public void hasExemptionButStudentHasNoExemption() { ApplicationPeriod applicationPeriod = createPeriod(-10, -5); - final User newStudent = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + final User newStudent = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); createExemption(newStudent, applicationPeriod, LocalDate.now()); assertFalse(applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption(applicationPeriod, student)); @@ -164,12 +170,16 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { @Test public void hasOpenExemption() { ApplicationPeriod applicationPeriod = createPeriod(-2, -1); - createExemptionForExemptionType(student, applicationPeriod, LocalDate.now().plusDays(3), ApplicationPeriodExemption.Type.SELECT_SUPERVISOR_IDEA); + createExemptionForExemptionType( + student, + applicationPeriod, + LocalDate.now().plusDays(3), + ApplicationPeriodExemption.Type.SELECT_SUPERVISOR_IDEA + ); assertTrue(applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption(applicationPeriod, student)); } - @Test public void hasNoExemptions() { ApplicationPeriod applicationPeriod = createPeriod(-1, 1); @@ -180,12 +190,16 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { @Test public void hasExemption() { ApplicationPeriod applicationPeriod = createPeriod(-1, 1); - createExemptionForExemptionType(student, applicationPeriod, LocalDate.now().plusDays(1), ApplicationPeriodExemption.Type.NUMBER_OF_AUTHORS); + createExemptionForExemptionType( + student, + applicationPeriod, + LocalDate.now().plusDays(1), + ApplicationPeriodExemption.Type.NUMBER_OF_AUTHORS + ); assertTrue(applicationPeriodService.hasIdeaSizeExemption(student, applicationPeriod)); } - @Test public void get_previous_periods_returns_correct_number() { int size = 2; @@ -233,7 +247,12 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { public void exemption_without_date() { final ApplicationPeriod applicationPeriod = createPeriod(-5, -1); createExemptionForExemptionType(student, applicationPeriod, null, ApplicationPeriodExemption.Type.PROJECT_TYPE); - createExemptionForExemptionType(student, applicationPeriod, LocalDate.now().plusDays(1), ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA); + createExemptionForExemptionType( + student, + applicationPeriod, + LocalDate.now().plusDays(1), + ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA + ); final List currentStudentPeriods = applicationPeriodService.getCurrentStudentPeriods(student); final StudentPeriod studentPeriod = currentStudentPeriods.get(0); assertTrue(studentPeriod instanceof ExemptedPeriod); @@ -251,7 +270,10 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { save(student); createExemptionForExemptionType(student, applicationPeriod, null, ApplicationPeriodExemption.Type.PROJECT_TYPE); - final List typesForStudent = applicationPeriodService.getTypesForStudent(applicationPeriod, student); + final List typesForStudent = applicationPeriodService.getTypesForStudent( + applicationPeriod, + student + ); assertTrue(typesForStudent.contains(master)); } @@ -274,10 +296,20 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { } private void createExemption(User student, ApplicationPeriod applicationPeriod, LocalDate newDate) { - createExemptionForExemptionType(student, applicationPeriod, newDate, ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA); + createExemptionForExemptionType( + student, + applicationPeriod, + newDate, + ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA + ); } - private void createExemptionForExemptionType(User student, ApplicationPeriod applicationPeriod, LocalDate until, final ApplicationPeriodExemption.Type type) { + private void createExemptionForExemptionType( + User student, + ApplicationPeriod applicationPeriod, + LocalDate until, + final ApplicationPeriodExemption.Type type + ) { ApplicationPeriodExemption applicationPeriodExemption = new ApplicationPeriodExemption(); applicationPeriodExemption.setUser(student); applicationPeriodExemption.setApplicationPeriod(applicationPeriod); @@ -285,7 +317,9 @@ public class ApplicationPeriodServiceImplTest extends IntegrationTest { applicationPeriodExemption.setGrantedOn(LocalDateTime.now()); applicationPeriodExemption.setGrantedBy(student); applicationPeriodExemption.setType(type); - applicationPeriod.setApplicationPeriodExemptions(new HashSet<>(Collections.singletonList(applicationPeriodExemption))); + applicationPeriod.setApplicationPeriodExemptions( + new HashSet<>(Collections.singletonList(applicationPeriodExemption)) + ); save(applicationPeriodExemption); } } diff --git a/core/src/test/java/se/su/dsv/scipro/match/IdeaFacadeTest.java b/core/src/test/java/se/su/dsv/scipro/match/IdeaFacadeTest.java index 45d747b6b8..c3ea46732f 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/IdeaFacadeTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/IdeaFacadeTest.java @@ -1,24 +1,23 @@ package se.su.dsv.scipro.match; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class IdeaFacadeTest { @@ -27,10 +26,13 @@ public class IdeaFacadeTest { @Mock private IdeaService ideaService; + @Mock private ApplicationPeriodService applicationPeriodService; + @InjectMocks private IdeaFacade ideaFacade; + private ApplicationPeriod applicationPeriod; private IdeaService.Filter params; private Idea idea; @@ -50,7 +52,9 @@ public class IdeaFacadeTest { idea.setMatch(match); ideas = Collections.singletonList(idea); user = new UserBuilder().create(); - when(applicationPeriodService.getTypesForStudent(applicationPeriod, user)).thenReturn(Collections.singletonList(idea.getProjectType())); + when(applicationPeriodService.getTypesForStudent(applicationPeriod, user)).thenReturn( + Collections.singletonList(idea.getProjectType()) + ); } @Test @@ -58,7 +62,9 @@ public class IdeaFacadeTest { Pageable pageRequest = new PageRequest(0, 1); when(ideaService.findAll(params)).thenReturn(ideas); - when(targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType())).thenReturn(true); + when( + targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType()) + ).thenReturn(true); when(ideaService.findAllInList(ideas, pageRequest)).thenReturn(ideas); assertEquals(ideas, ideaFacade.findIdeasPossibleToMatch(applicationPeriod, user, params, pageRequest)); @@ -69,7 +75,9 @@ public class IdeaFacadeTest { int expectedInt = 1; when(ideaService.findAll(params)).thenReturn(ideas); - when(targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType())).thenReturn(true); + when( + targetService.hasTargetsLeft(applicationPeriod, idea.getMatch().getSupervisor(), idea.getProjectType()) + ).thenReturn(true); assertEquals(expectedInt, ideaFacade.countIdeasPossibleToMatch(applicationPeriod, user, params)); } diff --git a/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplIntegrationTest.java index 1b334f8802..57b8cca178 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplIntegrationTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.match; +import static com.google.common.collect.Iterators.size; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; + import com.google.common.collect.Sets; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Set; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -8,21 +15,14 @@ import org.hamcrest.core.Every; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Set; - -import static com.google.common.collect.Iterators.size; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; - public class IdeaServiceImplIntegrationTest extends IntegrationTest { public static final PageRequest ALL = new PageRequest(0, Integer.MAX_VALUE); + @Inject private IdeaService ideaService; @@ -118,7 +118,13 @@ public class IdeaServiceImplIntegrationTest extends IntegrationTest { }; } - private Idea setUpIdea(Idea.Status status, User author, ResearchArea researchArea, Set languages, ApplicationPeriod applicationPeriod) { + private Idea setUpIdea( + Idea.Status status, + User author, + ResearchArea researchArea, + Set languages, + ApplicationPeriod applicationPeriod + ) { Idea idea = createIdea(author, researchArea, languages); Match match = createMatch(status, randomUser, idea); idea.setMatch(match); @@ -177,7 +183,6 @@ public class IdeaServiceImplIntegrationTest extends IntegrationTest { private User createUser() { User user = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); return save(user); - } private Language createLanguage() { diff --git a/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplTest.java index c46e2bdc48..6365ba546a 100755 --- a/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/IdeaServiceImplTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.match; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.match.IdeaServiceImpl.*; + +import jakarta.persistence.EntityManager; +import java.time.*; +import java.util.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,32 +32,30 @@ import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.Pair; -import jakarta.persistence.EntityManager; -import java.time.*; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.match.IdeaServiceImpl.*; - @ExtendWith(MockitoExtension.class) public class IdeaServiceImplTest { @Mock private NotificationController notificationController; + @Mock private ApplicationPeriodService applicationPeriodService; + @Mock private GeneralSystemSettingsService generalSystemSettingsService; + @Mock private ProjectService projectService; + @Mock private FirstMeetingRepository firstMeetingRepository; + @Mock(answer = Answers.RETURNS_MOCKS) private EntityManager em; + @Mock TargetRepository targetRepository; + @Mock IdeaRepository ideaRepository; @@ -67,7 +73,17 @@ public class IdeaServiceImplTest { public void setUp() { final ZoneId sweden = ZoneId.of("Europe/Stockholm"); clock = Clock.fixed(Instant.from(LocalDateTime.now().atZone(sweden)), sweden); - ideaService = new IdeaServiceImpl(new InstanceProvider<>(em), applicationPeriodService, firstMeetingRepository, notificationController, projectService, generalSystemSettingsService, targetRepository, ideaRepository, clock); + ideaService = new IdeaServiceImpl( + new InstanceProvider<>(em), + applicationPeriodService, + firstMeetingRepository, + notificationController, + projectService, + generalSystemSettingsService, + targetRepository, + ideaRepository, + clock + ); student = new UserBuilder().create(); coAuthor = new UserBuilder().create(); @@ -92,7 +108,11 @@ public class IdeaServiceImplTest { ideaService.saveStudentIdea(idea, creator, null, Collections.singleton(coAuthor), new ArrayList<>(), true); // then - Mockito.verify(notificationController).notifyIdea(eq(idea), eq(IdeaEvent.Event.ADDED_AS_PARTNER), isA(NotificationSource.class)); + Mockito.verify(notificationController).notifyIdea( + eq(idea), + eq(IdeaEvent.Event.ADDED_AS_PARTNER), + isA(NotificationSource.class) + ); } @Test @@ -113,7 +133,11 @@ public class IdeaServiceImplTest { ideaService.saveStudentIdea(idea, creator, null, Collections.singleton(coAuthor), new ArrayList<>(), false); // then - Mockito.verify(notificationController, Mockito.times(0)).notifyIdea(isA(Idea.class), isA(IdeaEvent.Event.class), isA(NotificationSource.class)); + Mockito.verify(notificationController, Mockito.times(0)).notifyIdea( + isA(Idea.class), + isA(IdeaEvent.Event.class), + isA(NotificationSource.class) + ); } @Test @@ -130,7 +154,11 @@ public class IdeaServiceImplTest { ideaService.saveStudentIdea(idea, creator, null, Collections.singleton(coAuthor), new ArrayList<>(), false); // then - Mockito.verify(notificationController).notifyIdea(eq(idea), eq(IdeaEvent.Event.ADDED_AS_PARTNER), isA(NotificationSource.class)); + Mockito.verify(notificationController).notifyIdea( + eq(idea), + eq(IdeaEvent.Event.ADDED_AS_PARTNER), + isA(NotificationSource.class) + ); } @Test @@ -175,7 +203,11 @@ public class IdeaServiceImplTest { when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(new GeneralSystemSettings()); Idea idea = createBachelorIdea(Idea.Status.MATCHED); - assertPair(false, NO_LONGER_AVAILABLE_ERROR, ideaService.validateStudentAcceptance(idea, student, coAuthor, applicationPeriod)); + assertPair( + false, + NO_LONGER_AVAILABLE_ERROR, + ideaService.validateStudentAcceptance(idea, student, coAuthor, applicationPeriod) + ); } @Test @@ -185,8 +217,11 @@ public class IdeaServiceImplTest { when(applicationPeriodService.hasIdeaSizeExemption(student, applicationPeriod)).thenReturn(false); - assertPair(false, BACHELOR_NEED_PARTNER_ERROR, ideaService.validateStudentAcceptance(idea, student, null, applicationPeriod)); - + assertPair( + false, + BACHELOR_NEED_PARTNER_ERROR, + ideaService.validateStudentAcceptance(idea, student, null, applicationPeriod) + ); } @Test @@ -194,21 +229,25 @@ public class IdeaServiceImplTest { when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(new GeneralSystemSettings()); Idea idea = createBachelorIdea(Idea.Status.UNMATCHED); - assertPair(false, ADD_SELF_AS_PARTNER_ERROR, ideaService.validateStudentAcceptance(idea, student, student, applicationPeriod)); + assertPair( + false, + ADD_SELF_AS_PARTNER_ERROR, + ideaService.validateStudentAcceptance(idea, student, student, applicationPeriod) + ); } @Test public void validateStudentAcceptance() { when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(new GeneralSystemSettings()); Idea idea = createBachelorIdea(Idea.Status.UNMATCHED); - when(applicationPeriodService.getTypesForStudent(applicationPeriod, student)) - .thenReturn(List.of(bachelor)); + when(applicationPeriodService.getTypesForStudent(applicationPeriod, student)).thenReturn(List.of(bachelor)); Pair acceptance = ideaService.validateStudentAcceptance( - idea, - student, - coAuthor, - applicationPeriod); + idea, + student, + coAuthor, + applicationPeriod + ); assertTrue(acceptance.getHead()); } @@ -217,7 +256,11 @@ public class IdeaServiceImplTest { Idea idea = new Idea(); idea.setType(Idea.Type.SUPERVISOR); - assertPair(true, VALIDATION_PASSED, ideaService.validateAdminAddAuthors(idea, new TreeSet<>(new User.ByNameComparator()))); + assertPair( + true, + VALIDATION_PASSED, + ideaService.validateAdminAddAuthors(idea, new TreeSet<>(new User.ByNameComparator())) + ); } @Test @@ -225,7 +268,11 @@ public class IdeaServiceImplTest { Idea idea = new Idea(); idea.setType(Idea.Type.STUDENT); - assertPair(false, NO_AUTHORS_ERROR, ideaService.validateAdminAddAuthors(idea, new TreeSet<>(new User.ByNameComparator()))); + assertPair( + false, + NO_AUTHORS_ERROR, + ideaService.validateAdminAddAuthors(idea, new TreeSet<>(new User.ByNameComparator())) + ); } @Test @@ -245,7 +292,10 @@ public class IdeaServiceImplTest { public void saveSupervisorIdeaNewIdea() { Idea idea = new Idea(); - assertEquals(idea, ideaService.saveSupervisorIdea(idea, supervisor, Collections.singletonList(new Keyword()), true)); + assertEquals( + idea, + ideaService.saveSupervisorIdea(idea, supervisor, Collections.singletonList(new Keyword()), true) + ); } @Test @@ -255,7 +305,10 @@ public class IdeaServiceImplTest { match.setStatus(Idea.Status.UNMATCHED); idea.setMatch(match); - assertEquals(idea, ideaService.saveSupervisorIdea(idea, supervisor, Collections.singletonList(new Keyword()), false)); + assertEquals( + idea, + ideaService.saveSupervisorIdea(idea, supervisor, Collections.singletonList(new Keyword()), false) + ); } @Test @@ -264,11 +317,15 @@ public class IdeaServiceImplTest { idea.setMatch(new Match()); assertEquals(idea, ideaService.acceptIdea(idea, student, null, coAuthor, applicationPeriod)); - Mockito.verify(notificationController).notifyIdea(eq(idea), eq(IdeaEvent.Event.PARTNER_ACCEPT), any(NotificationSource.class)); + Mockito.verify(notificationController).notifyIdea( + eq(idea), + eq(IdeaEvent.Event.PARTNER_ACCEPT), + any(NotificationSource.class) + ); } @Test - public void savePartnerProgram(){ + public void savePartnerProgram() { Program program = new Program(); DomainObjects.injectId(program, 1L); User student = new UserBuilder().create(); @@ -279,7 +336,7 @@ public class IdeaServiceImplTest { idea = ideaService.savePartnerProgram(idea, student, program); - for (IdeaParticipation npi : idea.getIdeaParticipations()){ + for (IdeaParticipation npi : idea.getIdeaParticipations()) { Assertions.assertEquals(program, npi.getProgram()); } } @@ -303,7 +360,11 @@ public class IdeaServiceImplTest { when(applicationPeriodService.getCurrentPeriod(any(ProjectType.class))).thenReturn(applicationPeriod); SortedSet authors = new TreeSet<>(new User.ByNameComparator()); authors.add(student); - assertPair(false, "Selected number of authors is not allowed", ideaService.validateAdminAddAuthors(createBachelorIdea(Idea.Status.UNMATCHED), authors)); + assertPair( + false, + "Selected number of authors is not allowed", + ideaService.validateAdminAddAuthors(createBachelorIdea(Idea.Status.UNMATCHED), authors) + ); } @Test @@ -312,7 +373,11 @@ public class IdeaServiceImplTest { SortedSet authors = new TreeSet<>(new User.ByNameComparator()); authors.add(student); authors.add(coAuthor); - assertPair(false, "Selected number of authors is not allowed", ideaService.validateAdminAddAuthors(createMasterIdea(Idea.Status.UNMATCHED), authors)); + assertPair( + false, + "Selected number of authors is not allowed", + ideaService.validateAdminAddAuthors(createMasterIdea(Idea.Status.UNMATCHED), authors) + ); } @Test @@ -321,7 +386,11 @@ public class IdeaServiceImplTest { when(applicationPeriodService.hasIdeaSizeExemption(student, applicationPeriod)).thenReturn(true); SortedSet authors = new TreeSet<>(new User.ByNameComparator()); authors.add(student); - assertPair(true, VALIDATION_PASSED, ideaService.validateAdminAddAuthors(createBachelorIdea(Idea.Status.UNMATCHED), authors)); + assertPair( + true, + VALIDATION_PASSED, + ideaService.validateAdminAddAuthors(createBachelorIdea(Idea.Status.UNMATCHED), authors) + ); } @Test @@ -368,12 +437,16 @@ public class IdeaServiceImplTest { private void whenSupervisorHasTargetsLeft(final Idea idea) { final Target target = new Target(supervisor, idea.getApplicationPeriod(), idea.getProjectType()); target.setTarget(1); - when(targetRepository.getTarget(supervisor, idea.getApplicationPeriod(), idea.getProjectType())).thenReturn(target); + when(targetRepository.getTarget(supervisor, idea.getApplicationPeriod(), idea.getProjectType())).thenReturn( + target + ); } private void whenSupervisorHasNoTargetsLeft(final Idea idea) { final Target target = new Target(supervisor, idea.getApplicationPeriod(), idea.getProjectType()); - when(targetRepository.getTarget(supervisor, idea.getApplicationPeriod(), idea.getProjectType())).thenReturn(target); + when(targetRepository.getTarget(supervisor, idea.getApplicationPeriod(), idea.getProjectType())).thenReturn( + target + ); } private void assertValidateSupervisorAcceptanceFails(Idea idea, SelectionError error) { @@ -386,5 +459,4 @@ public class IdeaServiceImplTest { Assertions.assertEquals(tail, actual.getTail()); Assertions.assertEquals(head, actual.getHead()); } - } diff --git a/core/src/test/java/se/su/dsv/scipro/match/IdeaTest.java b/core/src/test/java/se/su/dsv/scipro/match/IdeaTest.java index edb9da2899..6c17a125d1 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/IdeaTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/IdeaTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -7,8 +9,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class IdeaTest { private Match supervisor; diff --git a/core/src/test/java/se/su/dsv/scipro/match/MatchFollowUpServiceTest.java b/core/src/test/java/se/su/dsv/scipro/match/MatchFollowUpServiceTest.java index ee84b2d14a..c443b0b709 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/MatchFollowUpServiceTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/MatchFollowUpServiceTest.java @@ -1,26 +1,31 @@ package se.su.dsv.scipro.match; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + import com.google.common.collect.ImmutableSet; +import jakarta.inject.Inject; +import java.util.Collections; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Collections; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; - public class MatchFollowUpServiceTest extends MatchModuleTest { - public static final PageRequest ALL = new PageRequest(0, Integer.MAX_VALUE, new Sort(Sort.Direction.DESC, "target")); + + public static final PageRequest ALL = new PageRequest( + 0, + Integer.MAX_VALUE, + new Sort(Sort.Direction.DESC, "target") + ); + @Inject private MatchFollowUpService matchFollowUpService; @@ -37,8 +42,22 @@ public class MatchFollowUpServiceTest extends MatchModuleTest { ApplicationPeriod applicationPeriod = new ApplicationPeriod("Test period"); applicationPeriod.setProjectTypes(ImmutableSet.of(bachelor, master)); this.applicationPeriod = save(applicationPeriod); - bob = save(User.builder().firstName("Bob").lastName("Supervisor").emailAddress("bob@example.com").roles(Collections.singleton(Roles.SUPERVISOR)).build()); - charles = save(User.builder().firstName("Charles").lastName("Supervisor").emailAddress("charles@example.com").roles(Collections.singleton(Roles.SUPERVISOR)).build()); + bob = save( + User.builder() + .firstName("Bob") + .lastName("Supervisor") + .emailAddress("bob@example.com") + .roles(Collections.singleton(Roles.SUPERVISOR)) + .build() + ); + charles = save( + User.builder() + .firstName("Charles") + .lastName("Supervisor") + .emailAddress("charles@example.com") + .roles(Collections.singleton(Roles.SUPERVISOR)) + .build() + ); } @Test @@ -103,4 +122,4 @@ public class MatchFollowUpServiceTest extends MatchModuleTest { targetEntity.setTarget(target); save(targetEntity); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/match/MatchModuleTest.java b/core/src/test/java/se/su/dsv/scipro/match/MatchModuleTest.java index 7a189d32f4..03090c4cf8 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/MatchModuleTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/MatchModuleTest.java @@ -14,21 +14,27 @@ import se.su.dsv.scipro.test.SpringTest; @ExtendWith(MockitoExtension.class) public abstract class MatchModuleTest extends SpringTest { + // ToDo:The system services should be move to a system module that other modules can depend on @Mock protected DateService dateService; + @Mock protected GeneralSystemSettingsService generalSystemSettingsService; + // ToDo:Work towards removing this dependency @Mock protected NotificationController notificationController; + @Mock protected MailEventService mailEventService; + @Mock protected ActivityPlanFacade activityPlanFacade; + @Mock protected EventBus eventBus; + @Mock protected ProjectService projectService; - } diff --git a/core/src/test/java/se/su/dsv/scipro/match/ProjectStartNotifierTest.java b/core/src/test/java/se/su/dsv/scipro/match/ProjectStartNotifierTest.java index 3e4764be11..0d31af0400 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/ProjectStartNotifierTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/ProjectStartNotifierTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; + import com.google.common.eventbus.EventBus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,19 +16,18 @@ import se.su.dsv.scipro.notifications.dataobject.IdeaEvent; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) public class ProjectStartNotifierTest { @Mock private EventBus eventBus; + @Mock private NotificationController notificationController; + @InjectMocks private ProjectStartNotifier projectStartNotifier; + private Idea idea; @BeforeEach @@ -36,12 +39,20 @@ public class ProjectStartNotifierTest { @Test public void sends_success_notifications() { projectStartNotifier.projectStarted(new ProjectStartedEvent(idea)); - verify(notificationController).notifyProject(eq(idea.getProject()), eq(ProjectEvent.Event.EXPORTED_SUCCESS), isA(NotificationSource.class)); + verify(notificationController).notifyProject( + eq(idea.getProject()), + eq(ProjectEvent.Event.EXPORTED_SUCCESS), + isA(NotificationSource.class) + ); } @Test public void sends_failure_notifications() { projectStartNotifier.projectStartDenied(new ProjectStartDeniedEvent(idea)); - verify(notificationController).notifyIdea(eq(idea), eq(IdeaEvent.Event.EXPORTED_FAIL), isA(NotificationSource.class)); + verify(notificationController).notifyIdea( + eq(idea), + eq(IdeaEvent.Event.EXPORTED_FAIL), + isA(NotificationSource.class) + ); } } diff --git a/core/src/test/java/se/su/dsv/scipro/match/TargetServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/match/TargetServiceImplTest.java index e31511020f..d2715aab5d 100644 --- a/core/src/test/java/se/su/dsv/scipro/match/TargetServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/match/TargetServiceImplTest.java @@ -1,21 +1,21 @@ package se.su.dsv.scipro.match; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; - public class TargetServiceImplTest extends MatchModuleTest { @Inject private TargetServiceImpl targetService; + private ApplicationPeriod applicationPeriod; private User supervisor; private ProjectType projectType; diff --git a/core/src/test/java/se/su/dsv/scipro/match/TestApplicationPeriod.java b/core/src/test/java/se/su/dsv/scipro/match/TestApplicationPeriod.java index 673632b6ab..4b42e30c12 100755 --- a/core/src/test/java/se/su/dsv/scipro/match/TestApplicationPeriod.java +++ b/core/src/test/java/se/su/dsv/scipro/match/TestApplicationPeriod.java @@ -1,44 +1,55 @@ package se.su.dsv.scipro.match; +import java.time.LocalDate; +import java.util.HashSet; +import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.HashSet; -import java.util.Set; - public class TestApplicationPeriod { - private ApplicationPeriod currentBachelor; + private ApplicationPeriod currentBachelor; @BeforeEach public void startTransaction() { ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor degree thesis project"); - Set bachelorSet = new HashSet<>(); - bachelorSet.add(bachelor); + Set bachelorSet = new HashSet<>(); + bachelorSet.add(bachelor); - currentBachelor = createPeriod(bachelorSet, date("2012-07-15"), date("2012-08-15"), date("2012-09-01"), "Current bachelor period"); - } + currentBachelor = createPeriod( + bachelorSet, + date("2012-07-15"), + date("2012-08-15"), + date("2012-09-01"), + "Current bachelor period" + ); + } @Test public void testIfCourseStartHasPassed() { - LocalDate currentDate = date("2012-07-30"); - boolean shouldBeFalse = currentBachelor.getCourseStartDate().compareTo(currentDate)<0; - Assertions.assertFalse(shouldBeFalse, "Not false"); - - currentDate = date("2012-09-02"); - boolean shouldBeTrue = currentBachelor.getCourseStartDate().compareTo(currentDate)<0; - Assertions.assertTrue(shouldBeTrue, "Not true"); + LocalDate currentDate = date("2012-07-30"); + boolean shouldBeFalse = currentBachelor.getCourseStartDate().compareTo(currentDate) < 0; + Assertions.assertFalse(shouldBeFalse, "Not false"); + + currentDate = date("2012-09-02"); + boolean shouldBeTrue = currentBachelor.getCourseStartDate().compareTo(currentDate) < 0; + Assertions.assertTrue(shouldBeTrue, "Not true"); } - + private LocalDate date(String dateString) { return LocalDate.parse(dateString); } - - private ApplicationPeriod createPeriod(final Set projectTypeSet, final LocalDate startDate, final LocalDate endDate, final LocalDate courseStartDate, final String name) { + + private ApplicationPeriod createPeriod( + final Set projectTypeSet, + final LocalDate startDate, + final LocalDate endDate, + final LocalDate courseStartDate, + final String name + ) { ApplicationPeriod appPeriod = new ApplicationPeriod(); appPeriod.setStartDate(startDate); appPeriod.setEndDate(endDate); diff --git a/core/src/test/java/se/su/dsv/scipro/match/TestKeyword.java b/core/src/test/java/se/su/dsv/scipro/match/TestKeyword.java index 3932af2b01..fbe3b02194 100755 --- a/core/src/test/java/se/su/dsv/scipro/match/TestKeyword.java +++ b/core/src/test/java/se/su/dsv/scipro/match/TestKeyword.java @@ -1,26 +1,23 @@ package se.su.dsv.scipro.match; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; - import jakarta.inject.Inject; import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; public class TestKeyword extends IntegrationTest { @Inject private KeywordService keywordService; - private Keyword k; private Keyword k2; private Keyword k3; private Keyword k4; private Keyword k10; - @BeforeEach public void startTransaction() { @@ -30,25 +27,24 @@ public class TestKeyword extends IntegrationTest { k4 = newKeyword("keyword4"); k10 = newKeyword("keyword10"); } - + @Test public void testAutoCompleteKeywords() { - List emptyList = keywordService.getAutoCompleteKeywords("kei", 5); - Assertions.assertTrue(emptyList.isEmpty()); - - List sortedByName = keywordService.getAutoCompleteKeywords("keyword", 5); - List expected = Arrays.asList(k, k10, k2, k3, k4); - Assertions.assertEquals(expected, sortedByName); - - List keywords = keywordService.getAutoCompleteKeywords("keyword1", 5); - List twoKeywords = Arrays.asList(k, k10); - Assertions.assertEquals(twoKeywords, keywords); - } - - private Keyword newKeyword(String name) { - Keyword key = new Keyword(); - key.setKeyword(name); - return save(key); + List emptyList = keywordService.getAutoCompleteKeywords("kei", 5); + Assertions.assertTrue(emptyList.isEmpty()); + + List sortedByName = keywordService.getAutoCompleteKeywords("keyword", 5); + List expected = Arrays.asList(k, k10, k2, k3, k4); + Assertions.assertEquals(expected, sortedByName); + + List keywords = keywordService.getAutoCompleteKeywords("keyword1", 5); + List twoKeywords = Arrays.asList(k, k10); + Assertions.assertEquals(twoKeywords, keywords); } -} \ No newline at end of file + private Keyword newKeyword(String name) { + Keyword key = new Keyword(); + key.setKeyword(name); + return save(key); + } +} diff --git a/core/src/test/java/se/su/dsv/scipro/milestones/service/MilestoneActivatorTest.java b/core/src/test/java/se/su/dsv/scipro/milestones/service/MilestoneActivatorTest.java index fed52e8629..53f9ed6eb1 100644 --- a/core/src/test/java/se/su/dsv/scipro/milestones/service/MilestoneActivatorTest.java +++ b/core/src/test/java/se/su/dsv/scipro/milestones/service/MilestoneActivatorTest.java @@ -1,9 +1,21 @@ package se.su.dsv.scipro.milestones.service; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; -import org.junit.jupiter.api.extension.ExtendWith; +import java.time.LocalDate; +import java.time.Month; +import java.util.List; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.finalseminar.*; @@ -20,30 +32,21 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.time.Month; -import java.util.List; -import java.util.Set; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class MilestoneActivatorTest { @Mock private MileStoneService mileStoneService; + @Mock private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Mock private EventBus eventBus; + @Mock private FinalSeminarService finalSeminarService; + @Mock private NotificationController notificationController; @@ -58,27 +61,29 @@ public class MilestoneActivatorTest { @BeforeEach public void setUp() { - author = User.builder() - .firstName("Bob") - .lastName("Builder") - .emailAddress("bob@example.com") - .build(); + author = User.builder().firstName("Bob").lastName("Builder").emailAddress("bob@example.com").build(); author.setId(123L); ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); bachelor.getProjectTypeSettings().setMinActiveParticipationsToBeGraded(2); project = Project.builder() - .title("Project title") - .projectType(bachelor) - .startDate(LocalDate.of(2023, Month.MAY, 26)) - .projectParticipants(Set.of(author)) - .build(); + .title("Project title") + .projectType(bachelor) + .startDate(LocalDate.of(2023, Month.MAY, 26)) + .projectParticipants(Set.of(author)) + .build(); opposition = createOpposition(); respondent = createRespondent(); participation = createParticipation(); peerReview = createPeerReview(); - milestoneActivator = new MilestoneActivator(milestoneActivityTemplateService, mileStoneService, eventBus, finalSeminarService, notificationController); + milestoneActivator = new MilestoneActivator( + milestoneActivityTemplateService, + mileStoneService, + eventBus, + finalSeminarService, + notificationController + ); } @Test @@ -97,14 +102,20 @@ public class MilestoneActivatorTest { @Test public void does_nothing_if_no_milestone_for_the_opposition_approved_event() { milestoneActivator.oppositionApproved(new OppositionApprovedEvent(opposition)); - verify(mileStoneService, never()).setConfirmed(any(Project.class), any(User.class), any(MilestoneActivityTemplate.class), anyBoolean()); + verify(mileStoneService, never()).setConfirmed( + any(Project.class), + any(User.class), + any(MilestoneActivityTemplate.class), + anyBoolean() + ); } @Test public void activates_milestone_for_participation_approved_events() { participation.setGrade(FinalSeminarGrade.APPROVED); - when(finalSeminarService.findUserParticipating(project, author)) - .thenReturn(List.of(participation, participation)); + when(finalSeminarService.findUserParticipating(project, author)).thenReturn( + List.of(participation, participation) + ); ParticipationApprovedEvent event = new ParticipationApprovedEvent(participation); MilestoneActivityTemplate milestoneActivityTemplate = mockMilestoneForEvent(); @@ -114,8 +125,7 @@ public class MilestoneActivatorTest { @Test public void does_not_activate_milestone_for_participations_when_not_done_enough() { - when(finalSeminarService.findUserParticipating(project, author)) - .thenReturn(List.of(participation)); + when(finalSeminarService.findUserParticipating(project, author)).thenReturn(List.of(participation)); ParticipationApprovedEvent event = new ParticipationApprovedEvent(participation); MilestoneActivityTemplate milestoneActivityTemplate = mockMilestoneForEvent(); @@ -181,7 +191,9 @@ public class MilestoneActivatorTest { SupervisorGradingReport supervisorGradingReport = mock(SupervisorGradingReport.class); when(supervisorGradingReport.getProject()).thenReturn(project); when(supervisorGradingReport.getUser()).thenReturn(author); - SupervisorGradingReportSubmittedEvent event = new SupervisorGradingReportSubmittedEvent(supervisorGradingReport); + SupervisorGradingReportSubmittedEvent event = new SupervisorGradingReportSubmittedEvent( + supervisorGradingReport + ); MilestoneActivityTemplate activity = mockMilestoneForEvent(); milestoneActivator.supervisorGradingReportSubmitted(event); verifyIndividualMilestoneConfirmed(project, author, activity, true); @@ -197,15 +209,28 @@ public class MilestoneActivatorTest { verify(mileStoneService, times(2)).setConfirmed(project, activity, false); } - private void verifyIndividualMilestoneActivated(Project project, User student, MilestoneActivityTemplate milestoneActivityTemplate) { + private void verifyIndividualMilestoneActivated( + Project project, + User student, + MilestoneActivityTemplate milestoneActivityTemplate + ) { verifyIndividualMilestoneConfirmed(project, student, milestoneActivityTemplate, true); } - private void verifyMilestoneDeactivated(Project project, User student, MilestoneActivityTemplate milestoneActivityTemplate) { + private void verifyMilestoneDeactivated( + Project project, + User student, + MilestoneActivityTemplate milestoneActivityTemplate + ) { verifyIndividualMilestoneConfirmed(project, student, milestoneActivityTemplate, false); } - private void verifyIndividualMilestoneConfirmed(Project project, User student, MilestoneActivityTemplate milestoneActivityTemplate, boolean activated) { + private void verifyIndividualMilestoneConfirmed( + Project project, + User student, + MilestoneActivityTemplate milestoneActivityTemplate, + boolean activated + ) { verify(mileStoneService).setConfirmed(project, student, milestoneActivityTemplate, activated); } @@ -254,4 +279,4 @@ public class MilestoneActivatorTest { peerReview.setPeerRequest(new PeerRequest()); return peerReview; } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImplTest.java index 8b4e7ebd6f..8aea46084c 100644 --- a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneActivityTemplateServiceImplTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.milestones.service.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,19 +22,15 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class MilestoneActivityTemplateServiceImplTest { @Mock MilestoneActivityTemplateRepository milestoneActivityTemplateRepository; + @InjectMocks MilestoneActivityTemplateServiceImpl mileStoneActivityService; + private LocalDate date; private ProjectType projectType; @@ -41,16 +42,46 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testGetActivities() { - MilestoneActivityTemplate projectActivity = createActivity(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "This is it..", 0); + MilestoneActivityTemplate projectActivity = createActivity( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "This is it..", + 0 + ); List projectList = Collections.singletonList(projectActivity); - MilestoneActivityTemplate studentActivity = createActivity(MilestoneActivityTemplate.Type.STUDENT, "Student milestone", "Hi?", 0); + MilestoneActivityTemplate studentActivity = createActivity( + MilestoneActivityTemplate.Type.STUDENT, + "Student milestone", + "Hi?", + 0 + ); List studentList = Collections.singletonList(studentActivity); - when(milestoneActivityTemplateRepository.findActivities(eq(MilestoneActivityTemplate.Type.PROJECT), isA(ProjectType.class), eq(date))).thenReturn(projectList); - when(milestoneActivityTemplateRepository.findActivities(eq(MilestoneActivityTemplate.Type.STUDENT), isA(ProjectType.class), eq(date))).thenReturn(studentList); + when( + milestoneActivityTemplateRepository.findActivities( + eq(MilestoneActivityTemplate.Type.PROJECT), + isA(ProjectType.class), + eq(date) + ) + ).thenReturn(projectList); + when( + milestoneActivityTemplateRepository.findActivities( + eq(MilestoneActivityTemplate.Type.STUDENT), + isA(ProjectType.class), + eq(date) + ) + ).thenReturn(studentList); - List studentActivities = mileStoneActivityService.getActivities(MilestoneActivityTemplate.Type.STUDENT, mock(ProjectType.class), date); - List projectActivities = mileStoneActivityService.getActivities(MilestoneActivityTemplate.Type.PROJECT, mock(ProjectType.class), date); + List studentActivities = mileStoneActivityService.getActivities( + MilestoneActivityTemplate.Type.STUDENT, + mock(ProjectType.class), + date + ); + List projectActivities = mileStoneActivityService.getActivities( + MilestoneActivityTemplate.Type.PROJECT, + mock(ProjectType.class), + date + ); assertEquals(projectList, projectActivities); assertEquals(studentList, studentActivities); @@ -58,24 +89,43 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testGetAllActivities() { - MilestoneActivityTemplate projectActivity = createActivity(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "This is it..", 0); - MilestoneActivityTemplate projectActivity2 = createActivity(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "This is it..", 1); + MilestoneActivityTemplate projectActivity = createActivity( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "This is it..", + 0 + ); + MilestoneActivityTemplate projectActivity2 = createActivity( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "This is it..", + 1 + ); projectActivity2.setDeleted(true); List listOfAll = Arrays.asList(projectActivity, projectActivity2); - when(milestoneActivityTemplateRepository.findAllActivitiesByProjectType(eq(MilestoneActivityTemplate.Type.PROJECT), eq(Collections.singletonList(projectType)))).thenReturn(listOfAll); + when( + milestoneActivityTemplateRepository.findAllActivitiesByProjectType( + eq(MilestoneActivityTemplate.Type.PROJECT), + eq(Collections.singletonList(projectType)) + ) + ).thenReturn(listOfAll); List projectTypes = new ArrayList<>(); projectTypes.add(projectType); - List all = mileStoneActivityService.getAllActivities(MilestoneActivityTemplate.Type.PROJECT, projectTypes); + List all = mileStoneActivityService.getAllActivities( + MilestoneActivityTemplate.Type.PROJECT, + projectTypes + ); assertEquals(all, listOfAll); } @Test public void testSave() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); String title = "title"; String desc = "desc"; MilestoneActivityTemplate activity = createActivity(MilestoneActivityTemplate.Type.PROJECT, title, desc, 0); @@ -95,8 +145,9 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testEditActivityShouldNotCareAboutSortOrder() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); MilestoneActivityTemplate activity = createActivity(MilestoneActivityTemplate.Type.PROJECT, "title", "desc", 0); DomainObjects.injectId(activity, 1L); @@ -113,8 +164,9 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testActivityWithZeroIdGetsSortOrderByCount() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); MilestoneActivityTemplate activity = createActivity(MilestoneActivityTemplate.Type.PROJECT, "title", "desc", 0); DomainObjects.injectId(activity, 0L); @@ -132,8 +184,9 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testActivityWithChangedPhaseGetsSortOrderByCount() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); MilestonePhaseTemplate currentPhase = new MilestonePhaseTemplate("title", "desc"); DomainObjects.injectId(currentPhase, 2L); MilestonePhaseTemplate newPhase = new MilestonePhaseTemplate("new title", "new desc"); @@ -155,25 +208,45 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testFindActivitiesByPhase() { - MilestoneActivityTemplate createSeminar = createActivity(MilestoneActivityTemplate.Type.PROJECT, "Create seminar", "description", 0); + MilestoneActivityTemplate createSeminar = createActivity( + MilestoneActivityTemplate.Type.PROJECT, + "Create seminar", + "description", + 0 + ); List list = Collections.singletonList(createSeminar); - when(milestoneActivityTemplateRepository.findByMilestonePhase(isA(MilestonePhaseTemplate.class))).thenReturn(list); + when(milestoneActivityTemplateRepository.findByMilestonePhase(isA(MilestonePhaseTemplate.class))).thenReturn( + list + ); - List serviceList = mileStoneActivityService.findByMileStonePhase(mock(MilestonePhaseTemplate.class)); + List serviceList = mileStoneActivityService.findByMileStonePhase( + mock(MilestonePhaseTemplate.class) + ); assertEquals(list, serviceList); } @Test public void testFindActiveActivitiesByPhase() { - List list = Collections.singletonList(createActivity(MilestoneActivityTemplate.Type.PROJECT, "Create seminar", "description", 0)); + List list = Collections.singletonList( + createActivity(MilestoneActivityTemplate.Type.PROJECT, "Create seminar", "description", 0) + ); LocalDate date = LocalDate.now().minusDays(1); ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); Project project = Project.builder().title("title").projectType(bachelor).startDate(LocalDate.now()).build(); project.setStartDate(date); - when(milestoneActivityTemplateRepository.findActiveByPhase(isA(MilestonePhaseTemplate.class), eq(bachelor), eq(date))).thenReturn(list); + when( + milestoneActivityTemplateRepository.findActiveByPhase( + isA(MilestonePhaseTemplate.class), + eq(bachelor), + eq(date) + ) + ).thenReturn(list); - List serviceList = mileStoneActivityService.findActiveByPhase(mock(MilestonePhaseTemplate.class), project); + List serviceList = mileStoneActivityService.findActiveByPhase( + mock(MilestonePhaseTemplate.class), + project + ); assertEquals(list, serviceList); } @@ -182,9 +255,19 @@ public class MilestoneActivityTemplateServiceImplTest { public void testCountActivitiesByTypeAndProjectTypeAndDate() { Long activityCount = 3L; LocalDate date = LocalDate.now().minusDays(1); - when(milestoneActivityTemplateRepository.countActivities(eq(MilestoneActivityTemplate.Type.PROJECT), isA(ProjectType.class), eq(date))).thenReturn(activityCount); + when( + milestoneActivityTemplateRepository.countActivities( + eq(MilestoneActivityTemplate.Type.PROJECT), + isA(ProjectType.class), + eq(date) + ) + ).thenReturn(activityCount); - Long serviceCount = mileStoneActivityService.countActivities(MilestoneActivityTemplate.Type.PROJECT, mock(ProjectType.class), date); + Long serviceCount = mileStoneActivityService.countActivities( + MilestoneActivityTemplate.Type.PROJECT, + mock(ProjectType.class), + date + ); assertEquals(serviceCount, activityCount); } @@ -201,17 +284,28 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testMoveUpPhase() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); - MilestoneActivityTemplate current = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate current = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); current.setMilestonePhaseTemplate(phase); - MilestoneActivityTemplate downActivity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate downActivity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); downActivity.setMilestonePhaseTemplate(phase); current.setSortOrder(2); downActivity.setSortOrder(1); - when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(1), eq(phase))).thenReturn(downActivity); + when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(1), eq(phase))).thenReturn( + downActivity + ); mileStoneActivityService.moveUp(current); @@ -222,27 +316,44 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testMoveUpPhaseOnTopDoesNothing() { MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); - MilestoneActivityTemplate current = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate current = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); current.setMilestonePhaseTemplate(phase); current.setSortOrder(1); - when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(0), eq(phase))).thenReturn(null); + when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(0), eq(phase))).thenReturn( + null + ); mileStoneActivityService.moveUp(current); Assertions.assertEquals(current.getSortOrder(), 1); } @Test public void testMoveDownPhase() { - when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))) - .thenAnswer(AdditionalAnswers.returnsFirstArg()); + when(milestoneActivityTemplateRepository.save(isA(MilestoneActivityTemplate.class))).thenAnswer( + AdditionalAnswers.returnsFirstArg() + ); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); - MilestoneActivityTemplate current = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate current = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); current.setMilestonePhaseTemplate(phase); - MilestoneActivityTemplate upActivity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate upActivity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); upActivity.setMilestonePhaseTemplate(phase); current.setSortOrder(1); upActivity.setSortOrder(2); - when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(2), eq(phase))).thenReturn(upActivity); + when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(2), eq(phase))).thenReturn( + upActivity + ); mileStoneActivityService.moveDown(current); @@ -253,10 +364,16 @@ public class MilestoneActivityTemplateServiceImplTest { @Test public void testMoveDownPhaseOnBottomDoesNothing() { MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); - MilestoneActivityTemplate current = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "title", "desc"); + MilestoneActivityTemplate current = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "title", + "desc" + ); current.setMilestonePhaseTemplate(phase); current.setSortOrder(1); - when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(2), eq(phase))).thenReturn(null); + when(milestoneActivityTemplateRepository.findBySortOrderAndMilestonePhaseTemplate(eq(2), eq(phase))).thenReturn( + null + ); mileStoneActivityService.moveDown(current); Assertions.assertEquals(current.getSortOrder(), 1); } @@ -269,13 +386,26 @@ public class MilestoneActivityTemplateServiceImplTest { Project project = Project.builder().title("title").projectType(projectType).startDate(LocalDate.now()).build(); project.setStartDate(dateCreated); - when(milestoneActivityTemplateRepository.findAllActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, projectType, dateCreated)).thenReturn(list); - List serviceList = mileStoneActivityService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, project); + when( + milestoneActivityTemplateRepository.findAllActivitiesInOrder( + MilestoneActivityTemplate.Type.PROJECT, + projectType, + dateCreated + ) + ).thenReturn(list); + List serviceList = mileStoneActivityService.getActivitiesInOrder( + MilestoneActivityTemplate.Type.PROJECT, + project + ); assertEquals(list, serviceList); } - - MilestoneActivityTemplate createActivity(MilestoneActivityTemplate.Type type, String title, String description, int order) { + MilestoneActivityTemplate createActivity( + MilestoneActivityTemplate.Type type, + String title, + String description, + int order + ) { MilestoneActivityTemplate activity = new MilestoneActivityTemplate(); activity.setType(type); activity.setTitle(title); diff --git a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImplTest.java index 348754d2d6..b8d885927a 100644 --- a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestonePhaseTemplateServiceImplTest.java @@ -1,25 +1,25 @@ package se.su.dsv.scipro.milestones.service.impl; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Sort; -import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; +import se.su.dsv.scipro.system.Sort; +import se.su.dsv.scipro.test.IntegrationTest; + public class MilestonePhaseTemplateServiceImplTest extends IntegrationTest { @Inject private MilestonePhaseTemplateServiceImpl service; + private MilestonePhaseTemplate first; private MilestonePhaseTemplate second; diff --git a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneServiceImplIntegrationTest.java index 8a3a74f6fa..09e2f53c87 100644 --- a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneServiceImplIntegrationTest.java @@ -1,26 +1,26 @@ package se.su.dsv.scipro.milestones.service.impl; +import static org.junit.jupiter.api.Assertions.*; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.milestones.dataobjects.Milestone; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.milestones.service.MileStoneService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.*; - public class MilestoneServiceImplIntegrationTest extends IntegrationTest { + public static final PageRequest ALL = new PageRequest(0, Long.MAX_VALUE); @Inject @@ -38,11 +38,19 @@ public class MilestoneServiceImplIntegrationTest extends IntegrationTest { project = createProject(); user = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); MilestonePhaseTemplate phase = save(new MilestonePhaseTemplate("Phase 1", "Description")); - MilestoneActivityTemplate individualMilestone = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.STUDENT, "Student milestone", "Description"); + MilestoneActivityTemplate individualMilestone = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.STUDENT, + "Student milestone", + "Description" + ); individualMilestone.setMilestonePhaseTemplate(phase); individualMilestone.addProjectType(bachelor); this.individualMilestone = save(individualMilestone); - MilestoneActivityTemplate projectMilestone = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "Description"); + MilestoneActivityTemplate projectMilestone = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "Description" + ); projectMilestone.setMilestonePhaseTemplate(phase); projectMilestone.addProjectType(bachelor); this.projectMilestone = save(projectMilestone); @@ -130,7 +138,16 @@ public class MilestoneServiceImplIntegrationTest extends IntegrationTest { } private Project createProject() { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - return save(Project.builder().title("Title").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + return save( + Project.builder() + .title("Title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); } } diff --git a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImplTest.java index 400261587a..9a1735cfd3 100644 --- a/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/milestones/service/impl/MilestoneStatisticsServiceImplTest.java @@ -1,24 +1,23 @@ package se.su.dsv.scipro.milestones.service.impl; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Collection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.milestones.dataobjects.Milestone; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Collection; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; - public class MilestoneStatisticsServiceImplTest extends IntegrationTest { @Inject @@ -58,19 +57,36 @@ public class MilestoneStatisticsServiceImplTest extends IntegrationTest { confirmMilestone(completed, secondMilestone); confirmMilestone(completed, firstMilestone); - Collection progressedProjects = milestoneStatisticsService.getProgressedProjects(secondMilestone, firstMilestone, new PageRequest(0, 10)); + Collection progressedProjects = milestoneStatisticsService.getProgressedProjects( + secondMilestone, + firstMilestone, + new PageRequest(0, 10) + ); assertThat(progressedProjects, hasItem(project)); assertThat(progressedProjects, not(hasItem(notCompleted))); assertThat(progressedProjects, not(hasItem(completed))); } private Project createProject() { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - return save(Project.builder().title("Title").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + return save( + Project.builder() + .title("Title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); } private MilestoneActivityTemplate createMilestone(final MilestonePhaseTemplate phase) { - MilestoneActivityTemplate individualMilestone = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "Description"); + MilestoneActivityTemplate individualMilestone = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "Description" + ); individualMilestone.setMilestonePhaseTemplate(phase); individualMilestone.addProjectType(bachelor); return save(individualMilestone); @@ -81,4 +97,4 @@ public class MilestoneStatisticsServiceImplTest extends IntegrationTest { milestone.setConfirmed(true); save(milestone); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/misc/DaysServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/misc/DaysServiceImplTest.java index 3448b46520..b91fd98aec 100644 --- a/core/src/test/java/se/su/dsv/scipro/misc/DaysServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/misc/DaysServiceImplTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.misc; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -10,18 +14,15 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriodService; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.*; - @ExtendWith(MockitoExtension.class) public class DaysServiceImplTest { @Mock NonWorkDayPeriodService nonWorkDays; + @InjectMocks DaysServiceImpl service; + private ZonedDateTime now; private ZonedDateTime then; @@ -106,7 +107,12 @@ public class DaysServiceImplTest { then(2013, 4, 26); // when - Mockito.when(nonWorkDays.isNonWorkDay(ArgumentMatchers.isA(LocalDate.class))).thenReturn(true, true, true, false); + Mockito.when(nonWorkDays.isNonWorkDay(ArgumentMatchers.isA(LocalDate.class))).thenReturn( + true, + true, + true, + false + ); // then Date ahead = service.workDaysAhead(now(), 1); diff --git a/core/src/test/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImplTest.java index 64d4ea6480..358530c931 100644 --- a/core/src/test/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/nonworkperiod/NonWorkDayPeriodServiceImplTest.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.nonworkperiod; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.inject.Inject; import java.time.LocalDate; import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; public class NonWorkDayPeriodServiceImplTest extends IntegrationTest { @@ -57,4 +56,4 @@ public class NonWorkDayPeriodServiceImplTest extends IntegrationTest { nonWorkDayPeriod.setComment("Comment"); return service.save(nonWorkDayPeriod); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationControllerImplTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationControllerImplTest.java index 6c770e1a9d..92c836e20c 100755 --- a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationControllerImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationControllerImplTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.notifications; +import static org.hamcrest.CoreMatchers.anything; +import static org.hamcrest.CoreMatchers.everyItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -26,38 +35,49 @@ import se.su.dsv.scipro.system.CurrentUser; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.anything; -import static org.hamcrest.CoreMatchers.everyItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class NotificationControllerImplTest { - @Mock MailEventService mailEventService; - @Mock NotificationService notificationService; - @Mock NotificationMailFormatter mailFormatter; - @Mock ReceiverConfigurationService receiverConfiguration; - @Mock DeliveryConfigurationService deliveryConfiguration; - @Mock CurrentUser currentUser; + @Mock + MailEventService mailEventService; + + @Mock + NotificationService notificationService; + + @Mock + NotificationMailFormatter mailFormatter; + + @Mock + ReceiverConfigurationService receiverConfiguration; + + @Mock + DeliveryConfigurationService deliveryConfiguration; + + @Mock + CurrentUser currentUser; NotificationControllerImpl notificationController; @BeforeEach public void setup() { notificationController = new NotificationControllerImpl( - notificationService, - mailFormatter, - mailEventService, - receiverConfiguration, deliveryConfiguration, () -> currentUser); + notificationService, + mailFormatter, + mailEventService, + receiverConfiguration, + deliveryConfiguration, + () -> currentUser + ); when(mailFormatter.format(isA(Notification.class))).thenReturn(new NotificationMail("Subject", "Body")); - when(deliveryConfiguration.isDelivery(isA(Notification.Type.class), isA(Enum.class), isA(DeliveryMethod.class), isA(Optional.class))).thenReturn(true); + when( + deliveryConfiguration.isDelivery( + isA(Notification.Type.class), + isA(Enum.class), + isA(DeliveryMethod.class), + isA(Optional.class) + ) + ).thenReturn(true); } @Test @@ -139,8 +159,12 @@ public class NotificationControllerImplTest { when(group.getMembers()).thenReturn(generateMemberList()); setReceivers(Member.Type.AUTHOR, Member.Type.SUPERVISOR); - Set notifications = - notificationController.notifyGroup(group,GroupEvent.Event.MESSAGE_THREAD_REPLY,new NotificationSource(),user); + Set notifications = notificationController.notifyGroup( + group, + GroupEvent.Event.MESSAGE_THREAD_REPLY, + new NotificationSource(), + user + ); assertThat(notifications, everyItem(hasSender(user))); } @@ -154,8 +178,12 @@ public class NotificationControllerImplTest { when(project.getMembers()).thenReturn(generateMemberList()); setReceivers(Member.Type.AUTHOR, Member.Type.SUPERVISOR); - Set notifications = - notificationController.notifyProjectForum( ProjectForumEvent.Event.NEW_FORUM_POST_COMMENT, new NotificationSource(), project, user); + Set notifications = notificationController.notifyProjectForum( + ProjectForumEvent.Event.NEW_FORUM_POST_COMMENT, + new NotificationSource(), + project, + user + ); assertThat(notifications, everyItem(hasSender(user))); } @@ -166,13 +194,20 @@ public class NotificationControllerImplTest { Project project = mock(Project.class); // when - when(receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class))).thenReturn(true); + when( + receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class)) + ).thenReturn(true); when(project.getMembers()).thenReturn(generateMemberList()); notificationController.notifyProject(project, ProjectEvent.Event.CREATED, new NotificationSource()); // then // there is only one supervisor, setting should be checked for every delivery method - verify(deliveryConfiguration, times(DeliveryMethod.values().length)).isDelivery(isA(Notification.Type.class), isA(Enum.class), isA(DeliveryMethod.class), MockitoHamcrest.argThat(isPresent(anything()))); + verify(deliveryConfiguration, times(DeliveryMethod.values().length)).isDelivery( + isA(Notification.Type.class), + isA(Enum.class), + isA(DeliveryMethod.class), + MockitoHamcrest.argThat(isPresent(anything())) + ); } private Matcher> isPresent(final Matcher aMatcher) { @@ -192,9 +227,13 @@ public class NotificationControllerImplTest { } private void setReceivers(Member.Type... members) { - when(receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class))).thenReturn(false); + when( + receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class)) + ).thenReturn(false); for (Member.Type member : members) { - when(receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), eq(member))).thenReturn(true); + when( + receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), eq(member)) + ).thenReturn(true); } } diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplIntegrationTest.java index a6e232e644..18ecf8ce88 100644 --- a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplIntegrationTest.java @@ -1,30 +1,29 @@ package se.su.dsv.scipro.notifications; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.notifications.dataobject.Notification; -import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; - import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.*; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.notifications.dataobject.Notification; +import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; + public class NotificationServiceImplIntegrationTest extends IntegrationTest { @Inject @@ -48,8 +47,12 @@ public class NotificationServiceImplIntegrationTest extends IntegrationTest { @Test public void find_all_with_all_filters() { NotificationService.Filter filter = new NotificationService.Filter(); - User currentUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); - User anotherUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User currentUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); + User anotherUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); createNotification(currentUser); createNotification(anotherUser); @@ -65,21 +68,32 @@ public class NotificationServiceImplIntegrationTest extends IntegrationTest { @Test public void find_all_with_no_filters() { - User currentUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); - User anotherUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User currentUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); + User anotherUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); Notification first = createNotification(currentUser); Notification second = createNotification(anotherUser); - Iterable all = notificationService.findAll(new NotificationService.Filter(), new PageRequest(0, 3)); + Iterable all = notificationService.findAll( + new NotificationService.Filter(), + new PageRequest(0, 3) + ); assertThat(all, hasItems(first, second)); } @Test public void count_with_filter() { - User currentUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); - User anotherUser = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User currentUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); + User anotherUser = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); createNotification(currentUser); createNotification(anotherUser); @@ -89,9 +103,18 @@ public class NotificationServiceImplIntegrationTest extends IntegrationTest { @Test public void mark_read_for_project() { - final User user = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + final User user = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); final ProjectType bachelor = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - final Project project = save(Project.builder().title("Project").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(user).build()); + final Project project = save( + Project.builder() + .title("Project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build() + ); final ProjectEvent projectEvent = new ProjectEvent(); projectEvent.setProject(project); final Notification notification = createNotification(user); diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplTest.java index 21215fba77..9297c23d0c 100644 --- a/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/NotificationServiceImplTest.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.notifications; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertFalse; - public class NotificationServiceImplTest extends IntegrationTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImplTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImplTest.java index 48aa666a57..9eb8af276e 100755 --- a/core/src/test/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/interfaces/impl/NotificationMailFormatterImplTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.notifications.interfaces.impl; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.util.Arrays; +import java.util.Collection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; @@ -10,13 +16,6 @@ import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.test.ObjectMother; -import java.util.Arrays; -import java.util.Collection; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - public class NotificationMailFormatterImplTest { NotificationMailFormatterImpl formatter; diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImplTest.java index 859d745825..9ae5b17a4f 100644 --- a/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/DeliveryConfigurationServiceImplTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.notifications.settings.service; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.notifications.dataobject.Notification; @@ -8,12 +13,6 @@ import se.su.dsv.scipro.notifications.settings.entities.DeliveryMethod; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class DeliveryConfigurationServiceImplTest extends IntegrationTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImplTest.java index 6bcf07bee1..a65475a9d8 100644 --- a/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/notifications/settings/service/ReceiverConfigurationServiceImplTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.notifications.settings.service; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.data.dataobjects.Member; @@ -7,11 +11,6 @@ import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ReceiverConfigurationServiceImplTest extends IntegrationTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/peer/CommentServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/peer/CommentServiceImplTest.java index a06e305f00..4901ff9b16 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/CommentServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/CommentServiceImplTest.java @@ -1,26 +1,31 @@ package se.su.dsv.scipro.peer; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; - public class CommentServiceImplTest extends IntegrationTest { @Inject private CommentServiceImpl commentService; + private Comment comment; private CommentThread commentThread; @BeforeEach public void setUp() throws Exception { commentThread = save(new CommentThread(getCommentable())); - comment = save(new Comment(save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()), commentThread)); + comment = save( + new Comment( + save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()), + commentThread + ) + ); } @Test diff --git a/core/src/test/java/se/su/dsv/scipro/peer/CommentThreadServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/peer/CommentThreadServiceImplTest.java index 55cee624c3..cd037f3ee5 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/CommentThreadServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/CommentThreadServiceImplTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.peer; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import jakarta.inject.Inject; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.file.FileDescription; @@ -11,17 +17,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.Dates; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; - -import java.time.LocalDate; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.*; - public class CommentThreadServiceImplTest extends IntegrationTest { - @Inject private CommentThreadServiceImpl commentThreadService; @@ -83,13 +80,21 @@ public class CommentThreadServiceImplTest extends IntegrationTest { } private Project createProject() { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - return save(Project.builder().title("project").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + return save( + Project.builder() + .title("project") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); } private void createDefaultProjectType() { ProjectType projectType = save(new ProjectType(DegreeType.NONE, "name", "description")); this.projectType = save(projectType); } - } diff --git a/core/src/test/java/se/su/dsv/scipro/peer/PeerPortalImplTest.java b/core/src/test/java/se/su/dsv/scipro/peer/PeerPortalImplTest.java index 0dade63f19..c522e28538 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/PeerPortalImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/PeerPortalImplTest.java @@ -1,7 +1,17 @@ package se.su.dsv.scipro.peer; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; import com.querydsl.core.types.Predicate; +import java.time.Clock; +import java.time.LocalDate; +import java.util.Collections; +import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,17 +35,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.Dates; import se.su.dsv.scipro.test.ObjectMother; -import java.time.Clock; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Optional; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class PeerPortalImplTest { @@ -44,16 +43,22 @@ public class PeerPortalImplTest { @Mock private FileService fileDescriptionService; + @Mock private PeerReviewRepository peerReviewRepository; + @Mock private PeerRequestRepository peerRequestRepository; + @Mock private ProjectService projectService; + @Mock private EventBus eventBus; + @Mock private ProjectFileService projectFileService; + @Mock private DaysService daysService; @@ -61,27 +66,39 @@ public class PeerPortalImplTest { @BeforeEach public void setUp() { - peerPortalController = new PeerPortalImpl(fileDescriptionService, peerReviewRepository, peerRequestRepository, eventBus, projectFileService, daysService, Clock.systemDefaultZone()); + peerPortalController = new PeerPortalImpl( + fileDescriptionService, + peerReviewRepository, + peerRequestRepository, + eventBus, + projectFileService, + daysService, + Clock.systemDefaultZone() + ); } private void mockSavingPeerRequest() { - when(peerRequestRepository.save(ArgumentMatchers.isA(PeerRequest.class))).thenAnswer(new org.mockito.stubbing.Answer() { - @Override - public PeerRequest answer(InvocationOnMock invocation) { - PeerRequest peerRequest = (PeerRequest) invocation.getArguments()[0]; - peerRequest.setId(SOME_REQUEST_ID); - return peerRequest; + when(peerRequestRepository.save(ArgumentMatchers.isA(PeerRequest.class))).thenAnswer( + new org.mockito.stubbing.Answer() { + @Override + public PeerRequest answer(InvocationOnMock invocation) { + PeerRequest peerRequest = (PeerRequest) invocation.getArguments()[0]; + peerRequest.setId(SOME_REQUEST_ID); + return peerRequest; + } } - }); + ); } private void mockSavingPeerReview() { - when(peerReviewRepository.save(ArgumentMatchers.isA(PeerReview.class))).thenAnswer(new org.mockito.stubbing.Answer() { - @Override - public PeerReview answer(InvocationOnMock invocation) { - return (PeerReview) invocation.getArguments()[0]; + when(peerReviewRepository.save(ArgumentMatchers.isA(PeerReview.class))).thenAnswer( + new org.mockito.stubbing.Answer() { + @Override + public PeerReview answer(InvocationOnMock invocation) { + return (PeerReview) invocation.getArguments()[0]; + } } - }); + ); } @Test @@ -256,7 +273,6 @@ public class PeerPortalImplTest { }); } - private Project projectWithSettings() { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "b", "b"); projectType.setProjectTypeSettings(new ProjectTypeSettings()); diff --git a/core/src/test/java/se/su/dsv/scipro/peer/PeerRequestServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/peer/PeerRequestServiceImplTest.java index 05a2437313..215e6c5f45 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/PeerRequestServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/PeerRequestServiceImplTest.java @@ -1,25 +1,24 @@ package se.su.dsv.scipro.peer; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.Dates; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.EnumSet; - import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.EnumSet; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.Dates; +import se.su.dsv.scipro.test.IntegrationTest; + public class PeerRequestServiceImplTest extends IntegrationTest { private static final PageRequest ALL = new PageRequest(0, Long.MAX_VALUE); @@ -37,9 +36,16 @@ public class PeerRequestServiceImplTest extends IntegrationTest { @BeforeEach public void setUp() throws Exception { requester = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); projectType = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - project = Project.builder().title("title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build(); + project = Project.builder() + .title("title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); project.addProjectParticipant(requester); save(project); this.cancelled = newRequest(project, requester, RequestStatus.CANCELED); @@ -56,7 +62,9 @@ public class PeerRequestServiceImplTest extends IntegrationTest { @Test public void findAllWithParams() { PeerRequestService.Filter params = new PeerRequestService.Filter(); - params.setAuthor(save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build())); + params.setAuthor( + save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()) + ); assertThat(peerRequestService.findAll(params, ALL), not(hasItem(waiting))); } @@ -82,13 +90,18 @@ public class PeerRequestServiceImplTest extends IntegrationTest { @Test public void findAvailableRequests() { RequestStatus status = RequestStatus.WAITING; - User reviewer = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User reviewer = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); assertThat(peerRequestService.findAvailableRequests(reviewer, status, projectType, ALL), hasItems(waiting)); } @Test public void findAvailableRequestsWithoutStatus() { - assertThat(peerRequestService.findAvailableRequests(null, null, projectType, ALL), hasItems(waiting, cancelled)); + assertThat( + peerRequestService.findAvailableRequests(null, null, projectType, ALL), + hasItems(waiting, cancelled) + ); } @Test @@ -105,7 +118,9 @@ public class PeerRequestServiceImplTest extends IntegrationTest { @Test public void countAvailableRequests() { - User reviewer = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User reviewer = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); assertEquals(1, peerRequestService.countAvailableRequests(reviewer, RequestStatus.WAITING, projectType)); } diff --git a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplIntegrationTest.java index 4aca6ed7c2..15a004fd89 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplIntegrationTest.java @@ -1,25 +1,24 @@ package se.su.dsv.scipro.peer; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.Dates; -import se.su.dsv.scipro.test.IntegrationTest; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; import jakarta.inject.Inject; import java.time.LocalDate; import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.Dates; +import se.su.dsv.scipro.test.IntegrationTest; public class PeerReviewServiceImplIntegrationTest extends IntegrationTest { @@ -121,8 +120,17 @@ public class PeerReviewServiceImplIntegrationTest extends IntegrationTest { } private Project createProject() { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); - return save(Project.builder().title("Peer project").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); + return save( + Project.builder() + .title("Peer project") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); } private void createDefaultProjectType() { diff --git a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplTest.java index d36f73b25e..9c6a5dd3da 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewServiceImplTest.java @@ -1,25 +1,24 @@ package se.su.dsv.scipro.peer; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.Dates; -import se.su.dsv.scipro.test.IntegrationTest; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static se.su.dsv.scipro.peer.PeerReviewService.Filter; import jakarta.inject.Inject; import java.time.LocalDate; import java.util.EnumSet; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; -import static se.su.dsv.scipro.peer.PeerReviewService.Filter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.Dates; +import se.su.dsv.scipro.test.IntegrationTest; public class PeerReviewServiceImplTest extends IntegrationTest { @@ -29,7 +28,11 @@ public class PeerReviewServiceImplTest extends IntegrationTest { private PeerReviewServiceImpl peerReviewService; public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - public static final Project SOME_PROJECT = Project.builder().title("Some title").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).build(); + public static final Project SOME_PROJECT = Project.builder() + .title("Some title") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .build(); private PeerRequest peerRequest; private User reviewer; private PeerReview completed; @@ -80,13 +83,18 @@ public class PeerReviewServiceImplTest extends IntegrationTest { @Test public void findByReviewerAndProject() { - assertThat(peerReviewService.findNonExpiredReviewsByProjectAuthor(reviewer, project), hasItems(completed, inProgress)); + assertThat( + peerReviewService.findNonExpiredReviewsByProjectAuthor(reviewer, project), + hasItems(completed, inProgress) + ); } private PeerRequest prepareRequest() { PeerRequest peerRequest = new PeerRequest(); peerRequest.setProject(requesterProject); - peerRequest.setRequester(save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build())); + peerRequest.setRequester( + save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()) + ); final FileDescription fileDescription = save(new FileDescription()); final FileReference fileReference = new FileReference(); fileReference.setFileDescription(fileDescription); @@ -96,9 +104,18 @@ public class PeerReviewServiceImplTest extends IntegrationTest { } private Project newProject() { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); ProjectType projectType = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - return save(Project.builder().title("Title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + return save( + Project.builder() + .title("Title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); } private PeerReview newReview(PeerReview.ReviewStatus status) { diff --git a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewTest.java b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewTest.java index 257da20d91..ff071c2109 100644 --- a/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewTest.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/PeerReviewTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.peer; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; @@ -7,11 +10,8 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.test.Dates; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class PeerReviewTest { + @Test public void submitting_review_late_expires_the_review() { PeerReview peerReview = createLateReview(); @@ -65,5 +65,4 @@ public class PeerReviewTest { projectType.setProjectTypeSettings(projectTypeSettings); return Project.builder().title("Peer project").projectType(projectType).startDate(LocalDate.now()).build(); } - } diff --git a/core/src/test/java/se/su/dsv/scipro/peer/TestPeerReview.java b/core/src/test/java/se/su/dsv/scipro/peer/TestPeerReview.java index 93a6feb96b..34e5e5c7e2 100755 --- a/core/src/test/java/se/su/dsv/scipro/peer/TestPeerReview.java +++ b/core/src/test/java/se/su/dsv/scipro/peer/TestPeerReview.java @@ -1,16 +1,6 @@ package se.su.dsv.scipro.peer; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; +import static java.util.Arrays.asList; import jakarta.inject.Inject; import java.text.ParseException; @@ -22,13 +12,23 @@ import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; - -import static java.util.Arrays.asList; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; public class TestPeerReview extends IntegrationTest { @Inject private PeerReviewService peerReviewService; + @Inject private PeerRequestService peerRequestService; @@ -42,7 +42,6 @@ public class TestPeerReview extends IntegrationTest { @BeforeEach public void startTransaction() { - ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor degree thesis project"); bachelor = save(bachelor); master = new ProjectType(ProjectType.MASTER, "Master", "Master degree thesis project"); @@ -138,7 +137,12 @@ public class TestPeerReview extends IntegrationTest { @Test public void findAvailableRequests() { - List requestPage = peerRequestService.findAvailableRequests(reviewer, RequestStatus.WAITING, master, new PageRequest(0, 8)); + List requestPage = peerRequestService.findAvailableRequests( + reviewer, + RequestStatus.WAITING, + master, + new PageRequest(0, 8) + ); List requestList = requestPage; Assertions.assertEquals(1, requestList.size()); Assertions.assertEquals(asList(request4), requestList); @@ -146,14 +150,25 @@ public class TestPeerReview extends IntegrationTest { request3.setStatus(RequestStatus.WAITING); request4.setProject(bachelorProject); - requestPage = peerRequestService.findAvailableRequests(reviewer, RequestStatus.WAITING, master, new PageRequest(0, 8)); + requestPage = peerRequestService.findAvailableRequests( + reviewer, + RequestStatus.WAITING, + master, + new PageRequest(0, 8) + ); requestList = requestPage; Assertions.assertEquals(asList(request3), requestList); - } - private PeerReview newReview(final User reviewer, final Project project, PeerRequest request, final RequestStatus status, boolean aborted, boolean submitted) { + private PeerReview newReview( + final User reviewer, + final Project project, + PeerRequest request, + final RequestStatus status, + boolean aborted, + boolean submitted + ) { PeerReview review = new PeerReview(); review.setReviewer(reviewer); review.setProject(project); @@ -165,14 +180,18 @@ public class TestPeerReview extends IntegrationTest { if (submitted) { review.setComment("a;".repeat(PeerReview.MINIMUM_COMMENT_LENGTH_IF_NO_ANSWERS)); review.submit(); - } - else if (aborted) { + } else if (aborted) { review.expire(); } return save(review); } - private PeerRequest newRequest(final User requester, final Project project, final String comment, final RequestStatus status) { + private PeerRequest newRequest( + final User requester, + final Project project, + final String comment, + final RequestStatus status + ) { PeerRequest request = new PeerRequest(); request.setComment(comment); request.setRequester(requester); @@ -188,14 +207,19 @@ public class TestPeerReview extends IntegrationTest { return save(request); } - private Project newProject(final ProjectType projectType, final User student, final User headSupervisor, final ProjectStatus status) { - Project newProject = Project.builder(). - title("Project title"). - projectType(projectType). - startDate(LocalDate.now()). - headSupervisor(headSupervisor). - projectStatus(status). - build(); + private Project newProject( + final ProjectType projectType, + final User student, + final User headSupervisor, + final ProjectStatus status + ) { + Project newProject = Project.builder() + .title("Project title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .projectStatus(status) + .build(); newProject.addProjectParticipant(student); return save(newProject); diff --git a/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryTest.java b/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryTest.java index 8b113e1524..19c616614f 100644 --- a/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryTest.java +++ b/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSettingsRepositoryTest.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.plagiarism.urkund; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.SpringTest; - -import jakarta.inject.Inject; - import static org.junit.jupiter.api.Assertions.assertEquals; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.SpringTest; + public class UrkundSettingsRepositoryTest extends SpringTest { + @Inject private UrkundSettingsRepository urkundSettingsRepository; @@ -24,4 +24,4 @@ public class UrkundSettingsRepositoryTest extends SpringTest { assertEquals(new_.getUsername(), updated.getUsername()); assertEquals(new_.getPassword(), updated.getPassword()); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryTest.java b/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryTest.java index 6120fe3468..c09f3ea67e 100644 --- a/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryTest.java +++ b/core/src/test/java/se/su/dsv/scipro/plagiarism/urkund/UrkundSubmissionRepositoryTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.plagiarism.urkund; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import jakarta.inject.Inject; +import java.time.Instant; +import java.util.Optional; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -8,14 +15,6 @@ import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.test.SpringTest; -import jakarta.inject.Inject; -import java.time.Instant; -import java.util.Optional; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - public class UrkundSubmissionRepositoryTest extends SpringTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplIntegrationTest.java index a5945c7c91..5181dfffff 100644 --- a/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplIntegrationTest.java @@ -1,29 +1,29 @@ package se.su.dsv.scipro.project; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.Unit; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.Unit; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; + public class ProjectServiceImplIntegrationTest extends IntegrationTest { @Inject private ProjectService projectService; + private Project project; private User user; @@ -127,7 +127,6 @@ public class ProjectServiceImplIntegrationTest extends IntegrationTest { assertEquals(expected, projectService.count(params)); } - @Test public void getActiveProjects() { ProjectType projectType = createProjectType(); @@ -270,7 +269,9 @@ public class ProjectServiceImplIntegrationTest extends IntegrationTest { } private Project createProject(ProjectType projectType, ProjectStatus active) { - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); Project project = new Project(); project.setTitle("Some title"); project.setProjectType(projectType); diff --git a/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplTest.java index 90c4d77867..6a5734f950 100644 --- a/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/project/ProjectServiceImplTest.java @@ -1,6 +1,15 @@ package se.su.dsv.scipro.project; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -13,29 +22,27 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ProjectServiceImplTest { + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType( + DegreeType.BACHELOR, + "Some project type", + "Some description" + ); - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); @Mock private ProjectRepo projectRepo; + @Mock private EventBus eventBus; + @Mock private Provider em; + @InjectMocks private ProjectServiceImpl projectService; + private Project project; @BeforeEach @@ -46,12 +53,12 @@ public class ProjectServiceImplTest { private void initProjects() { User headSupervisorUser = new UserBuilder().create(); project = Project.builder() - .title("Some title") - .projectType(SOME_PROJECT_TYPE) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisorUser) - .stateOfMind(StateOfMind.FINE) - .build(); + .title("Some title") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisorUser) + .stateOfMind(StateOfMind.FINE) + .build(); project.addCoSupervisor(new UserBuilder().create()); project.addReviewer(new UserBuilder().create()); } @@ -74,8 +81,6 @@ public class ProjectServiceImplTest { @Test public void isNotPartOfProject() { - - assertFalse(projectService.isPartOfProject(project, new UserBuilder().create())); } diff --git a/core/src/test/java/se/su/dsv/scipro/project/ProjectTest.java b/core/src/test/java/se/su/dsv/scipro/project/ProjectTest.java index c4cda5b784..c597265d6c 100644 --- a/core/src/test/java/se/su/dsv/scipro/project/ProjectTest.java +++ b/core/src/test/java/se/su/dsv/scipro/project/ProjectTest.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.project; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - public class ProjectTest { private Project project; diff --git a/core/src/test/java/se/su/dsv/scipro/project/TestProject.java b/core/src/test/java/se/su/dsv/scipro/project/TestProject.java index 7d92c2e545..1cff5bc479 100755 --- a/core/src/test/java/se/su/dsv/scipro/project/TestProject.java +++ b/core/src/test/java/se/su/dsv/scipro/project/TestProject.java @@ -1,6 +1,9 @@ package se.su.dsv.scipro.project; - +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,11 +11,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.List; - public class TestProject extends IntegrationTest { @Inject @@ -23,7 +21,6 @@ public class TestProject extends IntegrationTest { @BeforeEach public void startTransaction() { - ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor degree thesis project"); bachelor = save(bachelor); @@ -37,17 +34,23 @@ public class TestProject extends IntegrationTest { authorUser = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); authorUser = save(authorUser); - project1 = Project.builder(). - title("Project 1"). - projectType(bachelor). - startDate(LocalDate.now()). - headSupervisor(employeeUser). - projectStatus(ProjectStatus.ACTIVE). - build(); + project1 = Project.builder() + .title("Project 1") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(employeeUser) + .projectStatus(ProjectStatus.ACTIVE) + .build(); project1.addProjectParticipant(authorUser); project1 = save(project1); - project2 = Project.builder().title("Tester 2").projectType(master).startDate(LocalDate.now()).headSupervisor(employeeUser).projectStatus(ProjectStatus.INACTIVE).build(); + project2 = Project.builder() + .title("Tester 2") + .projectType(master) + .startDate(LocalDate.now()) + .headSupervisor(employeeUser) + .projectStatus(ProjectStatus.INACTIVE) + .build(); project2.addProjectParticipant(authorUser); project2 = save(project2); diff --git a/core/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImplTest.java index 3dfeddaf19..66d7ece367 100644 --- a/core/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerServiceImplTest.java @@ -1,28 +1,29 @@ package se.su.dsv.scipro.projectpartner; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.match.ApplicationPeriod; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.match.ApplicationPeriod; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.IntegrationTest; + public class ProjectPartnerServiceImplTest extends IntegrationTest { + public static final PageRequest ALL = new PageRequest(0, Long.MAX_VALUE); @Inject private ProjectPartnerServiceImpl projectPartnerService; + private User user; private ProjectType projectType; private ApplicationPeriod applicationPeriod; @@ -40,14 +41,23 @@ public class ProjectPartnerServiceImplTest extends IntegrationTest { public void getProjectPartnerInSpan() { ProjectPartner projectPartner = newProjectPartner(); ProjectPartner pastProjectPartner = newProjectPartner(10); - assertThat(projectPartnerService.getProjectPartnerInSpan(5, applicationPeriod, projectType, ALL), hasItem(projectPartner)); - assertThat(projectPartnerService.getProjectPartnerInSpan(5, applicationPeriod, projectType, ALL), not(hasItem(pastProjectPartner))); + assertThat( + projectPartnerService.getProjectPartnerInSpan(5, applicationPeriod, projectType, ALL), + hasItem(projectPartner) + ); + assertThat( + projectPartnerService.getProjectPartnerInSpan(5, applicationPeriod, projectType, ALL), + not(hasItem(pastProjectPartner)) + ); } @Test public void getProjectPartnerInSpanDaysAreZero() { ProjectPartner projectPartner = newProjectPartner(365); - assertThat(projectPartnerService.getProjectPartnerInSpan(0, applicationPeriod, projectType, ALL), hasItem(projectPartner)); + assertThat( + projectPartnerService.getProjectPartnerInSpan(0, applicationPeriod, projectType, ALL), + hasItem(projectPartner) + ); } @Test diff --git a/core/src/test/java/se/su/dsv/scipro/reflection/ReflectionServiceTest.java b/core/src/test/java/se/su/dsv/scipro/reflection/ReflectionServiceTest.java index 745def4bcd..78dfb897e7 100644 --- a/core/src/test/java/se/su/dsv/scipro/reflection/ReflectionServiceTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reflection/ReflectionServiceTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.reflection; +import static org.junit.jupiter.api.Assertions.*; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.finalseminar.FinalSeminar; @@ -15,18 +20,14 @@ import se.su.dsv.scipro.test.IntegrationTest; import se.su.dsv.scipro.test.MutableFixedClock; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; - -import java.time.LocalDate; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.*; - public class ReflectionServiceTest extends IntegrationTest { + @Inject public ReflectionService reflectionService; + @Inject public FinalSeminarService finalSeminarService; + @Inject public MutableFixedClock clock; @@ -36,17 +37,21 @@ public class ReflectionServiceTest extends IntegrationTest { @BeforeEach void setUp() { ProjectType bachelor = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - User supervisor = User.builder().firstName("Stefan").lastName("Supervisor").emailAddress("stefan@example.com").build(); + User supervisor = User.builder() + .firstName("Stefan") + .lastName("Supervisor") + .emailAddress("stefan@example.com") + .build(); save(supervisor); author = User.builder().firstName("Arthur").lastName("Author").emailAddress("arthur@example.com").build(); save(author); project = Project.builder() - .title("Project") - .projectType(bachelor) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .projectParticipants(Set.of(author)) - .build(); + .title("Project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .projectParticipants(Set.of(author)) + .build(); save(project); } @@ -105,28 +110,49 @@ public class ReflectionServiceTest extends IntegrationTest { public void request_resubmission() { LocalDate seminarDate = scheduleSeminar(); clock.setDate(seminarDate.plusDays(1)); - assertTrue(reflectionService.hasToFillInReflection(project, author), - "After the final seminar the author should be required to submit a reflection"); + assertTrue( + reflectionService.hasToFillInReflection(project, author), + "After the final seminar the author should be required to submit a reflection" + ); String myReflection = "my reflection"; reflectionService.submitReflection(project, author, myReflection); assertEquals(myReflection, reflectionService.getSubmittedReflection(project, author)); - assertFalse(reflectionService.hasToFillInReflection(project, author), - "After submitting the initial reflection it should no longer be required"); + assertFalse( + reflectionService.hasToFillInReflection(project, author), + "After submitting the initial reflection it should no longer be required" + ); reflectionService.requestNewReflection(project, author, "Very bad reflection"); - assertTrue(reflectionService.hasToFillInReflection(project, author), - "After supervisor requests resubmission the author should now be required to submit a new reflection"); - assertEquals(myReflection, reflectionService.getSubmittedReflection(project, author), - "The old reflection should be saved to make it easier for the student to update it"); + assertTrue( + reflectionService.hasToFillInReflection(project, author), + "After supervisor requests resubmission the author should now be required to submit a new reflection" + ); + assertEquals( + myReflection, + reflectionService.getSubmittedReflection(project, author), + "The old reflection should be saved to make it easier for the student to update it" + ); } private LocalDate scheduleSeminar() { project.setFinalSeminarRuleExempted(true); // to bypass rough draft approval - FinalSeminarDetails details = new FinalSeminarDetails("Zoom", false, 1, 1, Language.SWEDISH, Language.ENGLISH, "zoom id 123"); + FinalSeminarDetails details = new FinalSeminarDetails( + "Zoom", + false, + 1, + 1, + Language.SWEDISH, + Language.ENGLISH, + "zoom id 123" + ); LocalDate seminarDate = finalSeminarService.getEarliestSeminarDate(); - Either schedule = finalSeminarService.schedule(project, seminarDate.atStartOfDay(), details); + Either schedule = finalSeminarService.schedule( + project, + seminarDate.atStartOfDay(), + details + ); assertTrue(schedule.isRight(), "Failed to schedule seminar: " + schedule); return seminarDate; } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/report/GradeCalculatorTest.java b/core/src/test/java/se/su/dsv/scipro/report/GradeCalculatorTest.java index 252c11cdeb..10fa29a994 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/GradeCalculatorTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/GradeCalculatorTest.java @@ -1,12 +1,13 @@ package se.su.dsv.scipro.report; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public abstract class GradeCalculatorTest { + @Test public void a_report_whose_answers_does_not_meet_minimum_requirements_fails() { assessAllCriteria(0); diff --git a/core/src/test/java/se/su/dsv/scipro/report/GradingCriterionTest.java b/core/src/test/java/se/su/dsv/scipro/report/GradingCriterionTest.java index e1d046cbce..fcb4098f12 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/GradingCriterionTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/GradingCriterionTest.java @@ -1,10 +1,11 @@ package se.su.dsv.scipro.report; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + public class GradingCriterionTest { + @Test public void criterion_with_feedback_and_points_is_assessed() { GradingCriterion gradingCriterion = createCriterion(); diff --git a/core/src/test/java/se/su/dsv/scipro/report/GradingReportServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/report/GradingReportServiceImplIntegrationTest.java index 765513cc4e..4eec189c37 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/GradingReportServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/GradingReportServiceImplIntegrationTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.report; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.Month; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.finalseminar.FinalSeminar; @@ -13,21 +22,12 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.Month; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class GradingReportServiceImplIntegrationTest extends IntegrationTest { public static final String FEEDBACK_ON_OPPOSITION = "Feedback on opposition"; public static final int OPPOSITION_CRITERION_POINTS = 2; public static final String FEEDBACK = "feedback"; + @Inject private GradingReportServiceImpl gradingReportService; @@ -55,7 +55,10 @@ public class GradingReportServiceImplIntegrationTest extends IntegrationTest { createGradingReport(project, student1); - assertEquals(project.getProjectParticipants().size(), gradingReportService.getSupervisorGradingReports(project).size()); + assertEquals( + project.getProjectParticipants().size(), + gradingReportService.getSupervisorGradingReports(project).size() + ); } @Test @@ -66,13 +69,17 @@ public class GradingReportServiceImplIntegrationTest extends IntegrationTest { @Test public void submit_supervisor_grading_report_flags_report_as_submitted() { assessAllCriteria(gradingReport); - Either, SupervisorGradingReport> result = gradingReportService.submitReport(gradingReport); + Either, SupervisorGradingReport> result = gradingReportService.submitReport( + gradingReport + ); assertTrue(result.isRight()); } @Test public void submitting_supervisor_report_throws_exception_if_report_is_not_finished() { - Either, SupervisorGradingReport> result = gradingReportService.submitReport(gradingReport); + Either, SupervisorGradingReport> result = gradingReportService.submitReport( + gradingReport + ); assertFalse(result.isRight()); } @@ -222,43 +229,83 @@ public class GradingReportServiceImplIntegrationTest extends IntegrationTest { return save(gradingReport); } - private GradingReportTemplate createProjectGradingCriterion(GradingReportTemplate gradingReportTemplate, int maxPoints) { - List gradingCriterionPointTemplates = getPointTemplates(maxPoints, "criterion description"); - gradingReportTemplate.addProjectCriterion("Projektkriterium", "Project Criterion", 0, gradingCriterionPointTemplates); + private GradingReportTemplate createProjectGradingCriterion( + GradingReportTemplate gradingReportTemplate, + int maxPoints + ) { + List gradingCriterionPointTemplates = getPointTemplates( + maxPoints, + "criterion description" + ); + gradingReportTemplate.addProjectCriterion( + "Projektkriterium", + "Project Criterion", + 0, + gradingCriterionPointTemplates + ); return save(gradingReportTemplate); } private List getPointTemplates(int maxPoints, String desc) { List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder().point(0).description(desc).descriptionEn(desc).build()); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder().point(0).description(desc).descriptionEn(desc).build() + ); for (int i = 1; i <= maxPoints; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder().point(i).description(desc).descriptionEn(desc).build()); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder().point(i).description(desc).descriptionEn(desc).build() + ); } return gradingCriterionPointTemplates; } - private GradingReportTemplate createIndividualGradingCriterion(GradingReportTemplate gradingReportTemplate, int maxPoints) { - List gradingCriterionPointTemplates = getPointTemplates(maxPoints, "criterion description"); - gradingReportTemplate.addIndividualCriterion("Individuellt kriterium", "Individual Criterion", 0, gradingCriterionPointTemplates); + private GradingReportTemplate createIndividualGradingCriterion( + GradingReportTemplate gradingReportTemplate, + int maxPoints + ) { + List gradingCriterionPointTemplates = getPointTemplates( + maxPoints, + "criterion description" + ); + gradingReportTemplate.addIndividualCriterion( + "Individuellt kriterium", + "Individual Criterion", + 0, + gradingCriterionPointTemplates + ); return save(gradingReportTemplate); } private GradingReportTemplate createOppositionCriteria(GradingReportTemplate gradingReportTemplate, int maxPoints) { List gradingCriterionPointTemplates = getPointTemplates(maxPoints, "Opposition"); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 0, gradingCriterionPointTemplates, AbstractGradingCriterion.Flag.OPPOSITION); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 0, + gradingCriterionPointTemplates, + AbstractGradingCriterion.Flag.OPPOSITION + ); return save(gradingReportTemplate); } private GradingReportTemplate createGradingReportTemplate(ProjectType projectType) { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(projectType, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + projectType, + LocalDate.of(2024, Month.JANUARY, 1) + ); return save(gradingReportTemplate); } private Project createProject(ProjectType projectType, int credits) { TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(student)); - Project project = Project.builder().title("some title").projectType(projectType).startDate(LocalDate.now()).projectParticipants(projectParticipants).headSupervisor(createSupervisor()).build(); + Project project = Project.builder() + .title("some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(createSupervisor()) + .build(); project.setCredits(credits); return save(project); } @@ -277,5 +324,4 @@ public class GradingReportServiceImplIntegrationTest extends IntegrationTest { user.addRole(Roles.SUPERVISOR); return save(user); } - } diff --git a/core/src/test/java/se/su/dsv/scipro/report/GradingReportTemplateTest.java b/core/src/test/java/se/su/dsv/scipro/report/GradingReportTemplateTest.java index 4f6b4adc27..0c503f990f 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/GradingReportTemplateTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/GradingReportTemplateTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.report; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -10,17 +20,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; - public class GradingReportTemplateTest { private ProjectType bachelor; @@ -35,7 +34,8 @@ public class GradingReportTemplateTest { @Test public void creating_a_grading_report_template_with_null_project_type_should_fail() { assertThrows(IllegalArgumentException.class, () -> - new GradingReportTemplate(null, LocalDate.of(2024, Month.JANUARY, 1))); + new GradingReportTemplate(null, LocalDate.of(2024, Month.JANUARY, 1)) + ); } @Test @@ -64,11 +64,13 @@ public class GradingReportTemplateTest { GradingReportTemplate gradingReportTemplate = createBachelorTemplate(); List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); gradingReportTemplate.addProjectCriterion(title, titleEn, 1, gradingCriterionPointTemplates); assertThat(gradingReportTemplate.getCriteria(), hasItem(withTitle(title))); diff --git a/core/src/test/java/se/su/dsv/scipro/report/OppositionReportServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/report/OppositionReportServiceImplTest.java index ebf8e6d827..39cf0e784f 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/OppositionReportServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/OppositionReportServiceImplTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.report; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +import java.time.LocalDate; +import java.time.Month; +import java.time.ZonedDateTime; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,14 +28,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; - @ExtendWith(MockitoExtension.class) public class OppositionReportServiceImplTest { @@ -36,16 +35,22 @@ public class OppositionReportServiceImplTest { @Mock OppositionReportRepo oppositionReportRepo; + @Mock GradingReportTemplateRepo gradingReportTemplateRepo; + @Mock FileService fileService; + @InjectMocks OppositionReportServiceImpl oppositionReportService; + private OppositionReport oppositionReport; private FinalSeminarOpposition finalSeminarOpposition; + @Mock FileDescriptionRepo fileDescriptionRepo; + @Mock FinalSeminarOppositionRepo finalSeminarOppositionRepo; @@ -53,11 +58,13 @@ public class OppositionReportServiceImplTest { public void setUp() throws Exception { GradingReportTemplate template = new GradingReportTemplate(BACHELOR, LocalDate.of(2024, Month.JANUARY, 1)); List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); template.addProjectCriterion("title", "titleEn", 1, gradingCriterionPointTemplates); finalSeminarOpposition = createFinalSeminarOpposition(); DomainObjects.injectId(finalSeminarOpposition, 1L); @@ -82,7 +89,9 @@ public class OppositionReportServiceImplTest { @Test public void get_existing_opposition_report() { - Mockito.when(oppositionReportRepo.findByFinalSeminarOpposition(any(FinalSeminarOpposition.class))).thenReturn(oppositionReport); + Mockito.when(oppositionReportRepo.findByFinalSeminarOpposition(any(FinalSeminarOpposition.class))).thenReturn( + oppositionReport + ); assertEquals(oppositionReport, oppositionReportService.findOrCreateReport(createFinalSeminarOpposition())); } diff --git a/core/src/test/java/se/su/dsv/scipro/report/OppositionReportTest.java b/core/src/test/java/se/su/dsv/scipro/report/OppositionReportTest.java index 6cdae1e826..65af375b71 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/OppositionReportTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/OppositionReportTest.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.report; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; public class OppositionReportTest { @@ -22,8 +21,10 @@ public class OppositionReportTest { public void prepareTemplate() { ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(bachelor, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + bachelor, + LocalDate.of(2024, Month.JANUARY, 1) + ); addCriteria(gradingReportTemplate); oppositionReport = gradingReportTemplate.createOppositionReport(new FinalSeminarOpposition()); @@ -61,16 +62,37 @@ public class OppositionReportTest { private void addCriteria(GradingReportTemplate gradingReportTemplate) { List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("For 1 point: Be nice to your supervisor") .descriptionEn("For 1 point: Be nice to your supervisor") - .build()); - gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1,gradingCriterionPointTemplates); - gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1,gradingCriterionPointTemplates); - gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1,gradingCriterionPointTemplates); - gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, gradingCriterionPointTemplates); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, gradingCriterionPointTemplates); + .build() + ); + gradingReportTemplate.addProjectCriterion( + "U1 Sammanfattning", + "U1 Abstract", + 1, + gradingCriterionPointTemplates + ); + gradingReportTemplate.addProjectCriterion( + "U2 Introduktion", + "U2 Introduction", + 1, + gradingCriterionPointTemplates + ); + gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, gradingCriterionPointTemplates); + gradingReportTemplate.addProjectCriterion( + "U4 Frågeställning", + "U4 Research question", + 1, + gradingCriterionPointTemplates + ); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + gradingCriterionPointTemplates + ); } - } diff --git a/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportFactoryTest.java b/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportFactoryTest.java index 46f39e4a7d..b956f46040 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportFactoryTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportFactoryTest.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.report; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static se.su.dsv.scipro.test.ObjectMother.*; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static se.su.dsv.scipro.test.ObjectMother.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SupervisorGradingReportFactoryTest { @@ -20,11 +19,13 @@ public class SupervisorGradingReportFactoryTest { public void setUp() throws Exception { gradingReportTemplate = new GradingReportTemplate(BACHELOR, LocalDate.of(2024, Month.JANUARY, 1)); List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); gradingReportTemplate.addProjectCriterion("Title", "TitleEn", 1, gradingCriterionPointTemplates); gradingReportTemplate.addIndividualCriterion("Title", "TitleEn", 1, gradingCriterionPointTemplates); } diff --git a/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportTest.java b/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportTest.java index 2cf70d275e..a5091ad1c7 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/SupervisorGradingReportTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.report; +import static org.junit.jupiter.api.Assertions.*; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -7,13 +13,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; - public class SupervisorGradingReportTest { private SupervisorGradingReport gradingReport; @@ -59,37 +58,111 @@ public class SupervisorGradingReportTest { } private void addCriteria(GradingReportTemplate gradingReportTemplate) { - gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 1, getPointTemplates(2)); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 1, + getPointTemplates(2) + ); gradingReportTemplate.addProjectCriterion("U8 Resultat", "U8 Result", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 1, getPointTemplates(2)).setFx(false); - gradingReportTemplate.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 0, getPointTemplates(3)).setFx(false); + gradingReportTemplate + .addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 1, + getPointTemplates(2) + ) + .setFx(false); + gradingReportTemplate + .addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + getPointTemplates(1) + ) + .setFx(false); + gradingReportTemplate + .addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, getPointTemplates(1)) + .setFx(false); + gradingReportTemplate + .addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + getPointTemplates(1) + ) + .setFx(false); + gradingReportTemplate + .addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 0, + getPointTemplates(3) + ) + .setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, getPointTemplates(2), AbstractGradingCriterion.Flag.OPPOSITION); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + getPointTemplates(2), + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingReportTemplate.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 0, getPointTemplates(1), AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + gradingReportTemplate.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + getPointTemplates(1) + ); + gradingReportTemplate + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + getPointTemplates(1) + ) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 0, + getPointTemplates(1), + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); } private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculatorTest.java b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculatorTest.java index f0c024be16..d89ee2e351 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculatorTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorBachelorGradeCalculatorTest.java @@ -1,21 +1,21 @@ package se.su.dsv.scipro.report.calculators.original; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.report.*; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.mock; - public class SupervisorBachelorGradeCalculatorTest extends GradeCalculatorTest { + private GradingReport gradingReport; private SupervisorBachelorGradeCalculator gradeCalculator; @@ -84,32 +84,98 @@ public class SupervisorBachelorGradeCalculatorTest extends GradeCalculatorTest { return gradeCalculator; } - @Override protected GradingReportTemplate prepareTemplate() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(ObjectMother.BACHELOR, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + ObjectMother.BACHELOR, + LocalDate.of(2024, Month.JANUARY, 1) + ); gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 1, getPointTemplates(2)); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 1, + getPointTemplates(2) + ); gradingReportTemplate.addProjectCriterion("U8 Resultat", "U8 Result", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, getPointTemplates(1)); + gradingReportTemplate.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + getPointTemplates(1) + ); gradingReportTemplate.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 0, getPointTemplates(3)).setFx(false); + gradingReportTemplate.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + getPointTemplates(1) + ); + gradingReportTemplate + .addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 0, + getPointTemplates(3) + ) + .setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, getPointTemplates(2), AbstractGradingCriterion.Flag.OPPOSITION); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + getPointTemplates(2), + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingReportTemplate.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 0, getPointTemplates(1), AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + gradingReportTemplate.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + getPointTemplates(1) + ); + gradingReportTemplate + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + getPointTemplates(1) + ) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 0, + getPointTemplates(1), + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplate; } @@ -117,11 +183,13 @@ public class SupervisorBachelorGradeCalculatorTest extends GradeCalculatorTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculatorTest.java b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculatorTest.java index da7d4ea369..b45abb7da1 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculatorTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster15GradeCalculatorTest.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.report.calculators.original; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.report.*; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.report.*; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; public class SupervisorMaster15GradeCalculatorTest extends GradeCalculatorTest { @@ -23,7 +22,10 @@ public class SupervisorMaster15GradeCalculatorTest extends GradeCalculatorTest { public void setUp() throws Exception { GradingReportTemplate gradingReportTemplate = prepareTemplate(); - gradingReport = gradingReportTemplate.createSupervisorReport(ObjectMother.SOME_MASTER_PROJECT, mock(User.class)); + gradingReport = gradingReportTemplate.createSupervisorReport( + ObjectMother.SOME_MASTER_PROJECT, + mock(User.class) + ); gradeCalculator = new SupervisorMaster15GradeCalculator(); } @@ -74,29 +76,94 @@ public class SupervisorMaster15GradeCalculatorTest extends GradeCalculatorTest { @Override protected GradingReportTemplate prepareTemplate() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(ObjectMother.MASTER, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + ObjectMother.MASTER, + LocalDate.of(2024, Month.JANUARY, 1) + ); gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 1, getPointTemplates(2)); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 1, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 1, + getPointTemplates(2) + ); gradingReportTemplate.addProjectCriterion("U8 Resultat", "U8 Result", 2, getPointTemplates(3)); - gradingReportTemplate.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 2, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U10 Form, Struktur och språk", "U10 Form, structure and language", 1, getPointTemplates(1)); + gradingReportTemplate.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 2, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U10 Form, Struktur och språk", + "U10 Form, structure and language", + 1, + getPointTemplates(1) + ); gradingReportTemplate.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 1, getPointTemplates(3)); + gradingReportTemplate.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + getPointTemplates(1) + ); + gradingReportTemplate.addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 1, + getPointTemplates(3) + ); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, getPointTemplates(2), AbstractGradingCriterion.Flag.OPPOSITION); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + getPointTemplates(2), + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingReportTemplate.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, getPointTemplates(1)).setFx(false); - gradingReportTemplate.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 0, getPointTemplates(1), AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + gradingReportTemplate.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + getPointTemplates(1) + ); + gradingReportTemplate + .addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + getPointTemplates(1) + ) + .setFx(false); + gradingReportTemplate + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 0, + getPointTemplates(1), + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplate; } @@ -104,11 +171,13 @@ public class SupervisorMaster15GradeCalculatorTest extends GradeCalculatorTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculatorTest.java b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculatorTest.java index 1f21c29600..be270c03ef 100644 --- a/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculatorTest.java +++ b/core/src/test/java/se/su/dsv/scipro/report/calculators/original/SupervisorMaster30GradeCalculatorTest.java @@ -1,20 +1,20 @@ package se.su.dsv.scipro.report.calculators.original; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.report.*; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - public class SupervisorMaster30GradeCalculatorTest extends GradeCalculatorTest { + private SupervisorGradingReport gradingReport; private SupervisorMaster30GradeCalculator gradeCalculator; @@ -22,7 +22,10 @@ public class SupervisorMaster30GradeCalculatorTest extends GradeCalculatorTest { public void setUp() throws Exception { GradingReportTemplate gradingReportTemplate = prepareTemplate(); - gradingReport = gradingReportTemplate.createSupervisorReport(ObjectMother.SOME_MASTER_PROJECT, mock(User.class)); + gradingReport = gradingReportTemplate.createSupervisorReport( + ObjectMother.SOME_MASTER_PROJECT, + mock(User.class) + ); gradeCalculator = new SupervisorMaster30GradeCalculator(); } @@ -74,29 +77,90 @@ public class SupervisorMaster30GradeCalculatorTest extends GradeCalculatorTest { @Override protected GradingReportTemplate prepareTemplate() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(ObjectMother.MASTER, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + ObjectMother.MASTER, + LocalDate.of(2024, Month.JANUARY, 1) + ); gradingReportTemplate.addProjectCriterion("U1 Sammanfattning", "U1 Abstract", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U2 Introduktion", "U2 Introduction", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U3 Problem", "U3 Problem", 1, getPointTemplates(1)); gradingReportTemplate.addProjectCriterion("U4 Frågeställning", "U4 Research question", 1, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U5 Vetenskaplig förankring", "U5 Scientific base", 2, getPointTemplates(3)); - gradingReportTemplate.addProjectCriterion("U6 Metodval", "U6 Choice of research method", 2, getPointTemplates(3)); - gradingReportTemplate.addProjectCriterion("U7 Metodtillämpning", "U7 Application of research method", 2, getPointTemplates(3)); + gradingReportTemplate.addProjectCriterion( + "U5 Vetenskaplig förankring", + "U5 Scientific base", + 2, + getPointTemplates(3) + ); + gradingReportTemplate.addProjectCriterion( + "U6 Metodval", + "U6 Choice of research method", + 2, + getPointTemplates(3) + ); + gradingReportTemplate.addProjectCriterion( + "U7 Metodtillämpning", + "U7 Application of research method", + 2, + getPointTemplates(3) + ); gradingReportTemplate.addProjectCriterion("U8 Resultat", "U8 Result", 2, getPointTemplates(3)); - gradingReportTemplate.addProjectCriterion("U9 Slutsatser och diskussion", "U9 Conclusions and discussion", 2, getPointTemplates(2)); - gradingReportTemplate.addProjectCriterion("U10 Form, struktur och språk", "U10 Form, structure and language", 1, getPointTemplates(1)); + gradingReportTemplate.addProjectCriterion( + "U9 Slutsatser och diskussion", + "U9 Conclusions and discussion", + 2, + getPointTemplates(2) + ); + gradingReportTemplate.addProjectCriterion( + "U10 Form, struktur och språk", + "U10 Form, structure and language", + 1, + getPointTemplates(1) + ); gradingReportTemplate.addProjectCriterion("U11 Argumentation", "U11 Argumentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U12 Källhänvisningar och dokumentation", "U12 References and documentation", 1, getPointTemplates(1)); - gradingReportTemplate.addProjectCriterion("U13 Originalitet och signifikans", "U13 Originality and significance", 2, getPointTemplates(4)); + gradingReportTemplate.addProjectCriterion( + "U12 Källhänvisningar och dokumentation", + "U12 References and documentation", + 1, + getPointTemplates(1) + ); + gradingReportTemplate.addProjectCriterion( + "U13 Originalitet och signifikans", + "U13 Originality and significance", + 2, + getPointTemplates(4) + ); - gradingReportTemplate.addIndividualCriterion("Ö1 Oppositionsrapport", "Ö1 Opposition report", 1, getPointTemplates(2), AbstractGradingCriterion.Flag.OPPOSITION); + gradingReportTemplate.addIndividualCriterion( + "Ö1 Oppositionsrapport", + "Ö1 Opposition report", + 1, + getPointTemplates(2), + AbstractGradingCriterion.Flag.OPPOSITION + ); gradingReportTemplate.addIndividualCriterion("Ö2 Presentationer", "Ö2 Presentations", 1, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö3 Aktivitet vid seminarier och möten", "Ö3 Participation in seminars and meetings", 1, getPointTemplates(1)); + gradingReportTemplate.addIndividualCriterion( + "Ö3 Aktivitet vid seminarier och möten", + "Ö3 Participation in seminars and meetings", + 1, + getPointTemplates(1) + ); gradingReportTemplate.addIndividualCriterion("Ö4 Deadlines", "Ö4 Deadlines", 0, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö5 Revision efter slutseminarium", "Ö5 Revisions after the final seminar", 0, getPointTemplates(1)); - gradingReportTemplate.addIndividualCriterion("Ö6 Reflektion", "Ö6 Reflection", 0, getPointTemplates(1), AbstractGradingCriterion.Flag.REFLECTION).setFx(false); + gradingReportTemplate.addIndividualCriterion( + "Ö5 Revision efter slutseminarium", + "Ö5 Revisions after the final seminar", + 0, + getPointTemplates(1) + ); + gradingReportTemplate + .addIndividualCriterion( + "Ö6 Reflektion", + "Ö6 Reflection", + 0, + getPointTemplates(1), + AbstractGradingCriterion.Flag.REFLECTION + ) + .setFx(false); return gradingReportTemplate; } @@ -104,11 +168,13 @@ public class SupervisorMaster30GradeCalculatorTest extends GradeCalculatorTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImplTest.java index 587bd8b6c8..2dc785806f 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalServiceImplTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.reviewing; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.Optional; +import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.file.FileUpload; @@ -8,28 +17,30 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.Optional; -import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class FinalSeminarApprovalServiceImplTest extends ReviewingModuleTest { @Inject private FinalSeminarApprovalServiceImpl finalSeminarApprovalService; + private Project project; @BeforeEach public void setUp() throws Exception { - User reviewer = save(User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build()); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + User reviewer = save( + User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build() + ); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); ProjectType bachelor = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - project = save(Project.builder().title("My project").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + project = save( + Project.builder() + .title("My project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); project.addReviewer(reviewer); } @@ -44,7 +55,10 @@ public class FinalSeminarApprovalServiceImplTest extends ReviewingModuleTest { finalSeminarApprovalService.requestApproval(project, createFileUpload(), "test"); Optional finalSeminarApproval = finalSeminarApprovalService.findBy(project); assertTrue(finalSeminarApproval.isPresent()); - assertEquals(finalSeminarApproval.orElse(null), finalSeminarApprovalService.findOne(finalSeminarApproval.orElse(null).getId())); + assertEquals( + finalSeminarApproval.orElse(null), + finalSeminarApprovalService.findOne(finalSeminarApproval.orElse(null).getId()) + ); } @Test diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalTest.java index 235994a2f2..91093b5716 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/FinalSeminarApprovalTest.java @@ -1,13 +1,5 @@ package se.su.dsv.scipro.reviewing; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.project.Project; - -import java.util.Date; -import java.util.Optional; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -15,7 +7,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static se.su.dsv.scipro.reviewing.WithStatus.withStatus; +import java.util.Date; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.project.Project; + public class FinalSeminarApprovalTest { + @Test public void new_approval_is_undecided() { FinalSeminarApproval approval = createUndecided(); diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImplTest.java index 8c87bf7d11..e940bca282 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerCapacityServiceImplTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.reviewing; +import static org.junit.jupiter.api.Assertions.*; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.Month; +import java.time.Year; +import java.util.EnumSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.project.Project; @@ -12,14 +19,6 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.Month; -import java.time.Year; -import java.util.EnumSet; - -import static org.junit.jupiter.api.Assertions.*; - class ReviewerCapacityServiceImplTest extends IntegrationTest { private static Year YEAR_2024 = Year.of(2024); @@ -36,20 +35,20 @@ class ReviewerCapacityServiceImplTest extends IntegrationTest { @BeforeEach void setUp() { User reviewer = User.builder() - .firstName("John") - .lastName("Doe") - .emailAddress("john@example.com") - .roles(EnumSet.of(Roles.REVIEWER)) - .build(); + .firstName("John") + .lastName("Doe") + .emailAddress("john@example.com") + .roles(EnumSet.of(Roles.REVIEWER)) + .build(); reviewer.setActiveAsSupervisor(true); this.reviewer = save(reviewer); User supervisor = User.builder() - .firstName("Bob") - .lastName("Doe") - .emailAddress("bob@example.com") - .roles(EnumSet.of(Roles.SUPERVISOR)) - .build(); + .firstName("Bob") + .lastName("Doe") + .emailAddress("bob@example.com") + .roles(EnumSet.of(Roles.SUPERVISOR)) + .build(); supervisor.setActiveAsSupervisor(true); save(supervisor); @@ -61,11 +60,11 @@ class ReviewerCapacityServiceImplTest extends IntegrationTest { save(bachelor); Project project = Project.builder() - .title("A project") - .projectType(bachelor) - .startDate(LocalDate.of(2024, Month.JANUARY, 1)) - .headSupervisor(supervisor) - .build(); + .title("A project") + .projectType(bachelor) + .startDate(LocalDate.of(2024, Month.JANUARY, 1)) + .headSupervisor(supervisor) + .build(); project.setLanguage(Language.SWEDISH); project.setResearchArea(researchArea); this.project = save(project); @@ -198,4 +197,4 @@ class ReviewerCapacityServiceImplTest extends IntegrationTest { private static Target autumnTarget(final int target) { return new Target(YEAR_2024, 0, target, ""); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorkerTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorkerTest.java index 771739d65b..1305035764 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorkerTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerDecisionReminderWorkerTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.reviewing; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.LocalDate; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; @@ -7,24 +17,15 @@ import se.su.dsv.scipro.mail.MailEvent; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.*; -import java.time.LocalDate; -import java.util.Date; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ReviewerDecisionReminderWorkerTest { @Test public void should_remind_if_is_same_date() { Date today = new Date(); RoughDraftApproval roughDraftApproval = newRoughDraftApproval(); - boolean needReminding = ReviewerDecisionReminderWorker.needReminding(today, x -> Set.of(today)).test(roughDraftApproval); + boolean needReminding = ReviewerDecisionReminderWorker.needReminding(today, x -> Set.of(today)).test( + roughDraftApproval + ); assertTrue(needReminding); } @@ -34,7 +35,9 @@ public class ReviewerDecisionReminderWorkerTest { Date date = new Date(987452359L); RoughDraftApproval roughDraftApproval = newRoughDraftApproval(); - boolean needReminding = ReviewerDecisionReminderWorker.needReminding(new Date(0), x -> Set.of(date)).test(roughDraftApproval); + boolean needReminding = ReviewerDecisionReminderWorker.needReminding(new Date(0), x -> Set.of(date)).test( + roughDraftApproval + ); assertFalse(needReminding); } @@ -43,7 +46,10 @@ public class ReviewerDecisionReminderWorkerTest { public void reminder_should_include_title_of_every_idea() { RoughDraftApproval roughDraftApproval = newRoughDraftApproval(); - MailEvent reminder = ReviewerDecisionReminderWorker.generateRoughDraftReminder(Optional.ofNullable(roughDraftApproval.getProject().getReviewer()), List.of(roughDraftApproval)); + MailEvent reminder = ReviewerDecisionReminderWorker.generateRoughDraftReminder( + Optional.ofNullable(roughDraftApproval.getProject().getReviewer()), + List.of(roughDraftApproval) + ); assertThat(reminder.getMessageBody(), containsString(roughDraftApproval.getProject().getTitle())); } @@ -52,11 +58,13 @@ public class ReviewerDecisionReminderWorkerTest { RoughDraftApproval roughDraftApproval = newRoughDraftApproval(); User reviewer = roughDraftApproval.getProject().getReviewer(); - MailEvent reminder = ReviewerDecisionReminderWorker.generateRoughDraftReminder(Optional.ofNullable(reviewer), List.of(roughDraftApproval)); + MailEvent reminder = ReviewerDecisionReminderWorker.generateRoughDraftReminder( + Optional.ofNullable(reviewer), + List.of(roughDraftApproval) + ); assertThat(reminder.getRecipients(), hasItem(reviewer)); } - private Unit newUnit() { Unit unit = new Unit(); unit.setMatchResponsible("test@test,test"); @@ -72,7 +80,11 @@ public class ReviewerDecisionReminderWorkerTest { private Project newProject() { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - Project project = Project.builder().title("This is a title").projectType(projectType).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("This is a title") + .projectType(projectType) + .startDate(LocalDate.now()) + .build(); project.addReviewer(newUser()); project.setHeadSupervisor(newUser()); project.setId(555L); diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImplTest.java index 60da361347..d7776a8437 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerInteractionServiceImplTest.java @@ -1,6 +1,15 @@ package se.su.dsv.scipro.reviewing; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import java.time.LocalDate; +import java.util.Collections; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -19,24 +28,18 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Optional; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ReviewerInteractionServiceImplTest { + @Mock private EventBus eventBus; + @Mock private ReviewerThreadRepository reviewerThreadRepository; + @Mock private BasicForumService basicForumService; + @InjectMocks private ReviewerInteractionServiceImpl reviewerInteractionService; @@ -44,21 +47,24 @@ public class ReviewerInteractionServiceImplTest { public void setUp() throws Exception { when(reviewerThreadRepository.findByProject(isA(Project.class))).thenReturn(Optional.empty()); when(basicForumService.createThread(anyString())).thenReturn(new ForumThread()); - when(basicForumService.createReply(isA(ForumThread.class), isA(User.class), anyString(), anySet())) - .thenAnswer(new Answer() { - @Override - public ForumPost answer(final InvocationOnMock invocation) { - ForumPost forumPost = new ForumPost(); - forumPost.setPostedBy(invocation.getArgument(1, User.class)); - return forumPost; - } - }); - when(reviewerThreadRepository.save(isA(ReviewerThread.class))).thenAnswer(new Answer() { - @Override - public ReviewerThread answer(final InvocationOnMock invocation) { - return invocation.getArgument(0, ReviewerThread.class); + when(basicForumService.createReply(isA(ForumThread.class), isA(User.class), anyString(), anySet())).thenAnswer( + new Answer() { + @Override + public ForumPost answer(final InvocationOnMock invocation) { + ForumPost forumPost = new ForumPost(); + forumPost.setPostedBy(invocation.getArgument(1, User.class)); + return forumPost; + } } - }); + ); + when(reviewerThreadRepository.save(isA(ReviewerThread.class))).thenAnswer( + new Answer() { + @Override + public ReviewerThread answer(final InvocationOnMock invocation) { + return invocation.getArgument(0, ReviewerThread.class); + } + } + ); } @Test @@ -68,7 +74,9 @@ public class ReviewerInteractionServiceImplTest { reviewerInteractionService.reply(project, reviewer, "Rough draft approvad", Collections.emptySet()); - ArgumentCaptor captor = ArgumentCaptor.forClass(NewReviewerInteractionMessage.class); + ArgumentCaptor captor = ArgumentCaptor.forClass( + NewReviewerInteractionMessage.class + ); verify(eventBus).post(captor.capture()); assertThat(captor.getValue().getProject(), is(project)); @@ -82,4 +90,4 @@ public class ReviewerInteractionServiceImplTest { final ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); return Project.builder().title("Project").projectType(bachelor).startDate(LocalDate.now()).build(); } -} \ No newline at end of file +} diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerTest.java index fcaa8a4731..1108562f34 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewerTest.java @@ -1,6 +1,16 @@ package se.su.dsv.scipro.reviewing; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import jakarta.inject.Inject; +import java.io.InputStream; +import java.time.LocalDate; +import java.time.Month; +import java.time.Year; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.file.FileUpload; import se.su.dsv.scipro.project.Project; @@ -12,27 +22,20 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.MutableFixedClock; import se.su.dsv.scipro.util.Either; -import java.io.InputStream; -import java.time.LocalDate; -import java.time.Month; -import java.time.Year; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class ReviewerTest extends ReviewingModuleTest { @Inject MutableFixedClock clock; + @Inject ReviewerAssignmentService reviewerAssignmentService; + @Inject ReviewerCapacityService reviewerCapacityService; + @Inject RoughDraftApprovalService roughDraftApprovalService; + @Inject ReviewerDecisionService reviewerDecisionService; @@ -49,35 +52,39 @@ public class ReviewerTest extends ReviewingModuleTest { reviewerCapacityService.assignTarget(reviewer, target); Either firstReviewRequest = roughDraftApprovalService.requestApproval( - project, - dummyFile(), - "Some comment"); + project, + dummyFile(), + "Some comment" + ); assertTrue(firstReviewRequest.isRight()); - ReviewerAssignment assignment = reviewerAssignmentService.assignReviewer(project,reviewer); + ReviewerAssignment assignment = reviewerAssignmentService.assignReviewer(project, reviewer); assertEquals(ReviewerAssignment.OK, assignment); reviewerDecisionService.reject(firstReviewRequest.right(), "Not good enough", Optional.empty()); Either secondReviewRequest = roughDraftApprovalService.requestApproval( - project, - dummyFile(), - "Some new comment"); + project, + dummyFile(), + "Some new comment" + ); assertTrue(secondReviewRequest.isRight()); // Then - ReviewerCapacityService.RemainingTargets remainingTargets = - reviewerCapacityService.getRemainingTargets(reviewer, target.year()); + ReviewerCapacityService.RemainingTargets remainingTargets = reviewerCapacityService.getRemainingTargets( + reviewer, + target.year() + ); assertEquals(1, remainingTargets.spring()); } private User createUser() { User user = User.builder() - .firstName("Edward") - .lastName("Employee") - .emailAddress("stuart@example.com") - .roles(Set.of(Roles.REVIEWER, Roles.SUPERVISOR)) - .build(); + .firstName("Edward") + .lastName("Employee") + .emailAddress("stuart@example.com") + .roles(Set.of(Roles.REVIEWER, Roles.SUPERVISOR)) + .build(); return save(user); } @@ -88,11 +95,11 @@ public class ReviewerTest extends ReviewingModuleTest { User supervisor = createUser(); Project project = Project.builder() - .title("A project") - .projectType(bachelor) - .startDate(LocalDate.now(clock).minusMonths(1)) - .headSupervisor(supervisor) - .build(); + .title("A project") + .projectType(bachelor) + .startDate(LocalDate.now(clock).minusMonths(1)) + .headSupervisor(supervisor) + .build(); return save(project); } diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingModuleTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingModuleTest.java index ba058fcce1..7417134b07 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingModuleTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingModuleTest.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.reviewing; import se.su.dsv.scipro.test.IntegrationTest; -public abstract class ReviewingModuleTest extends IntegrationTest { -} +public abstract class ReviewingModuleTest extends IntegrationTest {} diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingServiceImplTest.java index dd4ad1a076..47903467c1 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/ReviewingServiceImplTest.java @@ -1,5 +1,17 @@ package se.su.dsv.scipro.reviewing; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -14,26 +26,16 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class ReviewingServiceImplTest extends ReviewingModuleTest { + private static final TestPage ALL = new TestPage(0, Long.MAX_VALUE); @Inject private ReviewingServiceImpl reviewingService; + @Inject private FinalSeminarApprovalServiceImpl finalSeminarApprovalService; + @Inject private RoughDraftApprovalServiceImpl roughDraftApprovalService; @@ -43,15 +45,42 @@ public class ReviewingServiceImplTest extends ReviewingModuleTest { @BeforeEach public void setUp() throws Exception { - reviewer = save(User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build()); - User reviewer2 = save(User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build()); - User headSupervisor = save(User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build()); + reviewer = save( + User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build() + ); + User reviewer2 = save( + User.builder().firstName("Ronny").lastName("Reviewer").emailAddress("reviewer@dsv.su.se").build() + ); + User headSupervisor = save( + User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build() + ); ProjectType bachelor = save(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - project = save(Project.builder().title("My project").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + project = save( + Project.builder() + .title("My project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); project.addReviewer(reviewer); - Project project2 = save(Project.builder().title("My project 2").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + Project project2 = save( + Project.builder() + .title("My project 2") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); project2.addReviewer(reviewer2); - project3 = save(Project.builder().title("My project 3").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(headSupervisor).build()); + project3 = save( + Project.builder() + .title("My project 3") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build() + ); project3.addReviewer(reviewer); } @@ -71,13 +100,19 @@ public class ReviewingServiceImplTest extends ReviewingModuleTest { @Test public void find_undecided() { finalSeminarApprovalService.requestApproval(project, createFileUpload(), "test"); - assertThat(reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL), ALL), hasItem(where(Decision::getReviewerApproval, instanceOf(FinalSeminarApproval.class)))); + assertThat( + reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL), ALL), + hasItem(where(Decision::getReviewerApproval, instanceOf(FinalSeminarApproval.class))) + ); } @Test public void find_undecided_rough_draft_approvals() { roughDraftApprovalService.requestApproval(project, createFileUpload(), "test"); - assertThat(reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), ALL), hasItem(where(Decision::getReviewerApproval, instanceOf(RoughDraftApproval.class)))); + assertThat( + reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), ALL), + hasItem(where(Decision::getReviewerApproval, instanceOf(RoughDraftApproval.class))) + ); } @Test @@ -89,43 +124,69 @@ public class ReviewingServiceImplTest extends ReviewingModuleTest { @Test public void back_and_forth() { assertTrue(finalSeminarApprovalService.requiresUpload(project)); - Either first = finalSeminarApprovalService.requestApproval(project, createFileUpload(), "test"); + Either first = finalSeminarApprovalService.requestApproval( + project, + createFileUpload(), + "test" + ); assertFalse(finalSeminarApprovalService.requiresUpload(project)); - first.foreach(firstFinalSeminarApproval -> reviewingService.reject(firstFinalSeminarApproval, "Very bad", Optional.of(createFileUpload()))); + first.foreach(firstFinalSeminarApproval -> + reviewingService.reject(firstFinalSeminarApproval, "Very bad", Optional.of(createFileUpload())) + ); assertTrue(finalSeminarApprovalService.requiresUpload(project)); - Either second = finalSeminarApprovalService.requestApproval(project, createFileUpload(), "test"); + Either second = finalSeminarApprovalService.requestApproval( + project, + createFileUpload(), + "test" + ); assertFalse(finalSeminarApprovalService.requiresUpload(project)); - second.foreach(secondFinalSeminarApproval -> reviewingService.approve(secondFinalSeminarApproval, "Very good", Optional.empty())); + second.foreach(secondFinalSeminarApproval -> + reviewingService.approve(secondFinalSeminarApproval, "Very good", Optional.empty()) + ); assertFalse(finalSeminarApprovalService.requiresUpload(project)); } @Test public void only_fetches_my_reviews() { - Either myRequest = - roughDraftApprovalService.requestApproval(project, createFileUpload(), "my request"); + Either myRequest = roughDraftApprovalService.requestApproval( + project, + createFileUpload(), + "my request" + ); assertTrue(myRequest.isRight()); - List requests = reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), ALL); + List requests = reviewingService.findAllDecisions( + getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), + ALL + ); assertEquals(1, requests.size()); } @Test public void sort_by_requested() { - Either request1 = - roughDraftApprovalService.requestApproval(project, createFileUpload(), "request 1"); + Either request1 = roughDraftApprovalService.requestApproval( + project, + createFileUpload(), + "request 1" + ); assertTrue(request1.isRight()); - Either request2 = - roughDraftApprovalService.requestApproval(project3, createFileUpload(), "request 2"); + Either request2 = roughDraftApprovalService.requestApproval( + project3, + createFileUpload(), + "request 2" + ); assertTrue(request2.isRight()); var sortByRequested = new Page.Sort<>(MyReviewService.Sort.TITLE, Page.Direction.DESCENDING); TestPage page = new TestPage(0, Long.MAX_VALUE, sortByRequested); - List requests = - reviewingService.findAllDecisions(getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), page); + List requests = reviewingService.findAllDecisions( + getFilter(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), + page + ); assertEquals(2, requests.size()); assertEquals(request2.right(), requests.get(0).getReviewerApproval()); @@ -153,8 +214,7 @@ public class ReviewingServiceImplTest extends ReviewingModuleTest { @Override public void describeTo(Description description) { - description.appendText("an object where ") - .appendDescriptionOf(matcher); + description.appendText("an object where ").appendDescriptionOf(matcher); } }; } diff --git a/core/src/test/java/se/su/dsv/scipro/reviewing/WithStatus.java b/core/src/test/java/se/su/dsv/scipro/reviewing/WithStatus.java index f75202cdeb..c9eb318315 100644 --- a/core/src/test/java/se/su/dsv/scipro/reviewing/WithStatus.java +++ b/core/src/test/java/se/su/dsv/scipro/reviewing/WithStatus.java @@ -5,6 +5,7 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class WithStatus extends TypeSafeMatcher { + private final Status status; private WithStatus(final Status status) { diff --git a/core/src/test/java/se/su/dsv/scipro/security/auth/LocalAuthenticationTest.java b/core/src/test/java/se/su/dsv/scipro/security/auth/LocalAuthenticationTest.java index d752c73cff..9ebffb3b4a 100644 --- a/core/src/test/java/se/su/dsv/scipro/security/auth/LocalAuthenticationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/security/auth/LocalAuthenticationTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.security.auth; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.system.Password; @@ -8,12 +12,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.Username; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class LocalAuthenticationTest extends IntegrationTest { + public static final char[] TEST_PASSWORD = "s3cre7".toCharArray(); public static final String TEST_USERNAME = "kalle@dsv.su.se"; diff --git a/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImplTest.java index 50594a1acd..25cbc2ba53 100644 --- a/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/SupervisorServiceImplTest.java @@ -1,26 +1,26 @@ package se.su.dsv.scipro.springdata.serviceimpls; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static se.su.dsv.scipro.springdata.services.SupervisorService.FilterParams; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.springdata.services.SupervisorService; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.Username; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static se.su.dsv.scipro.springdata.services.SupervisorService.FilterParams; - public class SupervisorServiceImplTest extends IntegrationTest { + @Inject private SupervisorService supervisorService; diff --git a/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImplIntegrationTest.java index 69a22cdbaa..2c9ff21bf0 100644 --- a/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/springdata/serviceimpls/UserProfileServiceImplIntegrationTest.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.springdata.serviceimpls; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class UserProfileServiceImplIntegrationTest extends IntegrationTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/system/EventServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/system/EventServiceImplTest.java index 5154bddd10..1033b81c2d 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/EventServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/EventServiceImplTest.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.system; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; - import static org.junit.jupiter.api.Assertions.assertNotNull; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; + public class EventServiceImplTest extends IntegrationTest { + @Inject private EventServiceImpl eventService; diff --git a/core/src/test/java/se/su/dsv/scipro/system/PasswordServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/system/PasswordServiceImplTest.java index 899471ba99..bd766fdc31 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/PasswordServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/PasswordServiceImplTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.system; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; @@ -8,16 +12,14 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.test.UserBuilder; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class PasswordServiceImplTest { public static final String EMPTY_STRING = ""; + @Mock private PasswordRepo passwordRepo; + @InjectMocks private PasswordServiceImpl passwordService; @@ -40,7 +42,6 @@ public class PasswordServiceImplTest { @Test public void does_not_update_password_if_not_provided() { - passwordService.updatePassword(new User(), EMPTY_STRING); verify(passwordRepo, never()).save(any(Password.class)); diff --git a/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplIntegrationTest.java index 835a575d2a..90802bb40b 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplIntegrationTest.java @@ -1,20 +1,19 @@ package se.su.dsv.scipro.system; -import org.hamcrest.CoreMatchers; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; +import org.hamcrest.CoreMatchers; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.test.IntegrationTest; + public class ProjectTypeServiceImplIntegrationTest extends IntegrationTest { @Inject @@ -45,12 +44,28 @@ public class ProjectTypeServiceImplIntegrationTest extends IntegrationTest { @Test public void find_projects_types_from_supervisors_active_projects() { - User supervisor = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User supervisor = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); ProjectType bachelor = createProjectType(DegreeType.BACHELOR, "bachelor"); createProjectType(DegreeType.MASTER, "master"); - save(Project.builder().title("bachelor").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(supervisor).build()); - save(Project.builder().title("another bachelor").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(supervisor).build()); + save( + Project.builder() + .title("bachelor") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build() + ); + save( + Project.builder() + .title("another bachelor") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build() + ); List projectTypes = projectTypeService.findBySupervisorProjects(supervisor); @@ -60,12 +75,28 @@ public class ProjectTypeServiceImplIntegrationTest extends IntegrationTest { @Test public void find_projects_types_from_supervisors_active_projects_count_following_projects_as_well() { - User supervisor = save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + User supervisor = save( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); ProjectType bachelor = createProjectType(DegreeType.BACHELOR, "bachelor"); ProjectType master = createProjectType(DegreeType.MASTER, "master"); - save(Project.builder().title("bachelor").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(supervisor).build()); - Project reviewingProject = Project.builder().title("another bachelor").projectType(master).startDate(LocalDate.now()).headSupervisor(save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build())).build(); + save( + Project.builder() + .title("bachelor") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build() + ); + Project reviewingProject = Project.builder() + .title("another bachelor") + .projectType(master) + .startDate(LocalDate.now()) + .headSupervisor( + save(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()) + ) + .build(); reviewingProject.addReviewer(supervisor); save(reviewingProject); diff --git a/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplTest.java index 90f1502cb4..7ae179ddb1 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/ProjectTypeServiceImplTest.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.system; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; + public class ProjectTypeServiceImplTest extends IntegrationTest { + @Inject private ProjectTypeServiceImpl projectTypeService; diff --git a/core/src/test/java/se/su/dsv/scipro/system/ResearchAreaServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/system/ResearchAreaServiceImplIntegrationTest.java index a575b2a884..0807f76e39 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/ResearchAreaServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/ResearchAreaServiceImplIntegrationTest.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.system; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; - -import jakarta.inject.Inject; -import java.util.List; - import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; +import jakarta.inject.Inject; +import java.util.List; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; + public class ResearchAreaServiceImplIntegrationTest extends IntegrationTest { @Inject @@ -21,7 +20,11 @@ public class ResearchAreaServiceImplIntegrationTest extends IntegrationTest { Long identifier = 1L; ResearchArea researchArea = createResearchArea(identifier, "Some title"); - ResearchArea created = researchAreaService.updateExternalResearchArea(researchArea.getIdentifier(), researchArea.getTitle(), !researchArea.isDeleted()); + ResearchArea created = researchAreaService.updateExternalResearchArea( + researchArea.getIdentifier(), + researchArea.getTitle(), + !researchArea.isDeleted() + ); assertEquals(1, researchAreaService.count()); assertNotNull(created); assertNotNull(created.getId()); @@ -35,7 +38,11 @@ public class ResearchAreaServiceImplIntegrationTest extends IntegrationTest { String title = "New title"; - ResearchArea updated = researchAreaService.updateExternalResearchArea(old.getIdentifier(), title, !old.isDeleted()); + ResearchArea updated = researchAreaService.updateExternalResearchArea( + old.getIdentifier(), + title, + !old.isDeleted() + ); assertEquals(title, updated.getTitle()); assertEquals(1, researchAreaService.count()); diff --git a/core/src/test/java/se/su/dsv/scipro/system/UserServiceImplIntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/system/UserServiceImplIntegrationTest.java index 506e739ca0..fe669d7623 100644 --- a/core/src/test/java/se/su/dsv/scipro/system/UserServiceImplIntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/system/UserServiceImplIntegrationTest.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.system; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import jakarta.inject.Inject; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.test.IntegrationTest; -import jakarta.inject.Inject; -import java.util.Collections; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - public class UserServiceImplIntegrationTest extends IntegrationTest { @Inject diff --git a/core/src/test/java/se/su/dsv/scipro/test/Dates.java b/core/src/test/java/se/su/dsv/scipro/test/Dates.java index 54826ce825..1a6280a4b8 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/Dates.java +++ b/core/src/test/java/se/su/dsv/scipro/test/Dates.java @@ -6,6 +6,7 @@ import java.time.Period; import java.util.Date; public class Dates { + public static Date yesterday() { return Date.from(Instant.now().minus(Period.ofDays(1))); } diff --git a/core/src/test/java/se/su/dsv/scipro/test/DomainObjects.java b/core/src/test/java/se/su/dsv/scipro/test/DomainObjects.java index 0d04bc0568..c3f7b6ed0b 100755 --- a/core/src/test/java/se/su/dsv/scipro/test/DomainObjects.java +++ b/core/src/test/java/se/su/dsv/scipro/test/DomainObjects.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.test; +import java.lang.reflect.Field; import org.mockito.Mockito; import se.su.dsv.scipro.system.DomainObject; -import java.lang.reflect.Field; - public final class DomainObjects { - private DomainObjects() { } + private DomainObjects() {} public static T injectId(T object, Long id) { try { @@ -16,16 +15,13 @@ public final class DomainObjects { Field idField = clazz.getDeclaredField("id"); idField.setAccessible(true); idField.set(object, id); - } catch (NoSuchFieldException ignored) { - } + } catch (NoSuchFieldException ignored) {} } - } - catch (Exception ex) { + } catch (Exception ex) { object = Mockito.spy(object); Mockito.when(object.getId()).thenReturn(id); ex.printStackTrace(); } return object; } - } diff --git a/core/src/test/java/se/su/dsv/scipro/test/ForumBuilder.java b/core/src/test/java/se/su/dsv/scipro/test/ForumBuilder.java index 941b18b95c..e2f4a96813 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/ForumBuilder.java +++ b/core/src/test/java/se/su/dsv/scipro/test/ForumBuilder.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.test; +import java.time.LocalDate; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; @@ -7,8 +8,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - public class ForumBuilder { private static long ID = 1; @@ -28,7 +27,11 @@ public class ForumBuilder { public ProjectThread createThread() { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); - Project project = Project.builder().title("Some title").projectType(projectType).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("Some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .build(); project.setId(1L); ForumThread forumThread = new ForumThread(); forumThread.setSubject("Test subject"); diff --git a/core/src/test/java/se/su/dsv/scipro/test/InMemoryFileStore.java b/core/src/test/java/se/su/dsv/scipro/test/InMemoryFileStore.java index ea6221d811..52291710ad 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/InMemoryFileStore.java +++ b/core/src/test/java/se/su/dsv/scipro/test/InMemoryFileStore.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.test; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileStore; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.*; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileStore; public class InMemoryFileStore implements FileStore { + private Map fileData = new HashMap<>(); @Override diff --git a/core/src/test/java/se/su/dsv/scipro/test/InstanceProvider.java b/core/src/test/java/se/su/dsv/scipro/test/InstanceProvider.java index 5228f4755f..6398c9f1c0 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/InstanceProvider.java +++ b/core/src/test/java/se/su/dsv/scipro/test/InstanceProvider.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.test; import jakarta.inject.Provider; public class InstanceProvider implements Provider { + private final T instance; public InstanceProvider(T instance) { diff --git a/core/src/test/java/se/su/dsv/scipro/test/IntegrationTest.java b/core/src/test/java/se/su/dsv/scipro/test/IntegrationTest.java index 837f58dc90..10a141d80a 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/IntegrationTest.java +++ b/core/src/test/java/se/su/dsv/scipro/test/IntegrationTest.java @@ -1,5 +1,3 @@ package se.su.dsv.scipro.test; -public abstract class IntegrationTest extends SpringTest { - -} +public abstract class IntegrationTest extends SpringTest {} diff --git a/core/src/test/java/se/su/dsv/scipro/test/Matchers.java b/core/src/test/java/se/su/dsv/scipro/test/Matchers.java index 3e6907e137..e1b125f7c5 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/Matchers.java +++ b/core/src/test/java/se/su/dsv/scipro/test/Matchers.java @@ -6,24 +6,26 @@ import org.hamcrest.TypeSafeDiagnosingMatcher; import se.su.dsv.scipro.util.Either; public final class Matchers { + public static Matcher> isRight(Matcher subMatcher) { return new TypeSafeDiagnosingMatcher>() { @Override protected boolean matchesSafely(final Either item, final Description mismatchDescription) { return item.fold( - e -> { - mismatchDescription.appendText("Left(").appendValue(e).appendText(")"); + e -> { + mismatchDescription.appendText("Left(").appendValue(e).appendText(")"); + return false; + }, + a -> { + if (!subMatcher.matches(a)) { + mismatchDescription.appendText("Right("); + subMatcher.describeMismatch(a, mismatchDescription); + mismatchDescription.appendText(")"); return false; - }, - a -> { - if (!subMatcher.matches(a)) { - mismatchDescription.appendText("Right("); - subMatcher.describeMismatch(a, mismatchDescription); - mismatchDescription.appendText(")"); - return false; - } - return true; - }); + } + return true; + } + ); } @Override @@ -38,19 +40,20 @@ public final class Matchers { @Override protected boolean matchesSafely(final Either item, final Description mismatchDescription) { return item.fold( - e -> { - if (!subMatcher.matches(e)) { - mismatchDescription.appendText("Left("); - subMatcher.describeMismatch(e, mismatchDescription); - mismatchDescription.appendText(")"); - return false; - } - return true; - }, - a -> { - mismatchDescription.appendText("Right(").appendValue(a).appendText(")"); + e -> { + if (!subMatcher.matches(e)) { + mismatchDescription.appendText("Left("); + subMatcher.describeMismatch(e, mismatchDescription); + mismatchDescription.appendText(")"); return false; - }); + } + return true; + }, + a -> { + mismatchDescription.appendText("Right(").appendValue(a).appendText(")"); + return false; + } + ); } @Override @@ -59,5 +62,4 @@ public final class Matchers { } }; } - } diff --git a/core/src/test/java/se/su/dsv/scipro/test/MutableFixedClock.java b/core/src/test/java/se/su/dsv/scipro/test/MutableFixedClock.java index 29777648c3..e6c22e9a84 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/MutableFixedClock.java +++ b/core/src/test/java/se/su/dsv/scipro/test/MutableFixedClock.java @@ -7,6 +7,7 @@ import java.time.ZoneId; import java.util.*; public class MutableFixedClock extends Clock { + private final Clock fallback; private Instant fixed; diff --git a/core/src/test/java/se/su/dsv/scipro/test/ObjectMother.java b/core/src/test/java/se/su/dsv/scipro/test/ObjectMother.java index a0691540c3..7b6fade493 100755 --- a/core/src/test/java/se/su/dsv/scipro/test/ObjectMother.java +++ b/core/src/test/java/se/su/dsv/scipro/test/ObjectMother.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.test; +import java.lang.reflect.Field; +import java.time.LocalDate; +import java.util.*; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.match.Idea; import se.su.dsv.scipro.match.IdeaParticipation; @@ -9,10 +12,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.lang.reflect.Field; -import java.time.LocalDate; -import java.util.*; - /** * @deprecated global mutable state that can cause issues depending on the order the tests are run */ @@ -21,16 +20,24 @@ public class ObjectMother { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); public static final ProjectType MASTER = new ProjectType(DegreeType.MASTER, "Master", "Master"); - public static final User SOME_USER = User.builder().firstName("Kalle").lastName("Testare").emailAddress("kalle@dsv.su.se").build(); + public static final User SOME_USER = User.builder() + .firstName("Kalle") + .lastName("Testare") + .emailAddress("kalle@dsv.su.se") + .build(); public static final Project SOME_PROJECT = Project.builder() - .title("Some title") - .projectType(BACHELOR) - .startDate(LocalDate.now()) - .headSupervisor(User.builder().firstName("Foo").lastName("Bar").emailAddress("foo@dsv.su.se").build()) - .build(); + .title("Some title") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .headSupervisor(User.builder().firstName("Foo").lastName("Bar").emailAddress("foo@dsv.su.se").build()) + .build(); - public static final Project SOME_MASTER_PROJECT = Project.builder().title("Some title").projectType(MASTER).startDate(LocalDate.now()).build(); + public static final Project SOME_MASTER_PROJECT = Project.builder() + .title("Some title") + .projectType(MASTER) + .startDate(LocalDate.now()) + .build(); static { DomainObjects.injectId(BACHELOR, 1L); @@ -51,7 +58,8 @@ public class ObjectMother { return dom; } - private static abstract class AbstractBuilder { + private abstract static class AbstractBuilder { + protected Long id; protected abstract T build(); @@ -62,9 +70,14 @@ public class ObjectMother { } public static class IdeaBuilder extends AbstractBuilder { + public static final String TITLE = "[How A affects B in C]"; public static final User SUPERVISOR = new UserBuilder().setId(731L).create(); - public static final ProjectType PROJECT_TYPE = new ProjectType(ProjectType.BACHELOR, "Bachelor", "[Bachelor thesis]"); + public static final ProjectType PROJECT_TYPE = new ProjectType( + ProjectType.BACHELOR, + "Bachelor", + "[Bachelor thesis]" + ); public static final ApplicationPeriod APPLICATION_PERIOD = new ApplicationPeriod("[Test period]"); public static final Match MATCH = new Match(); @@ -110,6 +123,7 @@ public class ObjectMother { } public static class _User { + public static final String FIRST_NAME = "TEST_USER_FIRST_NAME"; public static final String LAST_NAME = "TEST_USER_LAST_NAME"; @@ -126,29 +140,48 @@ public class ObjectMother { } public static class _Project { + public static Project create(Long id) { Project project = get_with_id(new Project(), id); project.setTitle("test project"); project.setProjectType(new ProjectType(ProjectType.BACHELOR, "Bachelor", "tt")); - User headSupervisorUser = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 6L); + User headSupervisorUser = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 6L + ); project.setHeadSupervisor(headSupervisorUser); - User author1 = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 2L); + User author1 = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 2L + ); author1.setFirstName("Kalle"); author1.setLastName("Testare"); author1.setEmailAddress("kalle@dsv.su.se"); - User author2 = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 3L); + User author2 = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 3L + ); SortedSet authors = new TreeSet<>(new User.ByNameComparator()); authors.add(author1); authors.add(author2); project.setProjectParticipants(authors); - User reviewer1 = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 4L); + User reviewer1 = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 4L + ); - User reviewer2 = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 5L); + User reviewer2 = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 5L + ); - User cosupervisor1 = get_with_id(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), 8L); + User cosupervisor1 = get_with_id( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(), + 8L + ); project.addReviewer(reviewer1); project.addReviewer(reviewer2); diff --git a/core/src/test/java/se/su/dsv/scipro/test/SeminarBuilder.java b/core/src/test/java/se/su/dsv/scipro/test/SeminarBuilder.java index bc0eb20355..16ff430e3e 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/SeminarBuilder.java +++ b/core/src/test/java/se/su/dsv/scipro/test/SeminarBuilder.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.test; +import java.time.LocalDate; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.finalseminar.FinalSeminar; @@ -7,8 +8,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - public class SeminarBuilder { public FinalSeminar create() { @@ -21,13 +20,12 @@ public class SeminarBuilder { if (seminar.getProject() == null) { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); Project project = Project.builder() - .title("Some title") - .projectType(projectType) - .startDate(LocalDate.now()) - .build(); + .title("Some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .build(); seminar.setProject(project); } return seminar; } - } diff --git a/core/src/test/java/se/su/dsv/scipro/test/SpringTest.java b/core/src/test/java/se/su/dsv/scipro/test/SpringTest.java index eae4492265..2b68b55008 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/SpringTest.java +++ b/core/src/test/java/se/su/dsv/scipro/test/SpringTest.java @@ -4,23 +4,22 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.Persistence; +import java.time.Clock; +import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; - import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import se.su.dsv.scipro.CoreConfig; +import se.su.dsv.scipro.RepositoryConfiguration; import se.su.dsv.scipro.profiles.CurrentProfile; import se.su.dsv.scipro.sukat.Sukat; import se.su.dsv.scipro.system.CurrentUser; -import se.su.dsv.scipro.CoreConfig; -import se.su.dsv.scipro.RepositoryConfiguration; - -import java.time.Clock; -import java.util.Optional; public abstract class SpringTest { + private EntityManager entityManager; private EntityManagerFactory entityManagerFactory; @@ -32,13 +31,12 @@ public abstract class SpringTest { transaction.begin(); transaction.setRollbackOnly(); - AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); + AnnotationConfigApplicationContext annotationConfigApplicationContext = + new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(TestContext.class); - annotationConfigApplicationContext.getBeanFactory() - .registerSingleton("entityManager", this.entityManager); + annotationConfigApplicationContext.getBeanFactory().registerSingleton("entityManager", this.entityManager); annotationConfigApplicationContext.refresh(); - annotationConfigApplicationContext.getAutowireCapableBeanFactory() - .autowireBean(this); + annotationConfigApplicationContext.getAutowireCapableBeanFactory().autowireBean(this); } @AfterEach @@ -52,16 +50,16 @@ public abstract class SpringTest { EntityManager em = entityManager; if (em.contains(entity)) { return em.merge(entity); - } - else { + } else { em.persist(entity); return entity; } } @Configuration(proxyBeanMethods = false) - @Import({CoreConfig.class, RepositoryConfiguration.class}) + @Import({ CoreConfig.class, RepositoryConfiguration.class }) public static class TestContext { + @Bean public InMemoryFileStore inMemoryFileStore() { return new InMemoryFileStore(); @@ -74,7 +72,7 @@ public abstract class SpringTest { @Bean public Sukat sukat() { - return (username) -> Optional.empty(); + return username -> Optional.empty(); } @Bean diff --git a/core/src/test/java/se/su/dsv/scipro/test/StreamingUpload.java b/core/src/test/java/se/su/dsv/scipro/test/StreamingUpload.java index 163b71cbaf..492eb54391 100644 --- a/core/src/test/java/se/su/dsv/scipro/test/StreamingUpload.java +++ b/core/src/test/java/se/su/dsv/scipro/test/StreamingUpload.java @@ -1,19 +1,25 @@ package se.su.dsv.scipro.test; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.system.User; - import java.io.InputStream; import java.util.function.Function; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.system.User; public class StreamingUpload implements FileUpload { + private final String fileName; private final String contentType; private final User uploader; private final long size; private final InputStream is; - public StreamingUpload(final String fileName, final String contentType, final User uploader, final long size, final InputStream is) { + public StreamingUpload( + final String fileName, + final String contentType, + final User uploader, + final long size, + final InputStream is + ) { this.fileName = fileName; this.contentType = contentType; this.uploader = uploader; diff --git a/core/src/test/java/se/su/dsv/scipro/workerthreads/DailyScheduleTest.java b/core/src/test/java/se/su/dsv/scipro/workerthreads/DailyScheduleTest.java index 0c507f6501..0b06bf788b 100644 --- a/core/src/test/java/se/su/dsv/scipro/workerthreads/DailyScheduleTest.java +++ b/core/src/test/java/se/su/dsv/scipro/workerthreads/DailyScheduleTest.java @@ -1,11 +1,12 @@ package se.su.dsv.scipro.workerthreads; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static se.su.dsv.scipro.workerthreads.DailySchedule.minutesUntil; +import org.junit.jupiter.api.Test; + public class DailyScheduleTest { + @Test public void minutes_until_over_midnight() { assertEquals(45, minutesUntil(0, 15, 23, 30)); diff --git a/core/src/test/java/se/su/dsv/scipro/workerthreads/RepeatingScheduleTest.java b/core/src/test/java/se/su/dsv/scipro/workerthreads/RepeatingScheduleTest.java index 2bc32d7d8f..ca1501e43a 100644 --- a/core/src/test/java/se/su/dsv/scipro/workerthreads/RepeatingScheduleTest.java +++ b/core/src/test/java/se/su/dsv/scipro/workerthreads/RepeatingScheduleTest.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.workerthreads; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + public class RepeatingScheduleTest { + @Test public void delay_is_equal_to_period() { RepeatingSchedule repeatingSchedule = new RepeatingSchedule(7L, TimeUnit.HOURS); diff --git a/core/src/test/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImplTest.java b/core/src/test/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImplTest.java index f09cba2817..3aa3271c9d 100644 --- a/core/src/test/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImplTest.java +++ b/core/src/test/java/se/su/dsv/scipro/workerthreads/WorkerDataServiceImplTest.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.workerthreads; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.test.IntegrationTest; +import static org.junit.jupiter.api.Assertions.assertEquals; import jakarta.inject.Inject; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.test.IntegrationTest; public class WorkerDataServiceImplTest extends IntegrationTest { diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ExternalImporter.java b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ExternalImporter.java index 010b65ee81..642668a636 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ExternalImporter.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ExternalImporter.java @@ -4,9 +4,7 @@ package se.su.dsv.scipro.daisyExternal; * Specifies interaction of an importing service component. */ public interface ExternalImporter { - void importSupervisorUnits(); void importSupervisorActiveStatus(); } - diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ImporterTransactions.java b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ImporterTransactions.java index ee7924a069..bbf5af7707 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ImporterTransactions.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/ImporterTransactions.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.daisyExternal; +import java.util.Map; import se.su.dsv.scipro.io.dto.Person; import se.su.dsv.scipro.io.dto.Program; import se.su.dsv.scipro.io.dto.Thesis; import se.su.dsv.scipro.system.User; -import java.util.Map; - public interface ImporterTransactions { User importPerson(Person person, final Map programCache); User importStudent(Person person, final Map programCache); diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImpl.java b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImpl.java index 3f78ffd415..6613b2e597 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImpl.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImpl.java @@ -1,9 +1,11 @@ package se.su.dsv.scipro.daisyExternal.impl; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import jakarta.ws.rs.ClientErrorException; +import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.daisyExternal.ExternalImporter; import se.su.dsv.scipro.daisyExternal.ImporterTransactions; import se.su.dsv.scipro.daisyExternal.exceptions.ExternalImportException; @@ -14,19 +16,17 @@ import se.su.dsv.scipro.io.dto.Thesis; import se.su.dsv.scipro.io.dto.Unit; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.springdata.services.UnitService; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserImportService; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import jakarta.ws.rs.ClientErrorException; -import java.util.*; - /** * Importer implementation, uses standard HTTP requests and Json-wrappers. */ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportService { + public static final Integer DSV = 4; private static final Logger LOGGER = LoggerFactory.getLogger(ExternalImporterDaisyImpl.class); @@ -38,10 +38,11 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe @Inject public ExternalImporterDaisyImpl( - UserService userService, - UnitService unitService, - DaisyAPI client, - ImporterTransactions importerTransactions) { + UserService userService, + UnitService unitService, + DaisyAPI client, + ImporterTransactions importerTransactions + ) { this.userService = userService; this.unitService = unitService; this.client = client; @@ -50,11 +51,12 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe @Override public List search(String searchTerm) { - return client.findByPersonnummer(searchTerm) - .stream() - .filter(person -> !person.isDeceased()) - .map(this::toImportableUser) - .toList(); + return client + .findByPersonnummer(searchTerm) + .stream() + .filter(person -> !person.isDeceased()) + .map(this::toImportableUser) + .toList(); } private ImportableUser toImportableUser(Person person) { @@ -62,6 +64,7 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe } private static class DaisyImportableUser extends ImportableUser { + public DaisyImportableUser(Person person) { super(person.getFirstName(), person.getLastName(), person.getEmail(), person.getId()); } @@ -70,8 +73,7 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe @Override public void importUser(ImportableUser importableUser) { if (importableUser instanceof DaisyImportableUser) { - client.findPersonById(importableUser.getId()) - .ifPresent(this::importPerson); + client.findPersonById(importableUser.getId()).ifPresent(this::importPerson); } } @@ -87,7 +89,7 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe private User importPerson(Person person) { User user; - if (client.getSupervisors(DSV).contains(person)){ + if (client.getSupervisors(DSV).contains(person)) { user = importerTransactions.importSupervisor(person, new HashMap<>()); } else { user = importerTransactions.importStudent(person, new HashMap<>()); @@ -153,7 +155,9 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe //Remove units from supervisors that is not in the remote set. for (User supervisor : currentSupervisors) { if (!supervisorsWithRemoteUnit.contains(supervisor)) { - LOGGER.debug(supervisor.getFullName() + " does not have a remote unit. Searching for local units to remove."); + LOGGER.debug( + supervisor.getFullName() + " does not have a remote unit. Searching for local units to remove." + ); supervisor.setUnit(null); LOGGER.debug("Removed units from: " + supervisor.getFullName()); } @@ -161,7 +165,6 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe } private void addUnexistingUnitsAsUnits(final Set unitsFromDTO) { - Set remoteUnits = new HashSet<>(unitsFromDTO); //Add units to database @@ -200,10 +203,10 @@ public class ExternalImporterDaisyImpl implements ExternalImporter, UserImportSe final List employees = client.listEmployees(DSV); for (User supervisor : supervisors) { final boolean affiliatedWithDSV = employees - .stream() - .map(Employee::getPerson) - .map(Person::getId) - .anyMatch(id -> Objects.equals(id, supervisor.getIdentifier())); + .stream() + .map(Employee::getPerson) + .map(Person::getId) + .anyMatch(id -> Objects.equals(id, supervisor.getIdentifier())); supervisor.setActiveAsSupervisor(affiliatedWithDSV); userService.save(supervisor); } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImpl.java b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImpl.java index 9e6ea05554..0eca54eadf 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImpl.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImpl.java @@ -1,26 +1,25 @@ package se.su.dsv.scipro.daisyExternal.impl; +import jakarta.inject.Inject; +import jakarta.inject.Named; import jakarta.transaction.Transactional; import jakarta.ws.rs.core.Response; +import java.util.*; +import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.ImporterTransactions; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; -import se.su.dsv.scipro.io.dto.ResearchArea; import se.su.dsv.scipro.io.dto.*; +import se.su.dsv.scipro.io.dto.ResearchArea; import se.su.dsv.scipro.match.ProgramService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.Program; import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.system.Program; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import java.util.*; -import java.util.stream.Stream; - @Named public class ImporterTransactionsImpl implements ImporterTransactions { @@ -37,12 +36,13 @@ public class ImporterTransactionsImpl implements ImporterTransactions { @Inject public ImporterTransactionsImpl( - UserService userService, - ResearchAreaService researchAreaService, - ProjectService projectService, - UserNameService userNameService, - DaisyAPI client, - ProgramService programService) { + UserService userService, + ResearchAreaService researchAreaService, + ProjectService projectService, + UserNameService userNameService, + DaisyAPI client, + ProgramService programService + ) { this.userService = userService; this.researchAreaService = researchAreaService; this.projectService = projectService; @@ -62,25 +62,25 @@ public class ImporterTransactionsImpl implements ImporterTransactions { private void importAuthorLevel(final User user, final Map programCache) { final Stream> semesterPrograms = client - .getProgramAdmissionsForStudent(user.getIdentifier()) - .stream() - .map(pa -> new Pair<>(pa.getAdmissionSemester(), pa.getProgram().getId())); - final List courseRegistrations = client - .getCourseRegistrationsForStudent(user.getIdentifier()); + .getProgramAdmissionsForStudent(user.getIdentifier()) + .stream() + .map(pa -> new Pair<>(pa.getAdmissionSemester(), pa.getProgram().getId())); + final List courseRegistrations = client.getCourseRegistrationsForStudent( + user.getIdentifier() + ); final Stream> registrationSemesters = courseRegistrations - .stream() - .filter(cr -> cr.getProgramId() != null) - .map(cr -> new Pair<>(cr.getSemester(), cr.getProgramId())); - final DegreeType latestLevel = Stream - .concat(semesterPrograms, registrationSemesters) - .map(pair -> new Pair<>(pair.getHead(), getProgram(pair.getTail(), programCache))) - .filter(pair -> pair.getTail().getType() != null) - .max(Comparator.comparing(Pair::getHead)) - .map(Pair::getTail) - .map(se.su.dsv.scipro.io.dto.Program::getType) - .map(this::toDegreeType) - .or(() -> getOverrideBasedOnCourse(courseRegistrations)) - .orElse(DegreeType.BACHELOR); + .stream() + .filter(cr -> cr.getProgramId() != null) + .map(cr -> new Pair<>(cr.getSemester(), cr.getProgramId())); + final DegreeType latestLevel = Stream.concat(semesterPrograms, registrationSemesters) + .map(pair -> new Pair<>(pair.getHead(), getProgram(pair.getTail(), programCache))) + .filter(pair -> pair.getTail().getType() != null) + .max(Comparator.comparing(Pair::getHead)) + .map(Pair::getTail) + .map(se.su.dsv.scipro.io.dto.Program::getType) + .map(this::toDegreeType) + .or(() -> getOverrideBasedOnCourse(courseRegistrations)) + .orElse(DegreeType.BACHELOR); final DegreeType oldLevel = user.getDegreeType(); user.setDegreeType(latestLevel); @@ -89,8 +89,11 @@ public class ImporterTransactionsImpl implements ImporterTransactions { } } - private se.su.dsv.scipro.io.dto.Program getProgram(Integer programId, final Map programCache) { - return programCache.computeIfAbsent(programId, client::getProgram); + private se.su.dsv.scipro.io.dto.Program getProgram( + Integer programId, + final Map programCache + ) { + return programCache.computeIfAbsent(programId, client::getProgram); } private DegreeType toDegreeType(ProgramType programType) { @@ -125,11 +128,17 @@ public class ImporterTransactionsImpl implements ImporterTransactions { return user; } - private void importProgramsAndMakeStudent(Person person, User user, final Map programCache) { + private void importProgramsAndMakeStudent( + Person person, + User user, + final Map programCache + ) { Response response = client.getStudent(person.getId()); if (response.getStatus() == Response.Status.OK.getStatusCode()) { se.su.dsv.scipro.io.dto.Student student = response.readEntity(se.su.dsv.scipro.io.dto.Student.class); - for (StudentProgramAdmission admission : client.getProgramAdmissionsForStudent(student.getPerson().getId())) { + for (StudentProgramAdmission admission : client.getProgramAdmissionsForStudent( + student.getPerson().getId() + )) { Program program = importProgram(admission.getProgram().getId(), programCache); user.addProgram(program); } @@ -139,7 +148,12 @@ public class ImporterTransactionsImpl implements ImporterTransactions { private Program importProgram(Integer id, final Map programCache) { se.su.dsv.scipro.io.dto.Program program = getProgram(id, programCache); - return programService.updateExternalProgram(program.getId(), program.getName(), program.getNameEn(), program.getCode()); + return programService.updateExternalProgram( + program.getId(), + program.getName(), + program.getNameEn(), + program.getCode() + ); } private void importUsernames(Person person, User local) { @@ -162,23 +176,31 @@ public class ImporterTransactionsImpl implements ImporterTransactions { } private void importResearchAreasAndMakeSupervisor(Person person, User employee) { - List researchAreas = client.getResearchAreas(person.getId()) - .stream() - .filter(ResearchArea::isActive) - .toList(); + List researchAreas = client + .getResearchAreas(person.getId()) + .stream() + .filter(ResearchArea::isActive) + .toList(); for (ResearchArea daisyResearchArea : researchAreas) { - se.su.dsv.scipro.system.ResearchArea researchArea = - researchAreaService.updateExternalResearchArea(daisyResearchArea.getId(), daisyResearchArea.getNameEn(), daisyResearchArea.isActive()); + se.su.dsv.scipro.system.ResearchArea researchArea = researchAreaService.updateExternalResearchArea( + daisyResearchArea.getId(), + daisyResearchArea.getNameEn(), + daisyResearchArea.isActive() + ); employee.addResearchArea(researchArea); } - employee.getResearchAreas() - .removeIf(researchArea -> - researchAreas.stream() - .noneMatch(daisyResearchArea -> - Objects.equals(daisyResearchArea.getId(), researchArea.getIdentifier()))); + employee + .getResearchAreas() + .removeIf(researchArea -> + researchAreas + .stream() + .noneMatch(daisyResearchArea -> + Objects.equals(daisyResearchArea.getId(), researchArea.getIdentifier()) + ) + ); employee.addRole(Roles.SUPERVISOR); employee.setActiveAsSupervisor(true); - if (employee.getLanguages().isEmpty()){ + if (employee.getLanguages().isEmpty()) { employee.setLanguages(EnumSet.allOf(Language.class)); } userService.save(employee); @@ -193,11 +215,12 @@ public class ImporterTransactionsImpl implements ImporterTransactions { } private User overwritePersonData(User local, Person person) { - final boolean nothingChanged = Objects.equals(local.getFirstName(), person.getFirstName()) - && Objects.equals(local.getLastName(), person.getLastName()) - && Objects.equals(local.getEmailAddress(), person.getEmail()) - && Objects.equals(local.getIdentifier(), person.getId()) - && Objects.equals(local.isDeceased(), person.isDeceased()); + final boolean nothingChanged = + Objects.equals(local.getFirstName(), person.getFirstName()) && + Objects.equals(local.getLastName(), person.getLastName()) && + Objects.equals(local.getEmailAddress(), person.getEmail()) && + Objects.equals(local.getIdentifier(), person.getId()) && + Objects.equals(local.isDeceased(), person.isDeceased()); if (nothingChanged) { return local; } @@ -212,7 +235,7 @@ public class ImporterTransactionsImpl implements ImporterTransactions { @Override public void importProject(Thesis thesis) { - if (thesis.getLevel() == EducationalLevel.FIRST_CYCLE || thesis.getLevel() == EducationalLevel.SECOND_CYCLE){ + if (thesis.getLevel() == EducationalLevel.FIRST_CYCLE || thesis.getLevel() == EducationalLevel.SECOND_CYCLE) { LOGGER.info("Importing project: {} ({})", thesis.getTitle(), thesis.getId()); Set authors = client.getAuthors(thesis.getId()); Project project = convertProjectAndSave(thesis); @@ -237,5 +260,4 @@ public class ImporterTransactionsImpl implements ImporterTransactions { projectService.save(project); } } - } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/Daisy.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/Daisy.java index b9761ae4d9..cb4cc5f2bb 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/Daisy.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/Daisy.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.integration.daisy; +import jakarta.inject.Inject; +import java.util.SortedSet; +import java.util.TreeSet; import se.su.dsv.scipro.io.ExternalExporter; import se.su.dsv.scipro.io.exceptions.ExternalExportException; import se.su.dsv.scipro.io.facade.ExporterFacade; @@ -10,10 +13,6 @@ import se.su.dsv.scipro.match.IdeaParticipation; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.SortedSet; -import java.util.TreeSet; - public class Daisy implements IdeaCreationJudge { private final ExporterFacade exporterFacade; @@ -28,12 +27,12 @@ public class Daisy implements IdeaCreationJudge { @Override public Decision ruling(final Idea idea) { Project project = Project.builder() - .title(idea.getTitle()) - .projectType(idea.getProjectType()) - .startDate(idea.getCourseStartDate()) - .headSupervisor(idea.getMatch().getSupervisor()) - .projectParticipants(getAuthors(idea)) - .build(); + .title(idea.getTitle()) + .projectType(idea.getProjectType()) + .startDate(idea.getCourseStartDate()) + .headSupervisor(idea.getMatch().getSupervisor()) + .projectParticipants(getAuthors(idea)) + .build(); try { exporterFacade.exportProject(project, project.getHeadSupervisor().getUnit()); diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyConsentService.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyConsentService.java index 9d9196ffde..ac3916fd07 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyConsentService.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyConsentService.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.integration.daisy; +import jakarta.inject.Inject; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.WebApplicationException; +import java.util.List; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; import se.su.dsv.scipro.finalthesis.PublishingConsentService; import se.su.dsv.scipro.io.dto.PublishingConsentLevel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; - class DaisyConsentService implements PublishingConsentService { + private static final PublishingConsent UNAVAILABLE = new PublishingConsent(null, List.of()); private final DaisyAPI daisyAPI; @@ -23,11 +23,12 @@ class DaisyConsentService implements PublishingConsentService { @Override public boolean setPublishingConsent(Project project, User author, Level publishingConsent) { - final PublishingConsentLevel publishingConsentLevel = switch (publishingConsent) { - case DO_NOT_PUBLISH -> PublishingConsentLevel.DO_NOT_PUBLISH; - case PUBLISH_INTERNALLY -> PublishingConsentLevel.PUBLISH_INTERNALLY; - case PUBLISH -> PublishingConsentLevel.PUBLIC; - }; + final PublishingConsentLevel publishingConsentLevel = + switch (publishingConsent) { + case DO_NOT_PUBLISH -> PublishingConsentLevel.DO_NOT_PUBLISH; + case PUBLISH_INTERNALLY -> PublishingConsentLevel.PUBLISH_INTERNALLY; + case PUBLISH -> PublishingConsentLevel.PUBLIC; + }; return daisyAPI.setPublishingConsent(project.getIdentifier(), author.getIdentifier(), publishingConsentLevel); } @@ -37,13 +38,17 @@ class DaisyConsentService implements PublishingConsentService { return UNAVAILABLE; } try { - final se.su.dsv.scipro.io.dto.PublishingConsent publishingConsent = daisyAPI.getPublishingConsent(project.getIdentifier(), author.getIdentifier()); + final se.su.dsv.scipro.io.dto.PublishingConsent publishingConsent = daisyAPI.getPublishingConsent( + project.getIdentifier(), + author.getIdentifier() + ); final Level selected = fromDaisyLevel(publishingConsent.getSelected()); - final List available = publishingConsent.getAvailables() - .stream() - .map(DaisyConsentService::fromDaisyLevel) - .sorted() - .toList(); + final List available = publishingConsent + .getAvailables() + .stream() + .map(DaisyConsentService::fromDaisyLevel) + .sorted() + .toList(); return new PublishingConsent(selected, available); } catch (ProcessingException | WebApplicationException e) { return UNAVAILABLE; diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyIntegrationConfiguration.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyIntegrationConfiguration.java index 1a50b0c056..9956543fb5 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyIntegrationConfiguration.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyIntegrationConfiguration.java @@ -40,6 +40,7 @@ import se.su.dsv.scipro.workerthreads.Scheduler; @Configuration public class DaisyIntegrationConfiguration implements PluginConfiguration { + @Bean public Daisy daisy(ExporterFacade exporterFacade, ExternalExporter externalExporter) { return new Daisy(exporterFacade, externalExporter); @@ -57,106 +58,139 @@ public class DaisyIntegrationConfiguration implements PluginConfiguration { @Bean public DaisyWorkerInitialization daisyWorkerInitialization( - Scheduler scheduler, - Provider projectExporter, - Provider userImportWorker, - Provider projectFinalizer, - Provider rejectedThesisWorkerProvider, - Provider gradingFinalizer, - Provider importNationalCategories) - { - return new DaisyWorkerInitialization(scheduler, projectExporter, userImportWorker, projectFinalizer, - rejectedThesisWorkerProvider, gradingFinalizer, importNationalCategories); + Scheduler scheduler, + Provider projectExporter, + Provider userImportWorker, + Provider projectFinalizer, + Provider rejectedThesisWorkerProvider, + Provider gradingFinalizer, + Provider importNationalCategories + ) { + return new DaisyWorkerInitialization( + scheduler, + projectExporter, + userImportWorker, + projectFinalizer, + rejectedThesisWorkerProvider, + gradingFinalizer, + importNationalCategories + ); } @Bean public ProjectExporter projectExporter( - ExporterFacade exporterFacade, - ProjectRepo projectRepo, - DaisyAPI daisyApi, - ExternalExporter externalExporter, - FinalSeminarService finalSeminarService, - FinalThesisService finalThesisService) - { - return new ProjectExporter(projectRepo, exporterFacade, daisyApi, externalExporter, finalSeminarService, - finalThesisService); + ExporterFacade exporterFacade, + ProjectRepo projectRepo, + DaisyAPI daisyApi, + ExternalExporter externalExporter, + FinalSeminarService finalSeminarService, + FinalThesisService finalThesisService + ) { + return new ProjectExporter( + projectRepo, + exporterFacade, + daisyApi, + externalExporter, + finalSeminarService, + finalThesisService + ); } @Bean public UserImportWorker userImportWorker( - DaisyAPI daisyApi, - ImporterTransactions importerTransactions, - ExternalImporter externalImporter, - MergeService mergeService, - UserService userService, - ProgramService programService, - Provider entityManager, - ResearchAreaService researchAreaService) - { - return new UserImportWorker(daisyApi, importerTransactions, externalImporter, mergeService, userService, - programService, entityManager, researchAreaService); + DaisyAPI daisyApi, + ImporterTransactions importerTransactions, + ExternalImporter externalImporter, + MergeService mergeService, + UserService userService, + ProgramService programService, + Provider entityManager, + ResearchAreaService researchAreaService + ) { + return new UserImportWorker( + daisyApi, + importerTransactions, + externalImporter, + mergeService, + userService, + programService, + entityManager, + researchAreaService + ); } @Bean public ProjectFinalizer projectFinalizer( - ProjectService projectService, - DaisyAPI daisyApi, - ThesisApprovedHistoryService thesisApprovedHistoryService) - { + ProjectService projectService, + DaisyAPI daisyApi, + ThesisApprovedHistoryService thesisApprovedHistoryService + ) { return new ProjectFinalizer(projectService, daisyApi, thesisApprovedHistoryService); } @Bean public RejectedThesisWorker rejectedThesisWorker( - GradingReportService gradingReportService, - ProjectService projectService, - FinalThesisService finalThesisService, - ProjectForumService projectForumService, - ThesisRejectionHistoryService thesisRejectionHistoryService, - DaisyAPI daisyApi) - { - return new RejectedThesisWorker(gradingReportService, projectService, finalThesisService, projectForumService, - thesisRejectionHistoryService, daisyApi); + GradingReportService gradingReportService, + ProjectService projectService, + FinalThesisService finalThesisService, + ProjectForumService projectForumService, + ThesisRejectionHistoryService thesisRejectionHistoryService, + DaisyAPI daisyApi + ) { + return new RejectedThesisWorker( + gradingReportService, + projectService, + finalThesisService, + projectForumService, + thesisRejectionHistoryService, + daisyApi + ); } @Bean public GradingCompletedMilestoneActivator gradingFinalizer( - ProjectService projectService, - DaisyAPI daisyApi, - EventBus eventBus, - UserService userService) - { + ProjectService projectService, + DaisyAPI daisyApi, + EventBus eventBus, + UserService userService + ) { return new GradingCompletedMilestoneActivator(projectService, daisyApi, eventBus, userService); } @Bean public ImportNationalCategories importNationalCategories( - DaisyAPI daisyApi, - NationalSubjectCategoryService nationalSubjectCategoryService) - { + DaisyAPI daisyApi, + NationalSubjectCategoryService nationalSubjectCategoryService + ) { return new ImportNationalCategories(daisyApi, nationalSubjectCategoryService); } @Bean public ImporterTransactionsImpl importerTransactions( - UserService userService, - ResearchAreaService researchAreaService, - ProjectService projectService, - UserNameService userNameService, - DaisyAPI daisyApi, - ProgramService programService) - { - return new ImporterTransactionsImpl(userService, researchAreaService, projectService, userNameService, - daisyApi, programService); + UserService userService, + ResearchAreaService researchAreaService, + ProjectService projectService, + UserNameService userNameService, + DaisyAPI daisyApi, + ProgramService programService + ) { + return new ImporterTransactionsImpl( + userService, + researchAreaService, + projectService, + userNameService, + daisyApi, + programService + ); } @Bean public ExternalImporterDaisyImpl externalImporter( - DaisyAPI daisyApi, - ImporterTransactions importerTransactions, - UserService userService, - UnitService unitService) - { + DaisyAPI daisyApi, + ImporterTransactions importerTransactions, + UserService userService, + UnitService unitService + ) { return new ExternalImporterDaisyImpl(userService, unitService, daisyApi, importerTransactions); } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyUserSearchService.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyUserSearchService.java index 5a19240abf..ad9a87d6d0 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyUserSearchService.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyUserSearchService.java @@ -1,6 +1,12 @@ package se.su.dsv.scipro.integration.daisy; +import jakarta.inject.Inject; import jakarta.ws.rs.ProcessingException; +import jakarta.ws.rs.WebApplicationException; +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; @@ -9,14 +15,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchProvider; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import jakarta.ws.rs.WebApplicationException; -import java.util.Collection; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; - public class DaisyUserSearchService implements UserSearchProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(DaisyUserSearchService.class); private final DaisyAPI daisyAPI; @@ -37,13 +37,14 @@ public class DaisyUserSearchService implements UserSearchProvider { public Collection search(final String term, final Set role, final long maxResults) { if (term != null && term.length() >= 6) { try { - return daisyAPI.findByPersonnummer(term).stream() - .map(person -> userService.findByExternalIdentifier(person.getId())) - .filter(Objects::nonNull) - .filter(user -> role.stream().anyMatch(user::hasRole)) - .toList(); - } - catch (ProcessingException | WebApplicationException e) { + return daisyAPI + .findByPersonnummer(term) + .stream() + .map(person -> userService.findByExternalIdentifier(person.getId())) + .filter(Objects::nonNull) + .filter(user -> role.stream().anyMatch(user::hasRole)) + .toList(); + } catch (ProcessingException | WebApplicationException e) { LOGGER.debug("Failed to search for users in Daisy", e); } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyWorkerInitialization.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyWorkerInitialization.java index 4d52011ff7..72b8c84b40 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyWorkerInitialization.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/DaisyWorkerInitialization.java @@ -1,27 +1,34 @@ package se.su.dsv.scipro.integration.daisy; -import se.su.dsv.scipro.integration.daisy.workers.*; -import se.su.dsv.scipro.workerthreads.Scheduler; - import jakarta.inject.Inject; import jakarta.inject.Provider; import java.util.concurrent.TimeUnit; +import se.su.dsv.scipro.integration.daisy.workers.*; +import se.su.dsv.scipro.workerthreads.Scheduler; public class DaisyWorkerInitialization { + @Inject public DaisyWorkerInitialization( - Scheduler scheduler, - Provider projectExporter, - Provider userImportWorker, - Provider projectFinalizer, - Provider rejectedThesisWorkerProvider, - Provider gradingFinalizer, - Provider importNationalCategories) { + Scheduler scheduler, + Provider projectExporter, + Provider userImportWorker, + Provider projectFinalizer, + Provider rejectedThesisWorkerProvider, + Provider gradingFinalizer, + Provider importNationalCategories + ) { scheduler.schedule("Export projects to daisy").runBy(projectExporter).dailyAt(1, 0); scheduler.schedule("Remote supervisor (and projects) bulk import").runBy(userImportWorker).dailyAt(1, 30); scheduler.schedule("Mark projects as completed").runBy(projectFinalizer).dailyAt(2, 0); - scheduler.schedule("Mark the 'grading completed' milestone as completed").runBy(gradingFinalizer).dailyAt(2, 30); - scheduler.schedule("Reject thesis based on examiner rejection in Daisy").runBy(rejectedThesisWorkerProvider).every(5, TimeUnit.MINUTES); + scheduler + .schedule("Mark the 'grading completed' milestone as completed") + .runBy(gradingFinalizer) + .dailyAt(2, 30); + scheduler + .schedule("Reject thesis based on examiner rejection in Daisy") + .runBy(rejectedThesisWorkerProvider) + .every(5, TimeUnit.MINUTES); scheduler.schedule("Import national subject categories").runBy(importNationalCategories).dailyAt(3, 0); } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/SyncReviewerWithDaisy.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/SyncReviewerWithDaisy.java index 0ce564f578..be10731801 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/SyncReviewerWithDaisy.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/SyncReviewerWithDaisy.java @@ -2,7 +2,10 @@ package se.su.dsv.scipro.integration.daisy; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.util.Objects; +import java.util.Set; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; import se.su.dsv.scipro.io.dto.Person; import se.su.dsv.scipro.io.dto.ProjectParticipant; @@ -11,11 +14,8 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ReviewerAssignedEvent; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Objects; -import java.util.Set; - class SyncReviewerWithDaisy { + private static final System.Logger LOGGER = System.getLogger(SyncReviewerWithDaisy.class.getName()); private final DaisyAPI daisyAPI; @@ -37,8 +37,10 @@ class SyncReviewerWithDaisy { try { Set contributors = daisyAPI.getContributors(project.getIdentifier()); for (ProjectParticipant contributor : contributors) { - if (Objects.equals(contributor.getPerson().getId(), reviewer.getIdentifier()) - && Objects.equals(Role.REVIEWER, contributor.getRole())) { + if ( + Objects.equals(contributor.getPerson().getId(), reviewer.getIdentifier()) && + Objects.equals(Role.REVIEWER, contributor.getRole()) + ) { return; } } @@ -57,7 +59,11 @@ class SyncReviewerWithDaisy { try (var response = daisyAPI.addContributor(project.getIdentifier(), contributor)) { Response.Status.Family family = response.getStatusInfo().getFamily(); if (family == Response.Status.Family.CLIENT_ERROR) { - LOGGER.log(System.Logger.Level.ERROR, "Faulty reviewer sync: {0}", response.getHeaderString("X-Error-Message")); + LOGGER.log( + System.Logger.Level.ERROR, + "Faulty reviewer sync: {0}", + response.getHeaderString("X-Error-Message") + ); } } } catch (RuntimeException ignored) { diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivator.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivator.java index 3decbe0be9..769507253b 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivator.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivator.java @@ -1,8 +1,12 @@ package se.su.dsv.scipro.integration.daisy.workers; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import jakarta.inject.Named; import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.WebApplicationException; +import java.util.Optional; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; @@ -17,13 +21,9 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import java.util.Optional; -import java.util.Set; - @Named -public class GradingCompletedMilestoneActivator extends AbstractWorker{ +public class GradingCompletedMilestoneActivator extends AbstractWorker { + private static final Logger LOG = LoggerFactory.getLogger(GradingCompletedMilestoneActivator.class); private final ProjectService projectService; @@ -31,9 +31,13 @@ public class GradingCompletedMilestoneActivator extends AbstractWorker{ private final EventBus eventBus; private final UserService userService; - @Inject - public GradingCompletedMilestoneActivator(ProjectService projectRepo, DaisyAPI daisyAPI, EventBus eventBus, UserService userService) { + public GradingCompletedMilestoneActivator( + ProjectService projectRepo, + DaisyAPI daisyAPI, + EventBus eventBus, + UserService userService + ) { this.projectService = projectRepo; this.daisyAPI = daisyAPI; this.eventBus = eventBus; @@ -43,27 +47,29 @@ public class GradingCompletedMilestoneActivator extends AbstractWorker{ @Override protected void doWork() { beginTransaction(); - Iterable projects = projectService.findAll(QProject.project.projectStatus.eq(ProjectStatus.ACTIVE).and(QProject.project.identifier.isNotNull())); + Iterable projects = projectService.findAll( + QProject.project.projectStatus.eq(ProjectStatus.ACTIVE).and(QProject.project.identifier.isNotNull()) + ); for (Project project : projects) { try { Set participatingAuthors = daisyAPI.getAuthors(project.getIdentifier()); - for (AuthorProjectParticipant participatingAuthor: participatingAuthors) { - Course course = participatingAuthor.getCourse(); - Optional grade = daisyAPI.getGradeForStudentInCourse(participatingAuthor.getId(), course.getId()); + for (AuthorProjectParticipant participatingAuthor : participatingAuthors) { + Course course = participatingAuthor.getCourse(); + Optional grade = daisyAPI.getGradeForStudentInCourse( + participatingAuthor.getId(), + course.getId() + ); if (grade.isPresent()) { User user = userService.findByExternalIdentifier(participatingAuthor.getPerson().getId()); eventBus.post(new GradingCompletedEvent(project, user)); } } - } - catch (NotFoundException ignored) { + } catch (NotFoundException ignored) { LOG.warn("The project {} has been removed from Daisy, severing the connection", project); - } - catch (WebApplicationException e) { + } catch (WebApplicationException e) { LOG.info("Could not fetch authors grades from Daisy for project {}", project, e); - } - catch (Exception e) { + } catch (Exception e) { LOG.error("Failed to make 'grading completed' milestone as completed for project ({})", project, e); } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ImportNationalCategories.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ImportNationalCategories.java index 4f58039bb0..7ba4f4989e 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ImportNationalCategories.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ImportNationalCategories.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.integration.daisy.workers; +import jakarta.inject.Inject; +import java.util.List; +import java.util.Optional; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; import se.su.dsv.scipro.grading.NationalSubjectCategory; import se.su.dsv.scipro.grading.NationalSubjectCategoryService; import se.su.dsv.scipro.io.dto.ResearchSubject; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Optional; - public class ImportNationalCategories extends AbstractWorker { + private static final int DSV = 4; private final DaisyAPI daisyAPI; @@ -26,8 +26,9 @@ public class ImportNationalCategories extends AbstractWorker { protected void doWork() { List nationalResearchSubjects = daisyAPI.getNationalResearchSubjects(DSV); for (ResearchSubject researchSubject : nationalResearchSubjects) { - Optional nationalSubjectCategory = - nationalSubjectCategoryService.findByExternalId(researchSubject.getExternalID()); + Optional nationalSubjectCategory = nationalSubjectCategoryService.findByExternalId( + researchSubject.getExternalID() + ); if (nationalSubjectCategory.isEmpty()) { NationalSubjectCategory newSubjectCategory = new NationalSubjectCategory(); newSubjectCategory.setExternalId(researchSubject.getExternalID()); @@ -36,8 +37,7 @@ public class ImportNationalCategories extends AbstractWorker { newSubjectCategory.setActive(researchSubject.isActive()); newSubjectCategory.setPreselected(researchSubject.isPreselected()); nationalSubjectCategoryService.save(newSubjectCategory); - } - else { + } else { NationalSubjectCategory existingSubjectCategory = nationalSubjectCategory.get(); existingSubjectCategory.setSwedishName(researchSubject.getName()); existingSubjectCategory.setEnglishName(researchSubject.getNameEn()); diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporter.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporter.java index 049b6c2e94..3bd943ffca 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporter.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporter.java @@ -1,5 +1,19 @@ package se.su.dsv.scipro.integration.daisy.workers; +import static com.querydsl.core.types.dsl.Expressions.anyOf; + +import jakarta.inject.Inject; +import jakarta.inject.Named; +import jakarta.ws.rs.core.Response; +import java.time.Instant; +import java.time.Period; +import java.util.Calendar; +import java.util.Date; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; @@ -21,21 +35,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import jakarta.ws.rs.core.Response; -import java.time.Instant; -import java.time.Period; -import java.util.Calendar; -import java.util.Date; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static com.querydsl.core.types.dsl.Expressions.anyOf; - @Named public class ProjectExporter extends AbstractWorker { @@ -50,13 +49,14 @@ public class ProjectExporter extends AbstractWorker { private final FinalThesisService finalThesisService; @Inject - public ProjectExporter(ProjectRepo projectRepo, - ExporterFacade exporterFacade, - DaisyAPI daisyAPI, - ExternalExporter externalExporter, - final FinalSeminarService finalSeminarService, - final FinalThesisService finalThesisService) - { + public ProjectExporter( + ProjectRepo projectRepo, + ExporterFacade exporterFacade, + DaisyAPI daisyAPI, + ExternalExporter externalExporter, + final FinalSeminarService finalSeminarService, + final FinalThesisService finalThesisService + ) { this.projectRepo = projectRepo; this.exporterFacade = exporterFacade; this.daisyAPI = daisyAPI; @@ -69,19 +69,22 @@ public class ProjectExporter extends AbstractWorker { protected void doWork() { beginTransaction(); Iterable projects = projectRepo.findAll( - QProject.project.projectType.degreeType.in(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) - .and(QProject.project.headSupervisor.unit.isNotNull()) - .and(anyOf( - QProject.project.lastModified.after(oneWeekAgo()), - QProject.project.projectStatus.eq(ProjectStatus.ACTIVE) - )) - .and(QProject.project.headSupervisor.unit.identifier.isNotNull())); + QProject.project.projectType.degreeType + .in(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + .and(QProject.project.headSupervisor.unit.isNotNull()) + .and( + anyOf( + QProject.project.lastModified.after(oneWeekAgo()), + QProject.project.projectStatus.eq(ProjectStatus.ACTIVE) + ) + ) + .and(QProject.project.headSupervisor.unit.identifier.isNotNull()) + ); for (Project project : projects) { try { exportProject(project); - } - catch (ExternalExportException e) { + } catch (ExternalExportException e) { LOG.info("Failed to export project ({}) to Daisy: {}", project, e.getMessage()); } } @@ -105,16 +108,19 @@ public class ProjectExporter extends AbstractWorker { FinalSeminar finalSeminar = finalSeminarService.findByProject(project); if (finalSeminar != null) { - updateParticipants(project.getIdentifier(), finalSeminar.getActiveParticipations() + updateParticipants( + project.getIdentifier(), + finalSeminar + .getActiveParticipations() .stream() .filter(isApproved()) .map(toUser()) - .filter(onlyDaisyUsers())); - updateOpponents(project.getIdentifier(), finalSeminar.getOppositions() - .stream() - .filter(isApproved()) - .map(toUser()) - .filter(onlyDaisyUsers())); + .filter(onlyDaisyUsers()) + ); + updateOpponents( + project.getIdentifier(), + finalSeminar.getOppositions().stream().filter(isApproved()).map(toUser()).filter(onlyDaisyUsers()) + ); } } } @@ -154,7 +160,12 @@ public class ProjectExporter extends AbstractWorker { } private boolean isParticipant(final User user, final Role role, final Set contributors) { - return contributors.stream().anyMatch(contributor -> contributor.getRole() == role && contributor.getPerson().getId().equals(user.getIdentifier())); + return contributors + .stream() + .anyMatch( + contributor -> + contributor.getRole() == role && contributor.getPerson().getId().equals(user.getIdentifier()) + ); } private void createProject(Project project) throws ExternalExportException { @@ -171,20 +182,20 @@ public class ProjectExporter extends AbstractWorker { } } - private void updateInDaisy(final Project project, final Optional finalThesis, final Thesis daisyThesis) { + private void updateInDaisy( + final Project project, + final Optional finalThesis, + final Thesis daisyThesis + ) { UnitWithID unit = new UnitWithID(); unit.setId(project.getHeadSupervisor().getUnit().getIdentifier()); Calendar startDate = SciProUtilities.toCalendar(project.getStartDate()); String title = finalThesis - .map(FinalThesis::getSwedishTitle) - .orElseGet(() -> - finalThesis.map(FinalThesis::getEnglishTitle) - .orElseGet(project::getTitle)); - String englishTitle = finalThesis - .map(FinalThesis::getEnglishTitle) - .orElseGet(daisyThesis::getTitleEn); + .map(FinalThesis::getSwedishTitle) + .orElseGet(() -> finalThesis.map(FinalThesis::getEnglishTitle).orElseGet(project::getTitle)); + String englishTitle = finalThesis.map(FinalThesis::getEnglishTitle).orElseGet(daisyThesis::getTitleEn); ThesisToBeUpdated thesis = new ThesisToBeUpdated(); thesis.setTitle(truncate(title)); @@ -248,12 +259,17 @@ public class ProjectExporter extends AbstractWorker { if (contributor.getPerson().getId().equals(project.getHeadSupervisor().getIdentifier())) { toAdd = false; } else { - Response response = daisyAPI.deleteThesisPerson(project.getIdentifier(), contributor.getPerson().getId()); + Response response = daisyAPI.deleteThesisPerson( + project.getIdentifier(), + contributor.getPerson().getId() + ); if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { - LOG.warn("Failed to delete supervisor from project: {} (id: {} / {})", - project.getTitle(), - project.getId(), - project.getIdentifier()); + LOG.warn( + "Failed to delete supervisor from project: {} (id: {} / {})", + project.getTitle(), + project.getId(), + project.getIdentifier() + ); // Card 3413 // Do not attempt to add the new supervisor if the old one is still there to prevent @@ -273,8 +289,10 @@ public class ProjectExporter extends AbstractWorker { private void updateReviewers(Project project) throws ExternalExportException { Set contributors = daisyAPI.getContributors(project.getIdentifier()); for (ProjectParticipant contributor : contributors) { - if (contributor.getRole() == Role.REVIEWER && - reviewerIsRemoved(contributor.getPerson().getId(), project.getReviewers())) { + if ( + contributor.getRole() == Role.REVIEWER && + reviewerIsRemoved(contributor.getPerson().getId(), project.getReviewers()) + ) { daisyAPI.deleteThesisPerson(project.getIdentifier(), contributor.getPerson().getId()); } } @@ -296,7 +314,10 @@ public class ProjectExporter extends AbstractWorker { private boolean reviewerIsMissing(User reviewer, Iterable contributors) { for (ProjectParticipant contributor : contributors) { - if (contributor.getRole() == Role.REVIEWER && contributor.getPerson().getId().equals(reviewer.getIdentifier())) { + if ( + contributor.getRole() == Role.REVIEWER && + contributor.getPerson().getId().equals(reviewer.getIdentifier()) + ) { return false; } } @@ -306,8 +327,10 @@ public class ProjectExporter extends AbstractWorker { private void updateCoSupervisors(Project project) throws ExternalExportException { Set contributors = daisyAPI.getContributors(project.getIdentifier()); for (ProjectParticipant contributor : contributors) { - if (contributor.getRole() == Role.ASSISTANT_SUPERVISOR && - coSupervisorIsRemoved(contributor.getPerson().getId(), project.getCoSupervisors())) { + if ( + contributor.getRole() == Role.ASSISTANT_SUPERVISOR && + coSupervisorIsRemoved(contributor.getPerson().getId(), project.getCoSupervisors()) + ) { daisyAPI.deleteThesisPerson(project.getIdentifier(), contributor.getPerson().getId()); } } @@ -329,7 +352,10 @@ public class ProjectExporter extends AbstractWorker { private boolean coSupervisorIsMissing(User coSupervisor, Set contributors) { for (ProjectParticipant contributor : contributors) { - if (contributor.getRole() == Role.ASSISTANT_SUPERVISOR && contributor.getPerson().getId().equals(coSupervisor.getIdentifier())) { + if ( + contributor.getRole() == Role.ASSISTANT_SUPERVISOR && + contributor.getPerson().getId().equals(coSupervisor.getIdentifier()) + ) { return false; } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizer.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizer.java index 7830db1ab9..26ebd3813b 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizer.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizer.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.integration.daisy.workers; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import java.time.Instant; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; @@ -11,11 +15,6 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.QProject; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import java.time.Instant; -import java.util.Optional; - @Named public class ProjectFinalizer extends AbstractWorker { @@ -27,10 +26,10 @@ public class ProjectFinalizer extends AbstractWorker { @Inject public ProjectFinalizer( - ProjectService projectService, - DaisyAPI daisyAPI, - ThesisApprovedHistoryService thesisApprovedHistoryService) - { + ProjectService projectService, + DaisyAPI daisyAPI, + ThesisApprovedHistoryService thesisApprovedHistoryService + ) { this.projectService = projectService; this.daisyAPI = daisyAPI; this.thesisApprovedHistoryService = thesisApprovedHistoryService; @@ -43,14 +42,14 @@ public class ProjectFinalizer extends AbstractWorker { beginTransaction(); try { Optional.ofNullable(project.getIdentifier()) - .flatMap(daisyAPI::getThesis) - .filter(thesis -> thesis.getStatus() == STATUS.FINISHED) - .ifPresent(thesis -> { - projectService.complete(project); - Instant when = thesis.getReadyDate().toInstant(); - thesisApprovedHistoryService.addApproved(project, when); - LOG.info("Finalized project ({})", project); - }); + .flatMap(daisyAPI::getThesis) + .filter(thesis -> thesis.getStatus() == STATUS.FINISHED) + .ifPresent(thesis -> { + projectService.complete(project); + Instant when = thesis.getReadyDate().toInstant(); + thesisApprovedHistoryService.addApproved(project, when); + LOG.info("Finalized project ({})", project); + }); } catch (Exception e) { LOG.info("Failed to finalize project ({})", project, e); } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/RejectedThesisWorker.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/RejectedThesisWorker.java index ad6cd7d8eb..ab796585ec 100644 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/RejectedThesisWorker.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/RejectedThesisWorker.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.integration.daisy.workers; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Date; +import java.util.List; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; import se.su.dsv.scipro.finalthesis.FinalThesis; import se.su.dsv.scipro.finalthesis.FinalThesisService; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.report.GradingReportService; import se.su.dsv.scipro.report.SupervisorGradingReport; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Date; -import java.util.List; - public class RejectedThesisWorker extends AbstractWorker { private final GradingReportService gradingReportService; @@ -29,13 +28,13 @@ public class RejectedThesisWorker extends AbstractWorker { @Inject public RejectedThesisWorker( - final GradingReportService gradingReportService, - final ProjectService projectService, - final FinalThesisService finalThesisService, - final ProjectForumService projectForumService, - final ThesisRejectionHistoryService thesisRejectionHistoryService, - final DaisyAPI daisyAPI) - { + final GradingReportService gradingReportService, + final ProjectService projectService, + final FinalThesisService finalThesisService, + final ProjectForumService projectForumService, + final ThesisRejectionHistoryService thesisRejectionHistoryService, + final DaisyAPI daisyAPI + ) { this.gradingReportService = gradingReportService; this.projectService = projectService; this.finalThesisService = finalThesisService; @@ -51,7 +50,8 @@ public class RejectedThesisWorker extends AbstractWorker { final Date rejectedDate = thesisRejection.getRejected().getTime(); final Project project = projectService.findByExternalIdentifier(thesisRejection.getThesisId().intValue()); if (project != null) { - final List supervisorGradingReports = gradingReportService.getSupervisorGradingReports(project); + final List supervisorGradingReports = + gradingReportService.getSupervisorGradingReports(project); for (SupervisorGradingReport supervisorGradingReport : supervisorGradingReports) { if (supervisorGradingReport.getLastModified().before(rejectedDate)) { supervisorGradingReport.setState(GradingReport.State.INITIAL); @@ -60,18 +60,30 @@ public class RejectedThesisWorker extends AbstractWorker { } } final FinalThesis finalThesis = finalThesisService.findByProject(project); - if (finalThesis != null && finalThesis.getStatus() != FinalThesis.Status.REJECTED && finalThesis.getLastModified().before(rejectedDate)) { + if ( + finalThesis != null && + finalThesis.getStatus() != FinalThesis.Status.REJECTED && + finalThesis.getLastModified().before(rejectedDate) + ) { finalThesisService.reject(project, thesisRejection.getMessage()); } // Check dates here since the API call is only date-based rather than time as well. if (thesisRejection.isVisibleToAuthors() && rejectedDate.after(getLastSuccessfulRun())) { - projectForumService.createThread(project, null, - "Thesis rejected by examiner", - "This is an automated message generated by the system.\n\nThe following comment was provided by the examiner. Consult with your supervisor what actions to take from here.\n\n" + thesisRejection.getMessage(), - Collections.emptySet()); + projectForumService.createThread( + project, + null, + "Thesis rejected by examiner", + "This is an automated message generated by the system.\n\nThe following comment was provided by the examiner. Consult with your supervisor what actions to take from here.\n\n" + + thesisRejection.getMessage(), + Collections.emptySet() + ); } if (rejectedDate.after(getLastSuccessfulRun())) { - thesisRejectionHistoryService.addRejection(project, thesisRejection.getMessage(), rejectedDate.toInstant()); + thesisRejectionHistoryService.addRejection( + project, + thesisRejection.getMessage(), + rejectedDate.toInstant() + ); } } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorker.java b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorker.java index 7ddcc8a675..77845ced07 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorker.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorker.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.integration.daisy.workers; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.persistence.EntityManager; +import java.time.Year; +import java.util.*; +import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.ExternalImporter; @@ -19,14 +25,8 @@ import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.system.Username; import se.su.dsv.scipro.workerthreads.AbstractWorker; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.persistence.EntityManager; -import java.time.Year; -import java.util.*; -import java.util.stream.Stream; - public class UserImportWorker extends AbstractWorker { + private static final Logger LOGGER = LoggerFactory.getLogger(UserImportWorker.class); private static final Integer DSV = 4; @@ -40,15 +40,16 @@ public class UserImportWorker extends AbstractWorker { private final ResearchAreaService researchAreaService; @Inject - public UserImportWorker(DaisyAPI daisyAPI, - ImporterTransactions importerTransactions, - ExternalImporter externalImporter, - final MergeService mergeService, - UserService userService, - ProgramService programService, - Provider entityManagerProvider, - final ResearchAreaService researchAreaService) - { + public UserImportWorker( + DaisyAPI daisyAPI, + ImporterTransactions importerTransactions, + ExternalImporter externalImporter, + final MergeService mergeService, + UserService userService, + ProgramService programService, + Provider entityManagerProvider, + final ResearchAreaService researchAreaService + ) { this.daisyAPI = daisyAPI; this.importerTransactions = importerTransactions; this.externalImporter = externalImporter; @@ -61,7 +62,6 @@ public class UserImportWorker extends AbstractWorker { @Override protected void doWork() { - long startDate = System.currentTimeMillis(); LOGGER.info("Starting execution for scheduled remote user import of all remote supervisors"); @@ -75,18 +75,22 @@ public class UserImportWorker extends AbstractWorker { long endDate = System.currentTimeMillis(); long executionTimeSecs = (endDate - startDate) / 1000; - LOGGER.info("Finished running in {} hours, {} minutes, {} seconds", - executionTimeSecs / 3600, - (executionTimeSecs % 3600) / 60, - executionTimeSecs % 60); + LOGGER.info( + "Finished running in {} hours, {} minutes, {} seconds", + executionTimeSecs / 3600, + (executionTimeSecs % 3600) / 60, + executionTimeSecs % 60 + ); } private void importResearchAreas() { - List daisyResearchAreas = daisyAPI - .orgunit(DSV) - .getResearchAreas(); + List daisyResearchAreas = daisyAPI.orgunit(DSV).getResearchAreas(); for (ResearchArea daisyResearchArea : daisyResearchAreas) { - researchAreaService.updateExternalResearchArea(daisyResearchArea.getId(), daisyResearchArea.getName(), daisyResearchArea.isActive()); + researchAreaService.updateExternalResearchArea( + daisyResearchArea.getId(), + daisyResearchArea.getName(), + daisyResearchArea.isActive() + ); } } @@ -99,21 +103,20 @@ public class UserImportWorker extends AbstractWorker { Person person = idPerson.get(); if (person.getEmail() != null) { importerTransactions.importPerson(person, programCache); - } - else { + } else { LOGGER.info("Skipping user because of no e-mail in Daisy: {}", person); } - } - else { + } else { for (Username username : user.getUsernames()) { Optional usernamePerson = daisyAPI.findByUsername(username.getUsername()); if (usernamePerson.isPresent()) { - User duplicatedUser = userService.findByExternalIdentifier(usernamePerson.get().getId()); + User duplicatedUser = userService.findByExternalIdentifier( + usernamePerson.get().getId() + ); if (duplicatedUser != null) { LOGGER.info("User {} ({}) already exist in SciPro", user, user.getIdentifier()); mergeService.mergeUsers(user, duplicatedUser); - } - else { + } else { user.setIdentifier(usernamePerson.get().getId()); userService.save(user); importerTransactions.importPerson(usernamePerson.get(), programCache); @@ -143,17 +146,18 @@ public class UserImportWorker extends AbstractWorker { try { if (supervisor.getEmail() != null) { importerTransactions.importSupervisor(supervisor, programCache); - } - else { + } else { LOGGER.info("Skipping supervisor because of no e-mail in Daisy: {}", supervisor); } importAllProjectsForSupervisor(supervisor); } catch (RuntimeException e) { - LOGGER.error("Failed to fetch projects for supervisor: {} {} ({})", - supervisor.getFirstName(), - supervisor.getLastName(), - supervisor.getId(), - e); + LOGGER.error( + "Failed to fetch projects for supervisor: {} {} ({})", + supervisor.getFirstName(), + supervisor.getLastName(), + supervisor.getId(), + e + ); } } } @@ -165,10 +169,7 @@ public class UserImportWorker extends AbstractWorker { try { importProject(project); } catch (RuntimeException e) { - LOGGER.error("Failed to import project: {} ({})", - project.getTitle(), - project.getId(), - e); + LOGGER.error("Failed to import project: {} ({})", project.getTitle(), project.getId(), e); } } } @@ -190,21 +191,33 @@ public class UserImportWorker extends AbstractWorker { for (ProgramAdmission admission : admissions) { final User user = userService.findByExternalIdentifier(admission.getStudentId()); if (user == null) { - daisyAPI.findPersonById(admission.getStudentId()) - .stream() - .peek(person -> LOGGER.info("Found potential new student: {} {} ({}) - checking email...", person.getFirstName(), person.getLastName(), person.getId())) - .filter(person -> person.getEmail() != null) - .peek(person -> LOGGER.info("Email set - importing")) - .forEach(person1 -> importerTransactions.importStudent(person1, programCache)); - } - else { - final boolean needsProgramConnection = user.getPrograms() - .stream() - .map(se.su.dsv.scipro.system.Program::getExternalId) - .noneMatch(admission.getProgramId()::equals); + daisyAPI + .findPersonById(admission.getStudentId()) + .stream() + .peek(person -> + LOGGER.info( + "Found potential new student: {} {} ({}) - checking email...", + person.getFirstName(), + person.getLastName(), + person.getId() + ) + ) + .filter(person -> person.getEmail() != null) + .peek(person -> LOGGER.info("Email set - importing")) + .forEach(person1 -> importerTransactions.importStudent(person1, programCache)); + } else { + final boolean needsProgramConnection = user + .getPrograms() + .stream() + .map(se.su.dsv.scipro.system.Program::getExternalId) + .noneMatch(admission.getProgramId()::equals); if (needsProgramConnection) { - final se.su.dsv.scipro.system.Program sciproProgram - = programService.updateExternalProgram(program.getId(), program.getName(), program.getNameEn(), program.getCode()); + final se.su.dsv.scipro.system.Program sciproProgram = programService.updateExternalProgram( + program.getId(), + program.getName(), + program.getNameEn(), + program.getCode() + ); user.addProgram(sciproProgram); userService.save(user); } @@ -218,9 +231,9 @@ public class UserImportWorker extends AbstractWorker { private static List getAdmissionSemestersToImport() { return Stream.iterate(Year.now().plusYears(1), y -> y.minusYears(1)) - .limit(5) - .map(Year::getValue) - .flatMap(year -> Stream.of(Semester.spring(year), Semester.autumn(year))) - .toList(); + .limit(5) + .map(Year::getValue) + .flatMap(year -> Stream.of(Semester.spring(year), Semester.autumn(year))) + .toList(); } } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/io/ExternalExporter.java b/daisy-integration/src/main/java/se/su/dsv/scipro/io/ExternalExporter.java index ecff6db7e1..ea1c812718 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/io/ExternalExporter.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/io/ExternalExporter.java @@ -6,7 +6,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; - /** * Specification for external synchronization of core SciPro objects. * @@ -14,8 +13,9 @@ import se.su.dsv.scipro.system.User; * {@link se.su.dsv.scipro.io.facade.ExporterFacade} for exporting needs. */ public interface ExternalExporter { - void createProject(final Project project, final Unit unit) throws ExternalExportException; - void addAuthorToProject(final Project project, final User user) throws ExternalExportException; - void addContributorToProject(final Project project, final User user, final Role role) throws ExternalExportException; - void deleteProject(final Project project) throws ExternalExportException; + void createProject(final Project project, final Unit unit) throws ExternalExportException; + void addAuthorToProject(final Project project, final User user) throws ExternalExportException; + void addContributorToProject(final Project project, final User user, final Role role) + throws ExternalExportException; + void deleteProject(final Project project) throws ExternalExportException; } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/io/exceptions/ExternalExportException.java b/daisy-integration/src/main/java/se/su/dsv/scipro/io/exceptions/ExternalExportException.java index ac8c153f3b..71262ff649 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/io/exceptions/ExternalExportException.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/io/exceptions/ExternalExportException.java @@ -1,9 +1,10 @@ package se.su.dsv.scipro.io.exceptions; -public class ExternalExportException extends Exception{ - public ExternalExportException(final String message){ - super(message); - } +public class ExternalExportException extends Exception { + + public ExternalExportException(final String message) { + super(message); + } public ExternalExportException(final String message, final Throwable cause) { super(message, cause); diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/io/facade/ExporterFacade.java b/daisy-integration/src/main/java/se/su/dsv/scipro/io/facade/ExporterFacade.java index 75400ab642..6115dca3e7 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/io/facade/ExporterFacade.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/io/facade/ExporterFacade.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.io.facade; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; import se.su.dsv.scipro.io.ExternalExporter; import se.su.dsv.scipro.io.dto.Role; @@ -8,8 +9,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class ExporterFacade { private final ExternalExporter exporter; @@ -32,9 +31,7 @@ public class ExporterFacade { * @throws ExternalExportException if the process failed at any step */ @Transactional - public void exportProject(Project project, Unit unit) - throws ExternalExportException { - + public void exportProject(Project project, Unit unit) throws ExternalExportException { try { exporter.createProject(project, unit); @@ -53,5 +50,4 @@ public class ExporterFacade { throw eee; } } - } diff --git a/daisy-integration/src/main/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImpl.java b/daisy-integration/src/main/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImpl.java index 66d34aa027..90aaca25c2 100755 --- a/daisy-integration/src/main/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImpl.java +++ b/daisy-integration/src/main/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImpl.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.io.impl; +import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.daisyExternal.http.DaisyAPI; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - public class ExternalExporterDaisyImpl implements ExternalExporter { private static final Logger LOGGER = LoggerFactory.getLogger(ExternalExporterDaisyImpl.class); @@ -41,8 +40,7 @@ public class ExternalExporterDaisyImpl implements ExternalExporter { } @Override - public void createProject(final Project project, final Unit unit) - throws ExternalExportException { + public void createProject(final Project project, final Unit unit) throws ExternalExportException { UnitWithID unitDTO = new UnitWithID(); unitDTO.setId(unit.getIdentifier()); @@ -70,7 +68,11 @@ public class ExternalExporterDaisyImpl implements ExternalExporter { int identifier = Integer.parseInt(path.substring(index + 1)); project.setIdentifier(identifier); } catch (Exception ex) { - LOGGER.error("Could not extract external id from location header [project={}, location={}]", project, response.getLocation()); + LOGGER.error( + "Could not extract external id from location header [project={}, location={}]", + project, + response.getLocation() + ); throw new ExternalExportException("Failed to extract external identifier from response", ex); } } @@ -84,9 +86,7 @@ public class ExternalExporterDaisyImpl implements ExternalExporter { } @Override - public void addAuthorToProject(Project project, User user) - throws ExternalExportException { - + public void addAuthorToProject(Project project, User user) throws ExternalExportException { AddThesisAuthorStudent authorStudent = new AddThesisAuthorStudent(); authorStudent.setId(user.getIdentifier()); @@ -102,12 +102,17 @@ public class ExternalExporterDaisyImpl implements ExternalExporter { Response response = api.addAuthor(project.getIdentifier(), addThesisAuthor); - expect(response, Response.Status.CREATED, "Could not add student to project [student=\"{}\", project=\"{}\"]", user, project); + expect( + response, + Response.Status.CREATED, + "Could not add student to project [student=\"{}\", project=\"{}\"]", + user, + project + ); } @Override - public void addContributorToProject(Project project, User user, Role role) - throws ExternalExportException { + public void addContributorToProject(Project project, User user, Role role) throws ExternalExportException { Person personDTO = new Person(); personDTO.setId(user.getIdentifier()); @@ -118,18 +123,35 @@ public class ExternalExporterDaisyImpl implements ExternalExporter { Response response = api.addContributor(project.getIdentifier(), contributorDTO); - expect(response, Response.Status.CREATED, "Could not add contributor to project [project=\"{}\", user=\"{}\", role=\"{}\"]", project, user, role); + expect( + response, + Response.Status.CREATED, + "Could not add contributor to project [project=\"{}\", user=\"{}\", role=\"{}\"]", + project, + user, + role + ); } @Override public void deleteProject(Project project) throws ExternalExportException { Response response = api.deleteProject(project.getIdentifier()); - expect(response, Response.Status.NO_CONTENT, "Project deletion failed [id={}, title={}]", project.getId(), project.getTitle()); + expect( + response, + Response.Status.NO_CONTENT, + "Project deletion failed [id={}, title={}]", + project.getId(), + project.getTitle() + ); } - private void expect(final Response response, final Response.Status status, final String errorMessage, final Object... parameters) - throws ExternalExportException { + private void expect( + final Response response, + final Response.Status status, + final String errorMessage, + final Object... parameters + ) throws ExternalExportException { if (status.getStatusCode() == response.getStatus()) { return; } diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImplTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImplTest.java index f409381c10..566ec3fd57 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImplTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ExternalImporterDaisyImplTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.daisyExternal.impl; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -11,21 +16,18 @@ import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.UserImportService; import se.su.dsv.scipro.system.UserService; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class ExternalImporterDaisyImplTest { @Mock private DaisyAPI daisyAPI; + @Mock private UserService userService; + @Mock private UnitService unitService; + @Mock private ImporterTransactions importerTransactions; @@ -41,10 +43,15 @@ class ExternalImporterDaisyImplTest { when(daisyAPI.findByPersonnummer(anyString())).thenReturn(List.of(einstein, obama)); - ExternalImporterDaisyImpl importerDaisy = new ExternalImporterDaisyImpl(userService, unitService, daisyAPI, importerTransactions); + ExternalImporterDaisyImpl importerDaisy = new ExternalImporterDaisyImpl( + userService, + unitService, + daisyAPI, + importerTransactions + ); List importableUsers = importerDaisy.search("abc"); assertEquals(1, importableUsers.size()); assertEquals("Obama", importableUsers.get(0).getLastName()); } -} \ No newline at end of file +} diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImplTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImplTest.java index 3fd3a2c6e4..baa7bda301 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImplTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/daisyExternal/impl/ImporterTransactionsImplTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.daisyExternal.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.Mockito.*; + +import java.util.HashMap; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -13,13 +19,6 @@ import se.su.dsv.scipro.match.ProgramService; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.*; -import java.util.HashMap; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.AdditionalAnswers.returnsFirstArg; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class ImporterTransactionsImplTest { @@ -30,16 +29,22 @@ public class ImporterTransactionsImplTest { @Mock private DaisyAPI daisyAPI; + @Mock private UserService userService; + @Mock private ResearchAreaService researchAreaService; + @Mock private ProjectService projectService; + @Mock private ProjectTypeService projectTypeService; + @Mock private UserNameService userNameService; + @Mock private ProgramService programService; @@ -47,8 +52,14 @@ public class ImporterTransactionsImplTest { @BeforeEach public void createInstance() { - importerTransactions = new ImporterTransactionsImpl(userService, researchAreaService, projectService, - userNameService, daisyAPI, programService); + importerTransactions = new ImporterTransactionsImpl( + userService, + researchAreaService, + projectService, + userNameService, + daisyAPI, + programService + ); when(userService.save(any())).thenAnswer(returnsFirstArg()); } @@ -72,15 +83,13 @@ public class ImporterTransactionsImplTest { kth.setRealm("kth.se"); kth.setUsername("kalle"); - when(daisyAPI.getUsernames(person.getId())) - .thenReturn(Set.of(kth)); + when(daisyAPI.getUsernames(person.getId())).thenReturn(Set.of(kth)); importerTransactions.importPerson(person, new HashMap<>()); verify(userNameService, never()).save(any()); } - @Test public void imports_su_usernames() { Person person = createPerson(); @@ -88,8 +97,7 @@ public class ImporterTransactionsImplTest { su.setRealm("su.se"); su.setUsername("kalle"); - when(daisyAPI.getUsernames(person.getId())) - .thenReturn(Set.of(su)); + when(daisyAPI.getUsernames(person.getId())).thenReturn(Set.of(su)); importerTransactions.importPerson(person, new HashMap<>()); @@ -99,7 +107,6 @@ public class ImporterTransactionsImplTest { assertEquals(su.getUsername() + "@" + su.getRealm(), captor.getValue().getUsername()); } - private static void assertUserPersonData(User user) { assertEquals(SOME_FIRST_NAME, user.getFirstName()); assertEquals(SOME_LAST_NAME, user.getLastName()); diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivatorTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivatorTest.java index f51c23592a..ea13a62418 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivatorTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/GradingCompletedMilestoneActivatorTest.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.integration.daisy.workers; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,12 +26,6 @@ import se.su.dsv.scipro.workerthreads.WorkerData; import se.su.dsv.scipro.workerthreads.WorkerDataService; import se.su.dsv.scipro.workerthreads.WorkerTransactionManager; -import java.util.*; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class GradingCompletedMilestoneActivatorTest { @@ -37,20 +36,30 @@ public class GradingCompletedMilestoneActivatorTest { @Mock private ProjectService projectService; + @Mock private UserService userService; + @Mock private DaisyAPI daisyAPI; + @Mock private EventBus eventBus; + @Mock private WorkerTransactionManager workerTransactionManager; + @Mock private WorkerDataService workerDataService; @BeforeEach public void setup() { - gradingCompletedMilestoneActivator = new GradingCompletedMilestoneActivator(projectService, daisyAPI, eventBus, userService); + gradingCompletedMilestoneActivator = new GradingCompletedMilestoneActivator( + projectService, + daisyAPI, + eventBus, + userService + ); gradingCompletedMilestoneActivator.setTxManager(workerTransactionManager); gradingCompletedMilestoneActivator.setWorkerDataService(workerDataService); when(workerDataService.save(any(WorkerData.class))).thenReturn(new WorkerData()); @@ -60,7 +69,11 @@ public class GradingCompletedMilestoneActivatorTest { project.setProjectStatus(ProjectStatus.ACTIVE); List projects = Collections.singletonList(project); - when(projectService.findAll(QProject.project.projectStatus.eq(ProjectStatus.ACTIVE).and(QProject.project.identifier.isNotNull()))).thenReturn(projects); + when( + projectService.findAll( + QProject.project.projectStatus.eq(ProjectStatus.ACTIVE).and(QProject.project.identifier.isNotNull()) + ) + ).thenReturn(projects); Set participants = new HashSet<>(); AuthorProjectParticipant studentProjectParticipant = new AuthorProjectParticipant(); @@ -81,4 +94,4 @@ public class GradingCompletedMilestoneActivatorTest { verify(eventBus).post(isA(GradingCompletedEvent.class)); } -} \ No newline at end of file +} diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporterTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporterTest.java index dfd523ad4f..1cfcf78361 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporterTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectExporterTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.integration.daisy.workers; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.querydsl.core.types.Predicate; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,14 +31,6 @@ import se.su.dsv.scipro.workerthreads.WorkerData; import se.su.dsv.scipro.workerthreads.WorkerDataService; import se.su.dsv.scipro.workerthreads.WorkerTransactionManager; -import java.time.LocalDate; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ProjectExporterTest { @@ -55,7 +54,14 @@ public class ProjectExporterTest { @BeforeEach public void setUp() { - projectExporter = new ProjectExporter(projectRepo, exporterFacade, daisyAPI, externalExporter, finalSeminarService, finalThesisService); + projectExporter = new ProjectExporter( + projectRepo, + exporterFacade, + daisyAPI, + externalExporter, + finalSeminarService, + finalThesisService + ); projectExporter.setTxManager(workerTransactionManager); projectExporter.setWorkerDataService(workerDataService); when(workerDataService.save(any(WorkerData.class))).thenReturn(new WorkerData()); @@ -73,23 +79,22 @@ public class ProjectExporterTest { ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); newProject = Project.builder() - .title("New project") - .projectType(bachelor) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("New project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); ProjectType master = new ProjectType(DegreeType.MASTER, "Master", "Master"); exportedProject = Project.builder() - .title("Exported project") - .projectType(master) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .identifier(8) - .build(); + .title("Exported project") + .projectType(master) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .identifier(8) + .build(); - when(projectRepo.findAll(any(Predicate.class))) - .thenReturn(Arrays.asList(newProject, exportedProject)); + when(projectRepo.findAll(any(Predicate.class))).thenReturn(Arrays.asList(newProject, exportedProject)); when(daisyAPI.getThesis(anyInt())).thenReturn(Optional.of(new Thesis())); } diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizerTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizerTest.java index 048d2165e7..133616e85a 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizerTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/ProjectFinalizerTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.integration.daisy.workers; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -15,18 +23,8 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.QProject; import se.su.dsv.scipro.workerthreads.WorkerData; import se.su.dsv.scipro.workerthreads.WorkerDataService; - import se.su.dsv.scipro.workerthreads.WorkerTransactionManager; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ProjectFinalizerTest { @@ -40,7 +38,6 @@ public class ProjectFinalizerTest { private @Mock WorkerDataService workerDataService; private @Mock ThesisApprovedHistoryService thesisApprovedHistoryService; - @BeforeEach public void setup() { projectFinalizer = new ProjectFinalizer(projectService, daisyAPI, thesisApprovedHistoryService); @@ -65,4 +62,4 @@ public class ProjectFinalizerTest { verify(projectService).complete(project); } -} \ No newline at end of file +} diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorkerTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorkerTest.java index ad7b5d6951..6789af1f8f 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorkerTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/integration/daisy/workers/UserImportWorkerTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.integration.daisy.workers; +import static java.util.Arrays.asList; +import static org.mockito.Mockito.*; + +import jakarta.persistence.EntityManager; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -16,29 +21,30 @@ import se.su.dsv.scipro.system.ResearchAreaService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.persistence.EntityManager; -import java.util.*; - -import static java.util.Arrays.asList; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class UserImportWorkerTest { @Mock private ExternalImporter externalImporter; + @Mock private ImporterTransactions importerTransactions; + @Mock private DaisyAPI daisyAPI; + @Mock private UserService userService; + @Mock private MergeService mergeService; + @Mock private ProgramService programService; + @Mock private EntityManager entityManager; + @Mock private ResearchAreaService researchAreaService; @@ -49,14 +55,15 @@ public class UserImportWorkerTest { when(userService.findAll()).thenReturn(Collections.emptyList()); when(daisyAPI.orgunit(anyInt())).thenReturn(Collections::emptyList); worker = new UserImportWorker( - daisyAPI, - importerTransactions, - externalImporter, - mergeService, - userService, - programService, - () -> entityManager, - researchAreaService); + daisyAPI, + importerTransactions, + externalImporter, + mergeService, + userService, + programService, + () -> entityManager, + researchAreaService + ); } @Test diff --git a/daisy-integration/src/test/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImplTest.java b/daisy-integration/src/test/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImplTest.java index eabffe1efb..930ec58dc6 100644 --- a/daisy-integration/src/test/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImplTest.java +++ b/daisy-integration/src/test/java/se/su/dsv/scipro/io/impl/ExternalExporterDaisyImplTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.io.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.core.Response; +import java.net.URI; +import java.time.LocalDate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,19 +24,9 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.Unit; -import jakarta.ws.rs.core.Response; -import java.net.URI; -import java.time.LocalDate; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ExternalExporterDaisyImplTest { + private static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @Mock @@ -38,7 +38,9 @@ public class ExternalExporterDaisyImplTest { public void setUp() { daisy = new ExternalExporterDaisyImpl(daisyAPI); - when(daisyAPI.createProject(any(ThesisToBeCreated.class))).thenReturn(Response.created(URI.create("/1")).build()); + when(daisyAPI.createProject(any(ThesisToBeCreated.class))).thenReturn( + Response.created(URI.create("/1")).build() + ); } @Test diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000..ffc4227614 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,138 @@ +{ + "name": "scipro", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "devDependencies": { + "prettier-plugin-java": "^2.6.5" + } + }, + "node_modules/@chevrotain/cst-dts-gen": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.0.3.tgz", + "integrity": "sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/gast": "11.0.3", + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/gast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.0.3.tgz", + "integrity": "sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/regexp-to-ast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.0.3.tgz", + "integrity": "sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/types": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.0.3.tgz", + "integrity": "sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/utils": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.0.3.tgz", + "integrity": "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/chevrotain": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz", + "integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/cst-dts-gen": "11.0.3", + "@chevrotain/gast": "11.0.3", + "@chevrotain/regexp-to-ast": "11.0.3", + "@chevrotain/types": "11.0.3", + "@chevrotain/utils": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/chevrotain-allstar": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz", + "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash-es": "^4.17.21" + }, + "peerDependencies": { + "chevrotain": "^11.0.0" + } + }, + "node_modules/java-parser": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/java-parser/-/java-parser-2.3.2.tgz", + "integrity": "sha512-/O42UbEHy3VVJw8W0ruHkQjW75oWvQx4QisoUDRIGir6q3/IZ4JslDMPMYEqp7LU56PYJkH5uXdQiBaCXt/Opw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "chevrotain": "11.0.3", + "chevrotain-allstar": "0.3.1", + "lodash": "4.17.21" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", + "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-plugin-java": { + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/prettier-plugin-java/-/prettier-plugin-java-2.6.5.tgz", + "integrity": "sha512-2RkPNXyYpP5dRhr04pz45n+e5LXwYWTh1JXrztiCkZTGGokIGYrfwUuGa8csnDoGbP6CDPgVm8zZSIm/9I0SRQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "java-parser": "2.3.2", + "lodash": "4.17.21", + "prettier": "3.2.5" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000..94e82097d1 --- /dev/null +++ b/package.json @@ -0,0 +1,9 @@ +{ + "scripts": { + "format": "prettier --write \"**/src/{main,test}/**/*.java\"", + "format:check": "prettier --check \"**/src/{main,test}/**/*.java\"" + }, + "devDependencies": { + "prettier-plugin-java": "^2.6.5" + } +} diff --git a/pom.xml b/pom.xml index c96cb4a122..e69b87c989 100755 --- a/pom.xml +++ b/pom.xml @@ -396,6 +396,57 @@ WEB-INF/web.xml + + com.github.eirslett + frontend-maven-plugin + 1.9.1 + + + false + + + v22.11.0 + ${project.build.outputDirectory} + + + + + install-node-and-npm + + validate + + + install + validate + + npm + + + install + + + + check-format + verify + + npm + + + run format:check + + + + reformat + none + + npm + + + run format + + + + \ No newline at end of file diff --git a/view/src/main/java/ch/qos/logback/classic/Logger.java b/view/src/main/java/ch/qos/logback/classic/Logger.java index 8e3fe9cc9f..fe88284567 100644 --- a/view/src/main/java/ch/qos/logback/classic/Logger.java +++ b/view/src/main/java/ch/qos/logback/classic/Logger.java @@ -1,5 +1,4 @@ package ch.qos.logback.classic; // Force JBoss (Hibernate) to log through SLF4J even if Logback is not used as the implementation. -public class Logger { -} +public class Logger {} diff --git a/view/src/main/java/se/su/dsv/scipro/CurrentUserFromWicketSession.java b/view/src/main/java/se/su/dsv/scipro/CurrentUserFromWicketSession.java index 808992e771..a13b465884 100644 --- a/view/src/main/java/se/su/dsv/scipro/CurrentUserFromWicketSession.java +++ b/view/src/main/java/se/su/dsv/scipro/CurrentUserFromWicketSession.java @@ -6,6 +6,7 @@ import se.su.dsv.scipro.system.CurrentUser; import se.su.dsv.scipro.system.User; public class CurrentUserFromWicketSession implements CurrentUser { + @Override public User get() { return Session.exists() ? SciProSession.get().getUser() : null; diff --git a/view/src/main/java/se/su/dsv/scipro/FileSystemStore.java b/view/src/main/java/se/su/dsv/scipro/FileSystemStore.java index 3d0eafc255..ad9f851ece 100644 --- a/view/src/main/java/se/su/dsv/scipro/FileSystemStore.java +++ b/view/src/main/java/se/su/dsv/scipro/FileSystemStore.java @@ -1,8 +1,5 @@ package se.su.dsv.scipro; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileStore; - import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -11,8 +8,11 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileStore; public class FileSystemStore implements FileStore { + private static final int FILES_PER_SUBDIRECTORY = 1000; private static final String FILE_ROOT = "/scipro-files"; @@ -58,7 +58,9 @@ public class FileSystemStore implements FileStore { } private static String getSubdirectory(final FileDescription metaData) { - return Long.toString((metaData.getId() / FILES_PER_SUBDIRECTORY) * FILES_PER_SUBDIRECTORY + FILES_PER_SUBDIRECTORY); + return Long.toString( + (metaData.getId() / FILES_PER_SUBDIRECTORY) * FILES_PER_SUBDIRECTORY + FILES_PER_SUBDIRECTORY + ); } private static void createDirectory(Path directory) throws IOException { diff --git a/view/src/main/java/se/su/dsv/scipro/HomePage.java b/view/src/main/java/se/su/dsv/scipro/HomePage.java index c2eec34275..b93e1d9f41 100755 --- a/view/src/main/java/se/su/dsv/scipro/HomePage.java +++ b/view/src/main/java/se/su/dsv/scipro/HomePage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro; +import jakarta.inject.Inject; import org.apache.wicket.Page; import org.apache.wicket.RestartResponseException; import se.su.dsv.scipro.admin.pages.AdminStartPage; @@ -13,8 +14,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.supervisor.pages.SupervisorStartPage; -import jakarta.inject.Inject; - public class HomePage extends MenuPage { @Inject @@ -58,32 +57,40 @@ public class HomePage extends MenuPage { } } - private void show(Class page) { throw new RestartResponseException(page); } private boolean isSysAdmin() { - return SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN); + return ( + SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN) + ); } private boolean isAdmin() { - return SciProSession.get().authorizedForRole(Roles.ADMIN) && SciProSession.get().hasActualRole(Roles.ADMIN); + return (SciProSession.get().authorizedForRole(Roles.ADMIN) && SciProSession.get().hasActualRole(Roles.ADMIN)); } private boolean isSupervisor() { - return SciProSession.get().authorizedForRole(Roles.SUPERVISOR) && SciProSession.get().hasActualRole(Roles.SUPERVISOR); + return ( + SciProSession.get().authorizedForRole(Roles.SUPERVISOR) && + SciProSession.get().hasActualRole(Roles.SUPERVISOR) + ); } private boolean isAuthor() { - return SciProSession.get().authorizedForRole(Roles.AUTHOR) && SciProSession.get().hasActualRole(Roles.AUTHOR); + return (SciProSession.get().authorizedForRole(Roles.AUTHOR) && SciProSession.get().hasActualRole(Roles.AUTHOR)); } private boolean isReviewer() { - return SciProSession.get().authorizedForRole(Roles.REVIEWER) && SciProSession.get().hasActualRole(Roles.REVIEWER); + return ( + SciProSession.get().authorizedForRole(Roles.REVIEWER) && SciProSession.get().hasActualRole(Roles.REVIEWER) + ); } private boolean isExaminer() { - return SciProSession.get().authorizedForRole(Roles.EXAMINER) && SciProSession.get().hasActualRole(Roles.EXAMINER); + return ( + SciProSession.get().authorizedForRole(Roles.EXAMINER) && SciProSession.get().hasActualRole(Roles.EXAMINER) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/SciProApplication.java b/view/src/main/java/se/su/dsv/scipro/SciProApplication.java index 521595f7c3..37f93c29e7 100755 --- a/view/src/main/java/se/su/dsv/scipro/SciProApplication.java +++ b/view/src/main/java/se/su/dsv/scipro/SciProApplication.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro; import de.agilecoders.wicket.webjars.WicketWebjars; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; import org.apache.wicket.*; import org.apache.wicket.authorization.strategies.CompoundAuthorizationStrategy; import org.apache.wicket.csp.CSPDirective; @@ -80,42 +85,47 @@ import se.su.dsv.scipro.user.AdminSwitchUserPage; import se.su.dsv.scipro.user.AdminUsersPage; import se.su.dsv.scipro.util.AdditionalExceptionLogger; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - public class SciProApplication extends LifecycleManagedWebApplication { @Inject public SciProApplication(CurrentProfile currentProfile) { - setConfigurationType(currentProfile.getCurrentProfile() == Profiles.PROD + setConfigurationType( + currentProfile.getCurrentProfile() == Profiles.PROD ? RuntimeConfigurationType.DEPLOYMENT - : RuntimeConfigurationType.DEVELOPMENT); + : RuntimeConfigurationType.DEVELOPMENT + ); } @Override protected IConverterLocator newConverterLocator() { final ConverterLocator converterLocator = new ConverterLocator(); - converterLocator.set(LocalDate.class, new LocalDateConverter() { - @Override - protected DateTimeFormatter getDateTimeFormatter() { - return DateTimeFormatter.ISO_LOCAL_DATE; + converterLocator.set( + LocalDate.class, + new LocalDateConverter() { + @Override + protected DateTimeFormatter getDateTimeFormatter() { + return DateTimeFormatter.ISO_LOCAL_DATE; + } } - }); - converterLocator.set(LocalDateTime.class, new LocalDateTimeConverter() { - @Override - protected DateTimeFormatter getDateTimeFormatter() { - return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + ); + converterLocator.set( + LocalDateTime.class, + new LocalDateTimeConverter() { + @Override + protected DateTimeFormatter getDateTimeFormatter() { + return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + } } - }); - converterLocator.set(ZonedDateTime.class, new LocalDateTimeConverter() { - @Override - protected DateTimeFormatter getDateTimeFormatter() { - return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + ); + converterLocator.set( + ZonedDateTime.class, + new LocalDateTimeConverter() { + @Override + protected DateTimeFormatter getDateTimeFormatter() { + return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + } } - }); + ); return converterLocator; } @@ -149,22 +159,24 @@ public class SciProApplication extends LifecycleManagedWebApplication { getResourceSettings().getStringResourceLoaders().add(new NotificationLoader()); - getCspSettings().blocking() - // whitelist all css files coming from self - .add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF) - // script-src 'self' is ignored for CSP level 3 compliant browsers due to 'strict-dynamic' - // but is used as a fallback for older browsers to allow loading of local javascripts - .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.SELF) - // allow images to be defined inline using data: (used by bootstrap menu toggler (hamburger)) - .add(CSPDirective.IMG_SRC, "data:"); + getCspSettings() + .blocking() + // whitelist all css files coming from self + .add(CSPDirective.STYLE_SRC, CSPDirectiveSrcValue.SELF) + // script-src 'self' is ignored for CSP level 3 compliant browsers due to 'strict-dynamic' + // but is used as a fallback for older browsers to allow loading of local javascripts + .add(CSPDirective.SCRIPT_SRC, CSPDirectiveSrcValue.SELF) + // allow images to be defined inline using data: (used by bootstrap menu toggler (hamburger)) + .add(CSPDirective.IMG_SRC, "data:"); WicketWebjars.install(this); - getComponentInstantiationListeners().add(component -> { - if (component instanceof Form) { - component.add(new DisableSubmitButtonsOnSubmit()); - } - }); + getComponentInstantiationListeners() + .add(component -> { + if (component instanceof Form) { + component.add(new DisableSubmitButtonsOnSubmit()); + } + }); } private void mountErrorPages() { diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityDataProvider.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityDataProvider.java index 1478f4aa06..1c1fb9256e 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityDataProvider.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityDataProvider.java @@ -1,32 +1,34 @@ package se.su.dsv.scipro.activityplan; +import java.util.Date; +import java.util.Iterator; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.dataproviders.PageAdapter; import se.su.dsv.scipro.project.Project; -import java.util.Date; -import java.util.Iterator; - public class ActivityDataProvider extends SortableDataProvider { + public enum SearchMode { PROJECT_ALL { @Override public String toString() { return "all"; } - }, PROJECT_PAST { + }, + PROJECT_PAST { @Override public String toString() { return "past"; } - }, PROJECT_FUTURE { + }, + PROJECT_FUTURE { @Override public String toString() { return "upcoming"; } - } + }, } private ActivityPlanFacade activityPlanFacade; @@ -35,7 +37,11 @@ public class ActivityDataProvider extends SortableDataProvider private SearchMode searchMode = SearchMode.PROJECT_ALL; private final Project project; - public ActivityDataProvider(final ActivityPlanFacade activityPlanFacade, final ActivityService activityService, final Project p) { + public ActivityDataProvider( + final ActivityPlanFacade activityPlanFacade, + final ActivityService activityService, + final Project p + ) { this.activityPlanFacade = activityPlanFacade; this.activityService = activityService; this.project = p; diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanPanel.java index ff3b0414de..3b7fb74056 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -41,22 +46,20 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - public class ActivityPlanPanel extends GenericPanel { + public static final String FILE_UPLOAD = "fileUpload"; public static final String DATE = "date"; @Inject private ActivityService activityService; + @Inject private ActivityPlanFacade facade; + @Inject private NotificationController notificationController; + @Inject private ProjectService projectService; @@ -70,7 +73,6 @@ public class ActivityPlanPanel extends GenericPanel { public ActivityPlanPanel(final String id, final IModel project) { super(id, project); - dialogSetup(); formSetup(); newButtonSetup(); @@ -80,16 +82,13 @@ public class ActivityPlanPanel extends GenericPanel { } private void addFeedback() { - add(new FencedFeedbackPanel("feedback", this) - .setOutputMarkupId(true)); + add(new FencedFeedbackPanel("feedback", this).setOutputMarkupId(true)); } private void newButtonSetup() { - AjaxLink createLink = new AjaxCreateLink("createLink"); add(createLink); - } protected final Project getProject() { @@ -97,39 +96,48 @@ public class ActivityPlanPanel extends GenericPanel { } private void addModeControls() { - add(new AjaxRadioChoice<>("modeGroup", + add( + new AjaxRadioChoice<>( + "modeGroup", LambdaModel.of(sdp::getSearchMode, sdp::setSearchMode), Arrays.asList(ActivityDataProvider.SearchMode.values()), - new EnumChoiceRenderer<>(this)) { - @Override - protected void update(AjaxRequestTarget target) { - target.add(table); - if (ActivityDataProvider.SearchMode.PROJECT_PAST == getModelObject()) { - sdp.setSort(DATE, SortOrder.DESCENDING); - } else { - sdp.setSort(DATE, SortOrder.ASCENDING); + new EnumChoiceRenderer<>(this) + ) { + @Override + protected void update(AjaxRequestTarget target) { + target.add(table); + if (ActivityDataProvider.SearchMode.PROJECT_PAST == getModelObject()) { + sdp.setSort(DATE, SortOrder.DESCENDING); + } else { + sdp.setSort(DATE, SortOrder.ASCENDING); + } } } - }); + ); } private void dialogSetup() { addFromTemplateModalWindowPlus = new ModalWindowPlus("addDialog"); addFromTemplateModalWindowPlus.setTitle("Add activities from template"); - addActivitiesFromTemplatePanel = new AddActivitiesFromTemplatePanel(addFromTemplateModalWindowPlus.getContentId(), getModel()); + addActivitiesFromTemplatePanel = new AddActivitiesFromTemplatePanel( + addFromTemplateModalWindowPlus.getContentId(), + getModel() + ); addFromTemplateModalWindowPlus.setContent(addActivitiesFromTemplatePanel); add(addFromTemplateModalWindowPlus); saveAsTemplateModalWindowPlus = new ModalWindowPlus("saveAsTemplateDialog"); - saveAsTemplatePanel = new SaveAsTemplatePanel(saveAsTemplateModalWindowPlus.getContentId(), new LoadableDetachableModel<>() { - @Override - protected ActivityPlan load() { - return getActivityPlan(); + saveAsTemplatePanel = new SaveAsTemplatePanel( + saveAsTemplateModalWindowPlus.getContentId(), + new LoadableDetachableModel<>() { + @Override + protected ActivityPlan load() { + return getActivityPlan(); + } } - }); + ); saveAsTemplateModalWindowPlus.setTitle(new ResourceModel("save.as.template")); saveAsTemplateModalWindowPlus.setContent(saveAsTemplatePanel); add(saveAsTemplateModalWindowPlus); - } private void dataViewSetup() { @@ -141,68 +149,114 @@ public class ActivityPlanPanel extends GenericPanel { private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new DateColumn<>(new ResourceModel(DATE).wrapOnAssignment(this), Activity::getDate, DATE, DateStyle.DATETIME)); - columns.add(new LambdaColumn<>(new ResourceModel("title").wrapOnAssignment(this), "title", Activity::getTitle) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new TitleCell(componentId, rowModel)); + columns.add( + new DateColumn<>( + new ResourceModel(DATE).wrapOnAssignment(this), + Activity::getDate, + DATE, + DateStyle.DATETIME + ) + ); + columns.add( + new LambdaColumn<>(new ResourceModel("title").wrapOnAssignment(this), "title", Activity::getTitle) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add(new TitleCell(componentId, rowModel)); + } } - }); + ); columns.add(new ActionColumn(new StringResourceModel("action", this).setDefaultValue("Action"))); - columns.add(new AbstractExportableColumn<>(new ResourceModel("checklist").wrapOnAssignment(this)) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new ChecklistCell(componentId, LambdaModel.of(rowModel, Activity::getChecklist, Activity::setChecklist))); + columns.add( + new AbstractExportableColumn<>(new ResourceModel("checklist").wrapOnAssignment(this)) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new ChecklistCell( + componentId, + LambdaModel.of(rowModel, Activity::getChecklist, Activity::setChecklist) + ) + ); + } + + @Override + public IModel getDataModel(IModel rowModel) { + return new ChecklistNameModel( + LambdaModel.of(rowModel, Activity::getChecklist, Activity::setChecklist) + ); + } } + ); + columns.add( + new AbstractColumn<>(new ResourceModel("edit")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.EDIT)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(rowModel.getObject().isEditable()); + } - @Override - public IModel getDataModel(IModel rowModel) { - return new ChecklistNameModel(LambdaModel.of(rowModel, Activity::getChecklist, Activity::setChecklist)); + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), getProject().getId()); + pp.add(PageParameterKeys.MAP.get(Activity.class), model.getObject().getId()); + + editPage(pp); + } + } + ); + } } - }); - columns.add(new AbstractColumn<>(new ResourceModel("edit")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.EDIT)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(rowModel.getObject().isEditable()); - } + ); + columns.add( + new AbstractColumn<>(new ResourceModel("delete")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + getString("delete.confirmation") + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(rowModel.getObject().isEditable()); + } - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), getProject().getId()); - pp.add(PageParameterKeys.MAP.get(Activity.class), model.getObject().getId()); - - editPage(pp); - - } - }); + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + facade.deleteActivity(rowModel.getObject()); + target.add(table); + notifyDeletedActivityPlan(rowModel.getObject().getTitle()); + success(getString("activity.deleted", model)); + target.addListener(new AjaxFeedbackPanelUpdater()); + } + } + ); + } } - }); - columns.add(new AbstractColumn<>(new ResourceModel("delete")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), getString("delete.confirmation")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(rowModel.getObject().isEditable()); - } - - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - facade.deleteActivity(rowModel.getObject()); - target.add(table); - notifyDeletedActivityPlan(rowModel.getObject().getTitle()); - success(getString("activity.deleted", model)); - target.addListener(new AjaxFeedbackPanelUpdater()); - } - }); - } - }); + ); return columns; } @@ -219,61 +273,75 @@ public class ActivityPlanPanel extends GenericPanel { } private class TitleCell extends Fragment { + public TitleCell(String id, final IModel model) { super(id, "titleCell", ActivityPlanPanel.this, model); - add(new Label("title", LambdaModel.of(model, Activity::getTitle, Activity::setTitle))); - add(new InfoPanel("info", LambdaModel.of(model, Activity::getDescription, Activity::setDescription)){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(model.getObject().getDescription() != null && !model.getObject().getDescription().isEmpty()); + add( + new InfoPanel("info", LambdaModel.of(model, Activity::getDescription, Activity::setDescription)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + model.getObject().getDescription() != null && !model.getObject().getDescription().isEmpty() + ); + } } - }); + ); } } + private class ResourceCell extends Fragment { + public ResourceCell(String id, final IModel model) { super(id, "resourceCell", ActivityPlanPanel.this, model); - final Activity event = model.getObject(); if (event.getFileUpload() != null) { + add( + new FileDescriptionPanel( + FILE_UPLOAD, + model.map(Activity::getFileUpload).map(FileReference::getFileDescription) + ) { + @Override + public void onDelete(AjaxRequestTarget target) { + facade.deleteActivityUpload(model.getObject()); + target.add(table); + } - add(new FileDescriptionPanel(FILE_UPLOAD, model.map(Activity::getFileUpload).map(FileReference::getFileDescription)) { - @Override - public void onDelete(AjaxRequestTarget target) { - facade.deleteActivityUpload(model.getObject()); - target.add(table); + @Override + public boolean deleteAllowed() { + return true; + } } - - @Override - public boolean deleteAllowed() { - return true; - } - }); - + ); } else { - add(new ActivityUploadForm(model) { - @Override - protected void onFinished(AjaxRequestTarget target) { - target.add(table); - } - }.createDefaultWrapperPanel(FILE_UPLOAD)); + add( + new ActivityUploadForm(model) { + @Override + protected void onFinished(AjaxRequestTarget target) { + target.add(table); + } + }.createDefaultWrapperPanel(FILE_UPLOAD) + ); } } } private class ChecklistCell extends Fragment { + public ChecklistCell(String id, IModel model) { super(id, "checklistCell", ActivityPlanPanel.this, model); - Checklist checklist = model.getObject(); PageParameters pageParameters = new PageParameters(); if (checklist != null) { pageParameters.set(PageParameterKeys.MAP.get(Checklist.class), checklist.getId()); } - BookmarkablePageLink checklistLink = new BookmarkablePageLink<>("checklistLink", getChecklistPage(), pageParameters) { + BookmarkablePageLink checklistLink = new BookmarkablePageLink<>( + "checklistLink", + getChecklistPage(), + pageParameters + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -291,6 +359,7 @@ public class ActivityPlanPanel extends GenericPanel { } private static class ChecklistNameModel implements IModel { + private final IModel model; public ChecklistNameModel(IModel model) { @@ -305,17 +374,16 @@ public class ActivityPlanPanel extends GenericPanel { } private void formSetup() { - addActivitiesFromTemplatePanel.setOutputMarkupId(true); - add(new AjaxLink("addFromTemplateLink") { - - @Override - public void onClick(AjaxRequestTarget target) { - target.add(addActivitiesFromTemplatePanel); - addFromTemplateModalWindowPlus.show(target); + add( + new AjaxLink("addFromTemplateLink") { + @Override + public void onClick(AjaxRequestTarget target) { + target.add(addActivitiesFromTemplatePanel); + addFromTemplateModalWindowPlus.show(target); + } } - - }); + ); saveAsTemplatePanel.setOutputMarkupId(true); final AjaxLink saveAsTemplateLink = new AjaxLink("saveAsTemplateLink") { @@ -336,8 +404,10 @@ public class ActivityPlanPanel extends GenericPanel { add(saveAsTemplateLink); - - AjaxLink deleteAllActivities = new AjaxConfirmationLink<>("deleteAllActivitiesLink", "Are you sure you want to delete all activities?") { + AjaxLink deleteAllActivities = new AjaxConfirmationLink<>( + "deleteAllActivitiesLink", + "Are you sure you want to delete all activities?" + ) { @Override public void onClick(AjaxRequestTarget target) { facade.deleteAllEvents(getActivityPlan()); @@ -383,16 +453,20 @@ public class ActivityPlanPanel extends GenericPanel { editPage(pp); } - } private class ActionColumn extends AbstractColumn { + public ActionColumn(final IModel displayModel) { super(displayModel); } @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { final Activity activity = rowModel.getObject(); final Action action = activity.getAction(); final Project project = activity.getActivityPlan().getProject(); @@ -400,56 +474,90 @@ public class ActivityPlanPanel extends GenericPanel { case HAND_IN: if (hasSupervisingRole() && rowModel.getObject().getFileUpload() == null) { cellItem.add(new Label(componentId, new ResourceModel("upload.is.for.authors"))); - } - else { + } else { cellItem.add(new ResourceCell(componentId, rowModel)); } break; case PEER: if (hasSupervisingRole()) { - cellItem.add(LinkWrapper.apply(componentId, id -> { - PageParameters pp = SupervisorProjectDetailsPage.getPageParameters(project); - BookmarkablePageLink link = new BookmarkablePageLink<>(id, SupervisorProjectDetailsPage.class, pp); - link.setBody(Model.of("View peer status")); - link.setAnchor(new WebComponent("unused").setMarkupId("peerStatus")); - return link; - })); + cellItem.add( + LinkWrapper.apply(componentId, id -> { + PageParameters pp = SupervisorProjectDetailsPage.getPageParameters(project); + BookmarkablePageLink link = new BookmarkablePageLink<>( + id, + SupervisorProjectDetailsPage.class, + pp + ); + link.setBody(Model.of("View peer status")); + link.setAnchor(new WebComponent("unused").setMarkupId("peerStatus")); + return link; + }) + ); } else { - cellItem.add(LinkWrapper.apply(componentId, id -> { - PageParameters pp = PeerPortalPage.getPageParameters(project); - BookmarkablePageLink link = new BookmarkablePageLink<>(id, PeerPortalPage.class, pp); - link.setBody(Model.of("Submit peer request")); - return link; - })); + cellItem.add( + LinkWrapper.apply(componentId, id -> { + PageParameters pp = PeerPortalPage.getPageParameters(project); + BookmarkablePageLink link = new BookmarkablePageLink<>( + id, + PeerPortalPage.class, + pp + ); + link.setBody(Model.of("Submit peer request")); + return link; + }) + ); } break; case FINAL_THESIS: - cellItem.add(LinkWrapper.apply(componentId, id -> { - final Link link = getProjectBasedLink(id, project, ProjectDetailsPage.class, SupervisorProjectDetailsPage.class); - link.setBody(Model.of("Hand in final thesis")); - // Thanks Wicket for making it so easy to append an #anchor to a link... - link.setAnchor(new WebComponent("unused").setMarkupId("finalThesis")); - return link; - })); + cellItem.add( + LinkWrapper.apply(componentId, id -> { + final Link link = getProjectBasedLink( + id, + project, + ProjectDetailsPage.class, + SupervisorProjectDetailsPage.class + ); + link.setBody(Model.of("Hand in final thesis")); + // Thanks Wicket for making it so easy to append an #anchor to a link... + link.setAnchor(new WebComponent("unused").setMarkupId("finalThesis")); + return link; + }) + ); break; case FINAL_SEMINAR: - cellItem.add(LinkWrapper.apply(componentId, id -> { - final Link link = getProjectBasedLink(id, project, ProjectFinalSeminarPage.class, SupervisorFinalSeminarPage.class); - link.setBody(Model.of("Hand in final seminar thesis")); - return link; - })); + cellItem.add( + LinkWrapper.apply(componentId, id -> { + final Link link = getProjectBasedLink( + id, + project, + ProjectFinalSeminarPage.class, + SupervisorFinalSeminarPage.class + ); + link.setBody(Model.of("Hand in final seminar thesis")); + return link; + }) + ); break; case NONE: default: - cellItem.add(new Label(componentId, new StringResourceModel("action.not.available", ActivityPlanPanel.this).setDefaultValue("n/a"))); + cellItem.add( + new Label( + componentId, + new StringResourceModel("action.not.available", ActivityPlanPanel.this).setDefaultValue( + "n/a" + ) + ) + ); break; } } - private BookmarkablePageLink getProjectBasedLink(final String id, - final Project project, - final Class authorPage, - final Class supervisorPage) { + private BookmarkablePageLink getProjectBasedLink( + final String id, + final Project project, + final Class authorPage, + final Class supervisorPage + ) { final PageParameters pp = new PageParameters(); pp.set(PageParameterKeys.MAP.get(Project.class), project.getId()); if (project.isParticipant(SciProSession.get().getUser())) { diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanel.java index 80eeb110c3..3876bc438c 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanel.java @@ -1,6 +1,9 @@ package se.su.dsv.scipro.activityplan; - +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -26,11 +29,6 @@ import se.su.dsv.scipro.dataproviders.PageAdapter; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public abstract class ActivityPlanTemplateDataPanel extends Panel { @Inject @@ -48,7 +46,6 @@ public abstract class ActivityPlanTemplateDataPanel extends Panel { public ActivityPlanTemplateDataPanel(String id) { super(id); - filter = new ActivityPlanTemplateService.Filter(); filter.setCreator(SciProSession.get().getUser()); @@ -69,7 +66,7 @@ public abstract class ActivityPlanTemplateDataPanel extends Panel { AjaxCheckBox filterBox = new AjaxCheckBox("filterbox", new Model<>(Boolean.TRUE)) { @Override protected void onUpdate(AjaxRequestTarget target) { - if (getModelObject()){ + if (getModelObject()) { filter.setCreator(SciProSession.get().getUser()); } else { filter.setCreator(null); @@ -82,13 +79,18 @@ public abstract class ActivityPlanTemplateDataPanel extends Panel { } private void addTextFilter() { - TextField titleField = new TextField<>("titleFilter", LambdaModel.of(filter::getFilterString, filter::setFilterString)); - titleField.add(new OnChangeAjaxBehavior() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); + TextField titleField = new TextField<>( + "titleFilter", + LambdaModel.of(filter::getFilterString, filter::setFilterString) + ); + titleField.add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + } } - }); + ); add(titleField); } @@ -117,55 +119,94 @@ public abstract class ActivityPlanTemplateDataPanel extends Panel { private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new LambdaColumn<>(Model.of("Title"), ActivityPlanTemplate::getTitle) { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, LambdaModel.of(model, ActivityPlanTemplate::getTitle, ActivityPlanTemplate::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - onTitleClick(model, target); - } - }); + columns.add( + new LambdaColumn<>(Model.of("Title"), ActivityPlanTemplate::getTitle) { + @Override + public void populateItem( + Item> components, + String s, + final IModel model + ) { + components.add( + new AjaxLinkPanel<>( + s, + model, + LambdaModel.of(model, ActivityPlanTemplate::getTitle, ActivityPlanTemplate::setTitle) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + onTitleClick(model, target); + } + } + ); + } } - }); + ); - columns.add(new AbstractColumn<>(Model.of("Edit")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.EDIT)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - onEditClick(model); - target.add(dataPanel); - } + columns.add( + new AbstractColumn<>(Model.of("Edit")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.EDIT)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + onEditClick(model); + target.add(dataPanel); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(SciProSession.get().getUser().hasRole(Roles.SYSADMIN) || rowModel.getObject().getCreator().equals(SciProSession.get().getUser())); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + SciProSession.get().getUser().hasRole(Roles.SYSADMIN) || + rowModel.getObject().getCreator().equals(SciProSession.get().getUser()) + ); + } + } + ); + } } - }); + ); - columns.add(new AbstractColumn<>(Model.of("Delete")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), getString("delete.confirmation")) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - activityPlanTemplateService.delete(model.getObject().getId()); - target.add(dataPanel); - } + columns.add( + new AbstractColumn<>(Model.of("Delete")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + getString("delete.confirmation") + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + activityPlanTemplateService.delete(model.getObject().getId()); + target.add(dataPanel); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(SciProSession.get().getUser().hasRole(Roles.SYSADMIN) || rowModel.getObject().getCreator().equals(SciProSession.get().getUser())); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + SciProSession.get().getUser().hasRole(Roles.SYSADMIN) || + rowModel.getObject().getCreator().equals(SciProSession.get().getUser()) + ); + } + } + ); + } } - }); + ); return columns; } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDetailsPanel.java index ce514b5a7d..88d0a9cf6d 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDetailsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -12,8 +13,6 @@ import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - public class ActivityPlanTemplateDetailsPanel extends Panel { @Inject @@ -22,36 +21,91 @@ public class ActivityPlanTemplateDetailsPanel extends Panel { public ActivityPlanTemplateDetailsPanel(String id, final IModel model) { super(id, model); add(new Label("title", LambdaModel.of(model, ActivityPlanTemplate::getTitle, ActivityPlanTemplate::setTitle))); - add(new Label("description", LambdaModel.of(model, ActivityPlanTemplate::getDescription, ActivityPlanTemplate::setDescription))); + add( + new Label( + "description", + LambdaModel.of(model, ActivityPlanTemplate::getDescription, ActivityPlanTemplate::setDescription) + ) + ); - add(new UserLinkPanel("templateCreator", new DetachableServiceModel<>(userService, model.getObject().getCreator())){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!model.getObject().isSysAdminTemplate()); + add( + new UserLinkPanel( + "templateCreator", + new DetachableServiceModel<>(userService, model.getObject().getCreator()) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!model.getObject().isSysAdminTemplate()); + } } - }); + ); - add(new Label("admin", "System"){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(model.getObject().isSysAdminTemplate()); + add( + new Label("admin", "System") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(model.getObject().isSysAdminTemplate()); + } } - }); + ); - add(new DateLabel("templateCreated", LambdaModel.of(model, ActivityPlanTemplate::getDateCreated, ActivityPlanTemplate::setDateCreated))); - add(new DateLabel("templateUpdated", LambdaModel.of(model, ActivityPlanTemplate::getLastModified, ActivityPlanTemplate::setLastModified))); - add(new ListView<>("eventList", LambdaModel.of(model, ActivityPlanTemplate::getActivityTemplates, ActivityPlanTemplate::setActivityTemplates)) { - @Override - protected void populateItem(ListItem item) { - final IModel itemModel = item.getModel(); - item.add(new Label("etTitle", LambdaModel.of(itemModel, ActivityTemplate::getTitle, ActivityTemplate::setTitle))); - item.add(new Label("etDescription", LambdaModel.of(itemModel, ActivityTemplate::getDescription, ActivityTemplate::setDescription))); - item.add(new Label("etTimeConsumption", LambdaModel.of(itemModel, ActivityTemplate::getDaysOffset, ActivityTemplate::setDaysOffset))); - item.add(new EnumLabel<>("handinLabel", LambdaModel.of(itemModel, ActivityTemplate::getAction, ActivityTemplate::setAction))); - add(item); + add( + new DateLabel( + "templateCreated", + LambdaModel.of(model, ActivityPlanTemplate::getDateCreated, ActivityPlanTemplate::setDateCreated) + ) + ); + add( + new DateLabel( + "templateUpdated", + LambdaModel.of(model, ActivityPlanTemplate::getLastModified, ActivityPlanTemplate::setLastModified) + ) + ); + add( + new ListView<>( + "eventList", + LambdaModel.of( + model, + ActivityPlanTemplate::getActivityTemplates, + ActivityPlanTemplate::setActivityTemplates + ) + ) { + @Override + protected void populateItem(ListItem item) { + final IModel itemModel = item.getModel(); + item.add( + new Label( + "etTitle", + LambdaModel.of(itemModel, ActivityTemplate::getTitle, ActivityTemplate::setTitle) + ) + ); + item.add( + new Label( + "etDescription", + LambdaModel.of( + itemModel, + ActivityTemplate::getDescription, + ActivityTemplate::setDescription + ) + ) + ); + item.add( + new Label( + "etTimeConsumption", + LambdaModel.of(itemModel, ActivityTemplate::getDaysOffset, ActivityTemplate::setDaysOffset) + ) + ); + item.add( + new EnumLabel<>( + "handinLabel", + LambdaModel.of(itemModel, ActivityTemplate::getAction, ActivityTemplate::setAction) + ) + ); + add(item); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityUploadForm.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityUploadForm.java index 0893c724c7..33ea6b2319 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityUploadForm.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ActivityUploadForm.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import static se.su.dsv.scipro.notifications.dataobject.ProjectEvent.Event.FILE_UPLOADED; + +import jakarta.inject.Inject; import org.apache.wicket.markup.html.form.upload.FileUpload; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -11,15 +14,14 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -import static se.su.dsv.scipro.notifications.dataobject.ProjectEvent.Event.FILE_UPLOADED; - public class ActivityUploadForm extends AbstractUploadForm { + @Inject private ActivityPlanFacade facade; + @Inject private ProjectService projectService; + @Inject private NotificationController notificationController; @@ -32,7 +34,10 @@ public class ActivityUploadForm extends AbstractUploadForm { @Override protected void onNewUpload(final FileUpload fileUpload) { Activity activity = event.getObject(); - facade.storeActivityUpload(new WicketProjectFileUpload(fileUpload, activity.getActivityPlan().getProject()), activity); + facade.storeActivityUpload( + new WicketProjectFileUpload(fileUpload, activity.getActivityPlan().getProject()), + activity + ); Project project = projectService.findOne(activity.getActivityPlan().getProject().getId()); diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanel.java index 606e508172..340c565e13 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.Calendar; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -23,30 +27,28 @@ import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - public class AddActivitiesFromTemplatePanel extends GenericPanel { private final IModel model; + @Inject private NotificationController notificationController; + @Inject private ActivityPlanFacade activityPlanFacade; + @Inject private ActivityPlanTemplateService activityPlanTemplateService; private ActivityPlanTemplateService.Filter filter; - public AddActivitiesFromTemplatePanel(final String id, final IModel model){ - super(id, model); + public AddActivitiesFromTemplatePanel(final String id, final IModel model) { + super(id, model); filter = new ActivityPlanTemplateService.Filter(); this.model = model; filter.setCreator(this.model.getObject().getHeadSupervisor()); add(new ListFragment("content")); - } + } private void notifyChangeActivityPlan(String name, ProjectEvent.Event event) { PageParameters pp = new PageParameters(); @@ -63,47 +65,59 @@ public class AddActivitiesFromTemplatePanel extends GenericPanel { public ListFragment(final String id) { super(id, "list", AddActivitiesFromTemplatePanel.this); setOutputMarkupId(true); - final WebMarkupContainer container = new WebMarkupContainer("stupidContainerSinceWicketCantRefreshListViews"); + final WebMarkupContainer container = new WebMarkupContainer( + "stupidContainerSinceWicketCantRefreshListViews" + ); container.setOutputMarkupId(true); add(container); - add(new TextField<>("filter", LambdaModel.of(filter::getFilterString, filter::setFilterString)) { - { - add(new OnChangeAjaxBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(container); - } - }); - } - }); - add(new AjaxCheckBox("onlyRelevantTemplates", Model.of(Boolean.TRUE)) { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - if (getModelObject()){ - filter.setCreator(model.getObject().getHeadSupervisor()); - } else { - filter.setCreator(null); + add( + new TextField<>("filter", LambdaModel.of(filter::getFilterString, filter::setFilterString)) { + { + add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(container); + } + } + ); } - target.add(container); } - }); - container.add(new ListView<>("templates", getActivityPlanTemplates()) { - @Override - protected void populateItem(final ListItem item) { - item.add(new AjaxLink<>("title", item.getModel()) { - { - setBody(item.getModel().map(ActivityPlanTemplate::getTitle)); + ); + add( + new AjaxCheckBox("onlyRelevantTemplates", Model.of(Boolean.TRUE)) { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + if (getModelObject()) { + filter.setCreator(model.getObject().getHeadSupervisor()); + } else { + filter.setCreator(null); } + target.add(container); + } + } + ); + container.add( + new ListView<>("templates", getActivityPlanTemplates()) { + @Override + protected void populateItem(final ListItem item) { + item.add( + new AjaxLink<>("title", item.getModel()) { + { + setBody(item.getModel().map(ActivityPlanTemplate::getTitle)); + } - @Override - public void onClick(final AjaxRequestTarget target) { - DetailsFragment content = new DetailsFragment("content", getModel()); - AddActivitiesFromTemplatePanel.this.replace(content); - target.add(content); - } - }); + @Override + public void onClick(final AjaxRequestTarget target) { + DetailsFragment content = new DetailsFragment("content", getModel()); + AddActivitiesFromTemplatePanel.this.replace(content); + target.add(content); + } + } + ); + } } - }); + ); } private IModel> getActivityPlanTemplates() { @@ -132,19 +146,25 @@ public class AddActivitiesFromTemplatePanel extends GenericPanel { super(id, "details", AddActivitiesFromTemplatePanel.this); setOutputMarkupId(true); add(new ActivityPlanTemplateDetailsPanel("viewpanel", model)); - add(new AjaxLink("backlink") { - @Override - public void onClick(AjaxRequestTarget target) { - ListFragment content = new ListFragment("content"); - AddActivitiesFromTemplatePanel.this.replace(content); - target.add(content); + add( + new AjaxLink("backlink") { + @Override + public void onClick(AjaxRequestTarget target) { + ListFragment content = new ListFragment("content"); + AddActivitiesFromTemplatePanel.this.replace(content); + target.add(content); + } } - }); + ); Form form = new Form<>("form", model) { @Override protected void onSubmit() { - activityPlanFacade.addActivitiesFromTemplate(AddActivitiesFromTemplatePanel.this.getModelObject(), getModelObject(), dateModel.getObject()); + activityPlanFacade.addActivitiesFromTemplate( + AddActivitiesFromTemplatePanel.this.getModelObject(), + getModelObject(), + dateModel.getObject() + ); notifyChangeActivityPlan(getModelObject().getTitle(), ProjectEvent.Event.ACTIVITY_ADDED); } }; diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPage.java index 51e87cbbcf..11b2a99d43 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPage.java @@ -10,34 +10,39 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.util.PageParameterKeys; -@Authorization(authorizedRoles = {Roles.SYSADMIN, Roles.ADMIN}) -public class AdminActivityPlanTemplatesPage extends AbstractAdminProjectPage implements MenuHighlightAdminActivityPlanTemplates { +@Authorization(authorizedRoles = { Roles.SYSADMIN, Roles.ADMIN }) +public class AdminActivityPlanTemplatesPage + extends AbstractAdminProjectPage + implements MenuHighlightAdminActivityPlanTemplates { private ModalWindowPlus modalWindowPlus; public AdminActivityPlanTemplatesPage() { - modalWindowPlus = new ModalWindowPlus("dialog"); add(modalWindowPlus); - add(new ActivityPlanTemplateDataPanel("activityPlanTemplatePanel") { - @Override - public void onNewClick() { - setResponsePage(AdminEditActivityTemplatePage.class); - } + add( + new ActivityPlanTemplateDataPanel("activityPlanTemplatePanel") { + @Override + public void onNewClick() { + setResponsePage(AdminEditActivityTemplatePage.class); + } - @Override - public void onTitleClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setContent(new ActivityPlanTemplateDetailsPanel(modalWindowPlus.getContentId(), clicked)); - modalWindowPlus.show(target); - } + @Override + public void onTitleClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setContent( + new ActivityPlanTemplateDetailsPanel(modalWindowPlus.getContentId(), clicked) + ); + modalWindowPlus.show(target); + } - @Override - public void onEditClick(IModel clicked) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ActivityPlanTemplate.class), clicked.getObject().getId()); - setResponsePage(AdminEditActivityTemplatePage.class, pp); + @Override + public void onEditClick(IModel clicked) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(ActivityPlanTemplate.class), clicked.getObject().getId()); + setResponsePage(AdminEditActivityTemplatePage.class, pp); + } } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanel.java index d2d2a6ecf8..8893b5b77c 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.form.*; @@ -9,10 +11,8 @@ import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.checklist.ChecklistTemplate; import se.su.dsv.scipro.checklist.ChecklistTemplateService; -import jakarta.inject.Inject; -import java.util.Arrays; - public abstract class AdminEditActivityPanel extends Panel { + public static final String FORM = "form"; public static final String TITLE_FIELD = "titleField"; public static final String DESCRIPTION_AREA = "descriptionArea"; @@ -31,37 +31,57 @@ public abstract class AdminEditActivityPanel extends Panel { } protected class ActivityForm extends Form { + public ActivityForm(String id, final IModel model) { super(id, model); - - TextField title = new TextField<>(TITLE_FIELD, LambdaModel.of(model, ActivityTemplate::getTitle, ActivityTemplate::setTitle)); + TextField title = new TextField<>( + TITLE_FIELD, + LambdaModel.of(model, ActivityTemplate::getTitle, ActivityTemplate::setTitle) + ); title.setRequired(true); add(title); - add(new TextArea<>(DESCRIPTION_AREA, LambdaModel.of(model, ActivityTemplate::getDescription, ActivityTemplate::setDescription))); + add( + new TextArea<>( + DESCRIPTION_AREA, + LambdaModel.of(model, ActivityTemplate::getDescription, ActivityTemplate::setDescription) + ) + ); - TextField daysOffset = new TextField<>(DAYS_FIELD, LambdaModel.of(model, ActivityTemplate::getDaysOffset, ActivityTemplate::setDaysOffset), Integer.class); + TextField daysOffset = new TextField<>( + DAYS_FIELD, + LambdaModel.of(model, ActivityTemplate::getDaysOffset, ActivityTemplate::setDaysOffset), + Integer.class + ); daysOffset.setRequired(true); add(daysOffset); DropDownChoice checklistTemplate = new DropDownChoice<>( - CHECKLIST_DROP_DOWN, - LambdaModel.of(model, ActivityTemplate::getChecklistTemplate, ActivityTemplate::setChecklistTemplate), - checklistTemplateService.findAll(), - new LambdaChoiceRenderer<>(ChecklistTemplate::getName, ChecklistTemplate::getId)); + CHECKLIST_DROP_DOWN, + LambdaModel.of(model, ActivityTemplate::getChecklistTemplate, ActivityTemplate::setChecklistTemplate), + checklistTemplateService.findAll(), + new LambdaChoiceRenderer<>(ChecklistTemplate::getName, ChecklistTemplate::getId) + ); checklistTemplate.setNullValid(true); add(checklistTemplate); - DropDownChoice action = new DropDownChoice<>("action", LambdaModel.of(model, ActivityTemplate::getAction, ActivityTemplate::setAction), Arrays.asList(Action.values()), new EnumChoiceRenderer<>(this)); + DropDownChoice action = new DropDownChoice<>( + "action", + LambdaModel.of(model, ActivityTemplate::getAction, ActivityTemplate::setAction), + Arrays.asList(Action.values()), + new EnumChoiceRenderer<>(this) + ); action.setRequired(true); add(action); - add(new AjaxButton(ADD_BUTTON) { - @Override - protected void onSubmit(AjaxRequestTarget target) { - AdminEditActivityPanel.this.onSubmit(target, model); + add( + new AjaxButton(ADD_BUTTON) { + @Override + protected void onSubmit(AjaxRequestTarget target) { + AdminEditActivityPanel.this.onSubmit(target, model); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePage.java index 2bf7a8c88f..23f7b384d8 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.admin.pages.AbstractAdminProjectPage; @@ -7,9 +8,9 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminActivityPl import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -public class AdminEditActivityTemplatePage extends AbstractAdminProjectPage implements MenuHighlightAdminActivityPlanTemplates { +public class AdminEditActivityTemplatePage + extends AbstractAdminProjectPage + implements MenuHighlightAdminActivityPlanTemplates { public static final String PANEL = "panel"; public static final String FEEDBACK = "feedback"; @@ -19,20 +20,33 @@ public class AdminEditActivityTemplatePage extends AbstractAdminProjectPage impl public AdminEditActivityTemplatePage(final PageParameters pageParameters) { add(new FencedFeedbackPanel(FEEDBACK, this)); - if (pageParameters.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).isNull()){ - add(new EditActivityTemplatePanel(PANEL, new DetachableServiceModel<>(activityPlanTemplateService, new ActivityPlanTemplate())){ - @Override - public boolean isSysAdminTemplate() { - return true; + if (pageParameters.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).isNull()) { + add( + new EditActivityTemplatePanel( + PANEL, + new DetachableServiceModel<>(activityPlanTemplateService, new ActivityPlanTemplate()) + ) { + @Override + public boolean isSysAdminTemplate() { + return true; + } } - }); + ); } else { - add(new EditActivityTemplatePanel(PANEL, new DetachableServiceModel<>(activityPlanTemplateService, pageParameters.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).toLong())){ - @Override - public boolean isSysAdminTemplate() { - return true; + add( + new EditActivityTemplatePanel( + PANEL, + new DetachableServiceModel<>( + activityPlanTemplateService, + pageParameters.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).toLong() + ) + ) { + @Override + public boolean isSysAdminTemplate() { + return true; + } } - }); + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityPanel.java index f137f799ad..b369baa883 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -28,12 +33,6 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) public class EditActivityPanel extends Panel { @@ -45,11 +44,12 @@ public class EditActivityPanel extends Panel { add(new ActivityForm("form", activity)); } - @Inject private ChecklistTemplateService checklistTemplateService; + @Inject private ActivityPlanFacade activityPlanFacade; + @Inject private NotificationController notificationController; @@ -61,41 +61,62 @@ public class EditActivityPanel extends Panel { public ActivityForm(String id, IModel model) { super(id, model); - add(new FeedbackPanel("feedback")); wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); add(wmc); - if (model.getObject().getChecklist()!=null){ + if (model.getObject().getChecklist() != null) { checklistTemplate = checklistTemplateService.findByName(model.getObject().getChecklist().getName()); } - TextField title = new TextField<>("title", LambdaModel.of(model, Activity::getTitle, Activity::setTitle)); + TextField title = new TextField<>( + "title", + LambdaModel.of(model, Activity::getTitle, Activity::setTitle) + ); title.setRequired(true); add(title); - TextArea description = new TextArea<>("description", LambdaModel.of(model, Activity::getDescription, Activity::setDescription)); + TextArea description = new TextArea<>( + "description", + LambdaModel.of(model, Activity::getDescription, Activity::setDescription) + ); add(description); - FormComponent dateTime = new BootstrapDateTimeComponent("dateTime", LambdaModel.of(model, Activity::getDate, Activity::setDate)); + FormComponent dateTime = new BootstrapDateTimeComponent( + "dateTime", + LambdaModel.of(model, Activity::getDate, Activity::setDate) + ); dateTime.setRequired(true); add(dateTime); - DropDownChoice action = new DropDownChoice<>("action", LambdaModel.of(model, Activity::getAction, Activity::setAction), Arrays.asList(Action.values()), new EnumChoiceRenderer<>(this)); + DropDownChoice action = new DropDownChoice<>( + "action", + LambdaModel.of(model, Activity::getAction, Activity::setAction), + Arrays.asList(Action.values()), + new EnumChoiceRenderer<>(this) + ); action.setRequired(true); add(action); - final List checklistTemplates = checklistTemplateService.findByProject(project.getObject()); - IChoiceRenderer iChoiceRenderer = new LambdaChoiceRenderer<>(ChecklistTemplate::getName, ChecklistTemplate::getId); + final List checklistTemplates = checklistTemplateService.findByProject( + project.getObject() + ); + IChoiceRenderer iChoiceRenderer = new LambdaChoiceRenderer<>( + ChecklistTemplate::getName, + ChecklistTemplate::getId + ); AjaxDropDownChoice checklist = new AjaxDropDownChoice<>( - "checklist", - LambdaModel.of(() -> checklistTemplate, newTemplate -> checklistTemplate = newTemplate), - new ListModel<>(checklistTemplates), - iChoiceRenderer) - { + "checklist", + LambdaModel.of( + () -> checklistTemplate, + newTemplate -> checklistTemplate = newTemplate + ), + new ListModel<>(checklistTemplates), + iChoiceRenderer + ) { @Override public void onNewSelection(AjaxRequestTarget target, ChecklistTemplate objectSelected) { target.add(wmc); @@ -104,11 +125,17 @@ public class EditActivityPanel extends Panel { @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forComponent(this, "change", "alert('NOTE: Changing the checklist results in loosing the connection to the previous checklist (if any)');")); + response.render( + OnEventHeaderItem.forComponent( + this, + "change", + "alert('NOTE: Changing the checklist results in loosing the connection to the previous checklist (if any)');" + ) + ); } }; - checklist .setNullValid(true); - add(checklist ); + checklist.setNullValid(true); + add(checklist); questions = new AutoHidingListView<>("questions", getSome()) { @Override @@ -124,7 +151,7 @@ public class EditActivityPanel extends Panel { boolean isNew = getModelObject().getId() == null; getModelObject().setActivityPlan(activityPlanFacade.retrieveActivityPlan(project.getObject())); - if (checklistTemplate!=null){ + if (checklistTemplate != null) { ChecklistTemplate loadedTemplate = getLoadedChecklistTemplate(checklistTemplate).getObject(); Checklist checklist = activityPlanFacade.createChecklist(project.getObject(), loadedTemplate); getModelObject().setChecklist(checklist); @@ -142,7 +169,7 @@ public class EditActivityPanel extends Panel { success("Saved activity"); } - private LoadableDetachableModel> getSome(){ + private LoadableDetachableModel> getSome() { return new LoadableDetachableModel<>() { @Override protected List load() { @@ -154,7 +181,9 @@ public class EditActivityPanel extends Panel { }; } - private LoadableDetachableModel getLoadedChecklistTemplate(final ChecklistTemplate checklistTemplate){ + private LoadableDetachableModel getLoadedChecklistTemplate( + final ChecklistTemplate checklistTemplate + ) { return new LoadableDetachableModel<>() { @Override protected ChecklistTemplate load() { diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanel.java index c5de1cbb94..477b511b67 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -15,11 +18,8 @@ import org.apache.wicket.model.Model; import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class EditActivityTemplatePanel extends GenericPanel { + public static final String FORM = "form"; public static final String TITLE_FIELD = "titleField"; public static final String DESCRIPTION_AREA = "descriptionArea"; @@ -40,13 +40,12 @@ public class EditActivityTemplatePanel extends GenericPanel model) { super(id, model); - modalWindowPlus = new ModalWindowPlus(DIALOG); add(modalWindowPlus); @@ -58,9 +57,10 @@ public class EditActivityTemplatePanel extends GenericPanel { + List activityTemplates = new ArrayList<>(); - private void swapActivities(int index1, int index2){ + private void swapActivities(int index1, int index2) { ActivityTemplate pet1 = activityTemplates.get(index1); ActivityTemplate pet2 = activityTemplates.get(index2); @@ -71,15 +71,15 @@ public class EditActivityTemplatePanel extends GenericPanel model) { super(id, model); - activityTemplates.addAll(model.getObject().getActivityTemplates()); final WebMarkupContainer container = new WebMarkupContainer(CONTAINER); container.setOutputMarkupId(true); add(container); - TextField titleField = new TextField<>(TITLE_FIELD, LambdaModel.of(model, ActivityPlanTemplate::getTitle, ActivityPlanTemplate::setTitle)); + TextField titleField = new TextField<>( + TITLE_FIELD, + LambdaModel.of(model, ActivityPlanTemplate::getTitle, ActivityPlanTemplate::setTitle) + ); titleField.setRequired(true); add(titleField); - add(new TextArea<>(DESCRIPTION_AREA, LambdaModel.of(model, ActivityPlanTemplate::getDescription, ActivityPlanTemplate::setDescription))); + add( + new TextArea<>( + DESCRIPTION_AREA, + LambdaModel.of(model, ActivityPlanTemplate::getDescription, ActivityPlanTemplate::setDescription) + ) + ); - add(new AjaxLink(ADD_LINK) { - @Override - public void onClick(AjaxRequestTarget ajaxRequestTarget) { - modalWindowPlus.setContent(new AdminEditActivityPanel(modalWindowPlus.getContentId(), new Model<>(new ActivityTemplate())) { - @Override - protected void onSubmit(AjaxRequestTarget target, IModel activity) { - modalWindowPlus.close(target); - addActivity(activity.getObject()); - target.add(container); - target.add(preview); - } - }); - modalWindowPlus.show(ajaxRequestTarget); - } - }); - - container.add(new ListView<>(ACTIVITY_LIST, () -> activityTemplates) { - @Override - protected void populateItem(final ListItem item) { - AjaxLink activityLink = new AjaxLink<>(ACTIVITY_LINK) { - @Override - public void onClick(AjaxRequestTarget ajaxRequestTarget) { - modalWindowPlus.setContent(new AdminEditActivityPanel(modalWindowPlus.getContentId(), item.getModel()) { + add( + new AjaxLink(ADD_LINK) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + modalWindowPlus.setContent( + new AdminEditActivityPanel( + modalWindowPlus.getContentId(), + new Model<>(new ActivityTemplate()) + ) { @Override protected void onSubmit(AjaxRequestTarget target, IModel activity) { modalWindowPlus.close(target); + addActivity(activity.getObject()); target.add(container); target.add(preview); } - }); - modalWindowPlus.show(ajaxRequestTarget); - } - }; - activityLink.setBody(item.getModel().map(ActivityTemplate::getTitle)); - item.add(activityLink); - - item.add(new AjaxLink(UP) { - @Override - public void onClick(AjaxRequestTarget ajaxRequestTarget) { - ajaxRequestTarget.add(container); - ajaxRequestTarget.add(preview); - swapActivities(item.getIndex(), item.getIndex() - 1); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(item.getIndex() != 0); - } - }); - - item.add(new AjaxLink(DOWN) { - @Override - public void onClick(AjaxRequestTarget ajaxRequestTarget) { - ajaxRequestTarget.add(container); - ajaxRequestTarget.add(preview); - swapActivities(item.getIndex(), item.getIndex() + 1); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(item.getIndex() + 1 != activityTemplates.size()); - } - }); - - item.add(new AjaxLink(REMOVE) { - @Override - public void onClick(AjaxRequestTarget ajaxRequestTarget) { - ajaxRequestTarget.add(container); - ajaxRequestTarget.add(preview); - removeActivity(item.getModelObject()); - } - }); + } + ); + modalWindowPlus.show(ajaxRequestTarget); + } } - }); + ); + + container.add( + new ListView<>(ACTIVITY_LIST, () -> activityTemplates) { + @Override + protected void populateItem(final ListItem item) { + AjaxLink activityLink = new AjaxLink<>(ACTIVITY_LINK) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + modalWindowPlus.setContent( + new AdminEditActivityPanel(modalWindowPlus.getContentId(), item.getModel()) { + @Override + protected void onSubmit( + AjaxRequestTarget target, + IModel activity + ) { + modalWindowPlus.close(target); + target.add(container); + target.add(preview); + } + } + ); + modalWindowPlus.show(ajaxRequestTarget); + } + }; + activityLink.setBody(item.getModel().map(ActivityTemplate::getTitle)); + item.add(activityLink); + + item.add( + new AjaxLink(UP) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + ajaxRequestTarget.add(container); + ajaxRequestTarget.add(preview); + swapActivities(item.getIndex(), item.getIndex() - 1); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(item.getIndex() != 0); + } + } + ); + + item.add( + new AjaxLink(DOWN) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + ajaxRequestTarget.add(container); + ajaxRequestTarget.add(preview); + swapActivities(item.getIndex(), item.getIndex() + 1); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(item.getIndex() + 1 != activityTemplates.size()); + } + } + ); + + item.add( + new AjaxLink(REMOVE) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + ajaxRequestTarget.add(container); + ajaxRequestTarget.add(preview); + removeActivity(item.getModelObject()); + } + } + ); + } + } + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanel.java index 2b7762c5ae..e4a7e31086 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -14,10 +17,6 @@ import se.su.dsv.scipro.components.BootstrapDateField; import se.su.dsv.scipro.components.DateLabel; import se.su.dsv.scipro.misc.DaysService; -import jakarta.inject.Inject; -import java.util.Date; -import java.util.List; - public class PreviewActivityPlanTemplatePanel extends Panel { @Inject @@ -27,46 +26,59 @@ public class PreviewActivityPlanTemplatePanel extends Panel { public PreviewActivityPlanTemplatePanel(final String id, final IModel> model) { super(id, model); - final WebMarkupContainer container = new WebMarkupContainer("container"); container.setOutputMarkupId(true); add(container); final BootstrapDateField startDateField = new BootstrapDateField("startDate", startDate); - startDateField.add(new OnChangeAjaxBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(container); + startDateField.add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(container); + } } - }); + ); add(startDateField); - container.add(new ListView<>("activities", model) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label("title", item.getModel().map(ActivityTemplate::getTitle))); - item.add(new DateLabel("date", new LoadableDetachableModel<>() { - @Override - protected Date load() { - return calculateDate(startDate, model, item.getModel()); - } - })); + container.add( + new ListView<>("activities", model) { + @Override + protected void populateItem(final ListItem item) { + item.add(new Label("title", item.getModel().map(ActivityTemplate::getTitle))); + item.add( + new DateLabel( + "date", + new LoadableDetachableModel<>() { + @Override + protected Date load() { + return calculateDate(startDate, model, item.getModel()); + } + } + ) + ); + } } - }); + ); } private Date calculateDate( - final IModel startDateModel, - final IModel> activityPlanTemplateModel, - final IModel activityTemplateModel) { - return daysService.workDaysAfter(startDateModel.getObject(), getOffset(activityPlanTemplateModel.getObject(), activityTemplateModel.getObject())); + final IModel startDateModel, + final IModel> activityPlanTemplateModel, + final IModel activityTemplateModel + ) { + return daysService.workDaysAfter( + startDateModel.getObject(), + getOffset(activityPlanTemplateModel.getObject(), activityTemplateModel.getObject()) + ); } private static int getOffset(List activityTemplates, ActivityTemplate activityTemplate) { - final int earlierOffset = activityTemplates.stream() - .filter(otherTemplate -> otherTemplate.getNumberInOrder() < activityTemplate.getNumberInOrder()) - .mapToInt(ActivityTemplate::getDaysOffset) - .sum(); + final int earlierOffset = activityTemplates + .stream() + .filter(otherTemplate -> otherTemplate.getNumberInOrder() < activityTemplate.getNumberInOrder()) + .mapToInt(ActivityTemplate::getDaysOffset) + .sum(); return earlierOffset + activityTemplate.getDaysOffset(); } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPage.java index ce337610fe..f369bd6b8c 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPage.java @@ -1,6 +1,5 @@ package se.su.dsv.scipro.activityplan; - import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorMyProjects; import se.su.dsv.scipro.project.pages.AbstractProjectDetailsPage; @@ -9,15 +8,15 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; -@Authorization(authorizedRoles={Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) public class ProjectActivityPlanPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects { - - public ProjectActivityPlanPage(final PageParameters pp){ - super(pp); - if(getActiveProject() == null || loggedInUser() == null) { + + public ProjectActivityPlanPage(final PageParameters pp) { + super(pp); + if (getActiveProject() == null || loggedInUser() == null) { throw new IllegalStateException("No valid project or user"); } - add(new ActivityPlanPanel("activityPlan", projectModel)); - } + add(new ActivityPlanPanel("activityPlan", projectModel)); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPage.java index f1f0c622c7..3a66ccd47c 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -14,11 +15,10 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles={Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) public class ProjectEditActivityPage extends AbstractProjectDetailsPage implements MenuHighlightActivityPlan { + private static final long INVALID_ID = -1; @Inject @@ -26,16 +26,24 @@ public class ProjectEditActivityPage extends AbstractProjectDetailsPage implemen public ProjectEditActivityPage(PageParameters pp) { super(pp); - final StringValue parameter = pp.get(PageParameterKeys.MAP.get(Activity.class)); if (parameter.isNull()) { - add(new EditActivityPanel("edit", projectModel, new DetachableServiceModel<>(activityService, new Activity()))); + add( + new EditActivityPanel( + "edit", + projectModel, + new DetachableServiceModel<>(activityService, new Activity()) + ) + ); } else { final long activityId = parameter.toLong(INVALID_ID); final IModel activityModel = new DetachableServiceModel<>(activityService, activityId); final Activity activity = activityModel.getObject(); - if (activity == null || !activity.getActivityPlan().getProject().isParticipant(SciProSession.get().getUser())) { + if ( + activity == null || + !activity.getActivityPlan().getProject().isParticipant(SciProSession.get().getUser()) + ) { throw new RestartResponseException(getApplication().getHomePage()); } add(new EditActivityPanel("edit", projectModel, activityModel)); diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanel.java index d3f75c3f6f..92ab650c35 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.feedback.FencedFeedbackPanel; @@ -12,42 +13,45 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class SaveAsTemplatePanel extends GenericPanel { + @Inject private ActivityPlanFacade activityPlanFacade; - public SaveAsTemplatePanel(final String id, final IModel activityPlan){ - super(id, activityPlan); + public SaveAsTemplatePanel(final String id, final IModel activityPlan) { + super(id, activityPlan); final FencedFeedbackPanel feedback = new FencedFeedbackPanel("feedback", this); feedback.setOutputMarkupId(true); add(feedback); - final TextField title = new RequiredTextField<>("title",new Model<>("")); - final TextArea description = new TextArea<>("description",new Model<>("")); - Form form = new Form<>("form", activityPlan); - form.add(title); - form.add(description); - form.add(new AjaxSubmitLink("save") { - @Override - protected void onSubmit(final AjaxRequestTarget target) { - target.add(feedback); - ActivityPlanTemplate schedule = activityPlanFacade.createTemplateFromSchedule( + final TextField title = new RequiredTextField<>("title", new Model<>("")); + final TextArea description = new TextArea<>("description", new Model<>("")); + Form form = new Form<>("form", activityPlan); + form.add(title); + form.add(description); + form.add( + new AjaxSubmitLink("save") { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + target.add(feedback); + ActivityPlanTemplate schedule = activityPlanFacade.createTemplateFromSchedule( SaveAsTemplatePanel.this.getModelObject(), SciProSession.get().getUser(), title.getModelObject(), - description.getModelObject()); - title.setModelObject(""); - title.clearInput(); - description.setModelObject(""); - description.clearInput(); - success(getString("saved.as.template", Model.of(schedule))); + description.getModelObject() + ); + title.setModelObject(""); + title.clearInput(); + description.setModelObject(""); + description.clearInput(); + success(getString("saved.as.template", Model.of(schedule))); + } + + @Override + protected void onError(final AjaxRequestTarget target) { + target.add(feedback); + } } - @Override - protected void onError(final AjaxRequestTarget target) { - target.add(feedback); - } - }); - add(form); - } + ); + add(form); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPage.java index 1c7480416c..154aa89a1a 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPage.java @@ -1,6 +1,5 @@ package se.su.dsv.scipro.activityplan; - import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyProjects; @@ -10,16 +9,18 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; -@Authorization(authorizedRoles={Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) -public class SupervisorActivityPlanPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { - - public SupervisorActivityPlanPage(final PageParameters pp){ - super(pp); - if(projectModel.getObject() == null) { +public class SupervisorActivityPlanPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { + + public SupervisorActivityPlanPage(final PageParameters pp) { + super(pp); + if (projectModel.getObject() == null) { add(new Label("activityPlan", "No project selected")); } else { add(new SupervisorActivityPlanPanel("activityPlan", projectModel)); } - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPanel.java index b080db45f5..5b0fd19312 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPanel.java @@ -16,9 +16,3 @@ public class SupervisorActivityPlanPanel extends ActivityPlanPanel { return SupervisorViewChecklistPage.class; } } - - - - - - diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPage.java index 686c07ff9f..0ee96c770e 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.activityplan; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -9,37 +11,40 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; import se.su.dsv.scipro.util.PageParameterKeys; -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) -public class SupervisorActivityPlanTemplatesPage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorActivityTemplates { +@Authorization(authorizedRoles = { SUPERVISOR }) +public class SupervisorActivityPlanTemplatesPage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorActivityTemplates { private ModalWindowPlus modalWindowPlus; public SupervisorActivityPlanTemplatesPage(final PageParameters pp) { super(pp); - modalWindowPlus = new ModalWindowPlus("dialog"); add(modalWindowPlus); - add(new ActivityPlanTemplateDataPanel("activityPlanTemplatePanel") { - @Override - public void onNewClick() { - setResponsePage(SupervisorEditActivityTemplatePage.class); - } + add( + new ActivityPlanTemplateDataPanel("activityPlanTemplatePanel") { + @Override + public void onNewClick() { + setResponsePage(SupervisorEditActivityTemplatePage.class); + } - @Override - public void onTitleClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setContent(new ActivityPlanTemplateDetailsPanel(modalWindowPlus.getContentId(), clicked)); - modalWindowPlus.show(target); - } + @Override + public void onTitleClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setContent( + new ActivityPlanTemplateDetailsPanel(modalWindowPlus.getContentId(), clicked) + ); + modalWindowPlus.show(target); + } - @Override - public void onEditClick(IModel clicked) { - PageParameters pp = new PageParameters(); - pp.set(PageParameterKeys.MAP.get(ActivityPlanTemplate.class), clicked.getObject().getId()); - setResponsePage(SupervisorEditActivityTemplatePage.class, pp); + @Override + public void onEditClick(IModel clicked) { + PageParameters pp = new PageParameters(); + pp.set(PageParameterKeys.MAP.get(ActivityPlanTemplate.class), clicked.getObject().getId()); + setResponsePage(SupervisorEditActivityTemplatePage.class, pp); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPage.java index eba8a531b1..0c18fe8417 100755 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -16,11 +17,12 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles={Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) -public class SupervisorEditActivityPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorActivityPlan { +public class SupervisorEditActivityPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorActivityPlan { + public static final long INVALID_ID = -1; @Inject @@ -28,10 +30,15 @@ public class SupervisorEditActivityPage extends AbstractSupervisorProjectDetails public SupervisorEditActivityPage(PageParameters pp) { super(pp); - final StringValue parameter = pp.get(PageParameterKeys.MAP.get(Activity.class)); if (parameter.isNull()) { - add(new EditActivityPanel("edit", projectModel, new DetachableServiceModel<>(activityService, new Activity()))); + add( + new EditActivityPanel( + "edit", + projectModel, + new DetachableServiceModel<>(activityService, new Activity()) + ) + ); } else { final long activityId = parameter.toLong(INVALID_ID); final IModel activityModel = new DetachableServiceModel<>(activityService, activityId); diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePage.java b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePage.java index 03113925a5..c1235867cd 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePage.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePage.java @@ -1,24 +1,40 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorActivityTemplates; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; +public class SupervisorEditActivityTemplatePage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorActivityTemplates { -public class SupervisorEditActivityTemplatePage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorActivityTemplates { public static final String PANEL = "panel"; + @Inject private ActivityPlanTemplateService activityPlanTemplateService; public SupervisorEditActivityTemplatePage(PageParameters pp) { super(pp); - if (pp.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).isNull()){ - add(new EditActivityTemplatePanel(PANEL, new DetachableServiceModel<>(activityPlanTemplateService, new ActivityPlanTemplate()))); + if (pp.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).isNull()) { + add( + new EditActivityTemplatePanel( + PANEL, + new DetachableServiceModel<>(activityPlanTemplateService, new ActivityPlanTemplate()) + ) + ); } else { - add(new EditActivityTemplatePanel(PANEL, new DetachableServiceModel<>(activityPlanTemplateService, pp.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).toLong()))); + add( + new EditActivityTemplatePanel( + PANEL, + new DetachableServiceModel<>( + activityPlanTemplateService, + pp.get(PageParameterKeys.MAP.get(ActivityPlanTemplate.class)).toLong() + ) + ) + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanel.java b/view/src/main/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanel.java index d3d400648c..b5c493d321 100644 --- a/view/src/main/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import jakarta.inject.Inject; +import java.util.Date; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -8,19 +11,15 @@ import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.StringResourceModel; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.DateLabel; import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectModule; - -import jakarta.inject.Inject; -import java.util.Date; -import java.util.List; +import se.su.dsv.scipro.system.Sort; @ProjectModuleComponent(ProjectModule.ACTIVITY_PLAN) public abstract class UpcomingActivitiesPanel extends Panel { @@ -34,40 +33,58 @@ public abstract class UpcomingActivitiesPanel extends Panel { public UpcomingActivitiesPanel(String id, IModel model) { super(id, model); - - final List events = activityPlanFacade.findEventsByProject(model.getObject(), new Date(), null, new PageRequest(0, 5, new Sort(Sort.Direction.ASC, "date"))); + final List events = activityPlanFacade.findEventsByProject( + model.getObject(), + new Date(), + null, + new PageRequest(0, 5, new Sort(Sort.Direction.ASC, "date")) + ); listView = new ListView<>(LIST, events) { @Override protected void populateItem(ListItem item) { final IModel activityModel = item.getModel(); final IModel titleModel = LambdaModel.of(activityModel, Activity::getTitle, Activity::setTitle); - item.add(new DateLabel(DATE, LambdaModel.of(activityModel, Activity::getDate, Activity::setDate), DateStyle.DATETIME)); - item.add(new BookmarkablePageLink(AUTHOR_LINK, ProjectActivityPlanPage.class) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isAuthorView()); - } - }.add(new Label(AUTHOR_LABEL, titleModel))); - item.add(new BookmarkablePageLink(EMPLOYEE_LINK, SupervisorActivityPlanPage.class) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isAuthorView() && SciProSession.get().authorizedForRole(Roles.SUPERVISOR)); - } - }.add(new Label(EMPLOYEE_LABEL, titleModel))); + item.add( + new DateLabel( + DATE, + LambdaModel.of(activityModel, Activity::getDate, Activity::setDate), + DateStyle.DATETIME + ) + ); + item.add( + new BookmarkablePageLink(AUTHOR_LINK, ProjectActivityPlanPage.class) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isAuthorView()); + } + }.add(new Label(AUTHOR_LABEL, titleModel)) + ); + item.add( + new BookmarkablePageLink(EMPLOYEE_LINK, SupervisorActivityPlanPage.class) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + !isAuthorView() && SciProSession.get().authorizedForRole(Roles.SUPERVISOR) + ); + } + }.add(new Label(EMPLOYEE_LABEL, titleModel)) + ); } }; add(listView); - add(new Label(NO, new StringResourceModel("no", this, null)){ - @Override - protected void onConfigure(){ - super.onConfigure(); - setVisibilityAllowed(events.isEmpty()); + add( + new Label(NO, new StringResourceModel("no", this, null)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(events.isEmpty()); + } } - }); + ); } public static final String LIST = "list"; diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminMailPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminMailPage.java index 8bcba38d53..a85e371c8d 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminMailPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminMailPage.java @@ -1,26 +1,27 @@ package se.su.dsv.scipro.admin.pages; -import se.su.dsv.scipro.components.AbstractMenuPanel; - import java.util.ArrayList; import java.util.List; +import se.su.dsv.scipro.components.AbstractMenuPanel; public abstract class AbstractAdminMailPage extends AbstractAdminPage { + protected AbstractAdminMailPage() { - add(new AbstractMenuPanel("menuPanel", AbstractAdminMailPage.class, this.getClass()){ - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("Compose", AdminMailPage.class)); - items.add(new MenuItem("Log", AdminMailLogPage.class)); - return items; - } + add( + new AbstractMenuPanel("menuPanel", AbstractAdminMailPage.class, this.getClass()) { + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("Compose", AdminMailPage.class)); + items.add(new MenuItem("Log", AdminMailLogPage.class)); + return items; + } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } } - - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminPage.java index 8de601f2c2..513155a997 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.components.AbstractMenuPanel; @@ -12,11 +15,7 @@ import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.statistics.AdminStatisticsPage; import se.su.dsv.scipro.user.AdminUsersPage; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - -@Authorization(authorizedRoles={Roles.SYSADMIN, Roles.ADMIN, Roles.STUDADM}) +@Authorization(authorizedRoles = { Roles.SYSADMIN, Roles.ADMIN, Roles.STUDADM }) public abstract class AbstractAdminPage extends MenuPage { @Inject diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminProjectPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminProjectPage.java index 8fa344c822..1909e0853c 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminProjectPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages; +import java.util.Arrays; +import java.util.List; import se.su.dsv.scipro.activityplan.AdminActivityPlanTemplatesPage; import se.su.dsv.scipro.admin.pages.grading.AdminGradingTemplatesOverviewPage; import se.su.dsv.scipro.admin.pages.grading.MenuHighlightGradingTemplates; @@ -12,33 +14,52 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminProjectMan import se.su.dsv.scipro.finalseminar.AdminFinalSeminarPage; import se.su.dsv.scipro.nonworkdays.NonWorkDaysPage; -import java.util.Arrays; -import java.util.List; - public class AbstractAdminProjectPage extends AbstractAdminPage { public static final String TABS = "tabs"; public AbstractAdminProjectPage() { - add(new AbstractMenuPanel(TABS, AbstractAdminProjectPage.class, this.getClass()) { - @Override - protected List getItemList() { - return Arrays.asList( - new MenuItem("Projects", ProjectManagementPage.class, MenuHighlightAdminProjectManagement.class), - new MenuItem("Final seminars", AdminFinalSeminarPage.class, MenuHighlightAdminFinalSeminars.class), - new MenuItem("Activity plan templates", AdminActivityPlanTemplatesPage.class, MenuHighlightAdminActivityPlanTemplates.class), - new MenuItem("Checklist templates", AdminChecklistPage.class, MenuHighlightAdminChecklist.class), + add( + new AbstractMenuPanel(TABS, AbstractAdminProjectPage.class, this.getClass()) { + @Override + protected List getItemList() { + return Arrays.asList( + new MenuItem( + "Projects", + ProjectManagementPage.class, + MenuHighlightAdminProjectManagement.class + ), + new MenuItem( + "Final seminars", + AdminFinalSeminarPage.class, + MenuHighlightAdminFinalSeminars.class + ), + new MenuItem( + "Activity plan templates", + AdminActivityPlanTemplatesPage.class, + MenuHighlightAdminActivityPlanTemplates.class + ), + new MenuItem( + "Checklist templates", + AdminChecklistPage.class, + MenuHighlightAdminChecklist.class + ), new MenuItem("Non work days", NonWorkDaysPage.class), new MenuItem("Survey", AdminSurveyPage.class), new MenuItem("Reviewer targets", AdminReviewerCapacityManagementPage.class), - new MenuItem("Grading templates", AdminGradingTemplatesOverviewPage.class, MenuHighlightGradingTemplates.class) - ); - } + new MenuItem( + "Grading templates", + AdminGradingTemplatesOverviewPage.class, + MenuHighlightGradingTemplates.class + ) + ); + } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminSystemPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminSystemPage.java index 1266d715b5..c925dcffbf 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminSystemPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AbstractAdminSystemPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.feedback.FencedFeedbackPanel; import se.su.dsv.scipro.admin.pages.settings.*; import se.su.dsv.scipro.components.AbstractMenuPanel; @@ -12,38 +14,37 @@ import se.su.dsv.scipro.peer.AdminPeerSettingsPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import java.util.ArrayList; -import java.util.List; - @Authorization(authorizedRoles = { Roles.SYSADMIN }) public abstract class AbstractAdminSystemPage extends AbstractAdminPage { - protected AbstractAdminSystemPage() { - add(new FencedFeedbackPanel("feedbackPanel", this)); - - add(new AbstractMenuPanel("menuPanel", AbstractAdminSystemPage.class, this.getClass()){ - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("General settings", AdminGeneralSettingsPage.class)); - items.add(new MenuItem("Final seminar settings", AdminFinalSeminarSettingsPage.class)); - items.add(new MenuItem("URKUND settings", AdminUrkundSettingsPage.class)); - items.add(new MenuItem("Peer settings", AdminPeerSettingsPage.class)); - items.add(new MenuItem("Type settings", AdminProjectTypeSettingsPage.class)); - items.add(new MenuItem("Notification settings", AdminNotificationSettingsPage.class)); - items.add(new MenuItem("Milestone settings", AdminMileStoneSettingsPage.class)); - items.add(new MenuItem("Maintenance", SystemMaintenancePage.class)); - items.add(new MenuItem("Project module settings", AdminProjectModuleSettingsPage.class)); - items.add(new MenuItem("Footer settings", AdminFooterSettingsPage.class)); - items.add(new MenuItem("Reviewer deadline settings", AdminReviewerDeadlineSettingsPage.class)); - items.add(new MenuItem("GDPR", AdminGDPRPage.class)); - return items; - } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; - } - - }); - } -} \ No newline at end of file + protected AbstractAdminSystemPage() { + add(new FencedFeedbackPanel("feedbackPanel", this)); + + add( + new AbstractMenuPanel("menuPanel", AbstractAdminSystemPage.class, this.getClass()) { + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("General settings", AdminGeneralSettingsPage.class)); + items.add(new MenuItem("Final seminar settings", AdminFinalSeminarSettingsPage.class)); + items.add(new MenuItem("URKUND settings", AdminUrkundSettingsPage.class)); + items.add(new MenuItem("Peer settings", AdminPeerSettingsPage.class)); + items.add(new MenuItem("Type settings", AdminProjectTypeSettingsPage.class)); + items.add(new MenuItem("Notification settings", AdminNotificationSettingsPage.class)); + items.add(new MenuItem("Milestone settings", AdminMileStoneSettingsPage.class)); + items.add(new MenuItem("Maintenance", SystemMaintenancePage.class)); + items.add(new MenuItem("Project module settings", AdminProjectModuleSettingsPage.class)); + items.add(new MenuItem("Footer settings", AdminFooterSettingsPage.class)); + items.add(new MenuItem("Reviewer deadline settings", AdminReviewerDeadlineSettingsPage.class)); + items.add(new MenuItem("GDPR", AdminGDPRPage.class)); + return items; + } + + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } + } + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminAssignReviewerPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminAssignReviewerPage.java index 3d137d35b0..0c2acf7188 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminAssignReviewerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminAssignReviewerPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.time.Clock; +import java.time.LocalDate; +import java.util.ArrayList; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.GenericWebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -37,13 +41,9 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.LocalDate; -import java.util.ArrayList; - -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class AdminAssignReviewerPage extends AbstractAdminProjectPage { + @Inject private ProjectService projectService; @@ -72,45 +72,63 @@ public class AdminAssignReviewerPage extends AbstractAdminProjectPage { } private static class ProjectDetailsPanel extends WebMarkupContainer { + @Inject private RoughDraftApprovalService roughDraftApprovalService; public ProjectDetailsPanel(String id, IModel projectModel) { super(id, projectModel); - IModel roughDraftApproval = LoadableDetachableModel.of(() -> - roughDraftApprovalService.findBy(projectModel.getObject()).orElse(null)); + roughDraftApprovalService.findBy(projectModel.getObject()).orElse(null) + ); add(new Label("title", projectModel.map(Project::getTitle))); add(new Label("research_area", projectModel.map(Project::getResearchArea).map(ResearchArea::getTitle))); add(new UserLinkPanel("supervisor", projectModel.map(Project::getHeadSupervisor))); - add(new EnumLabel<>("language", projectModel.map(Project::getLanguage)){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); + add( + new EnumLabel<>("language", projectModel.map(Project::getLanguage)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } } - }); - add(new ViewAttachmentPanel("rough_draft", roughDraftApproval.map(RoughDraftApproval::getCurrentThesis).map(FileReference::getFileDescription))); - add(new DateLabel("requested_at", roughDraftApproval.map(RoughDraftApproval::getCurrentDecision).map(Decision::getRequested), DateStyle.DATETIME) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); + ); + add( + new ViewAttachmentPanel( + "rough_draft", + roughDraftApproval.map(RoughDraftApproval::getCurrentThesis).map(FileReference::getFileDescription) + ) + ); + add( + new DateLabel( + "requested_at", + roughDraftApproval.map(RoughDraftApproval::getCurrentDecision).map(Decision::getRequested), + DateStyle.DATETIME + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } } - }); - add(new ListView<>("authors", projectModel.map(Project::getProjectParticipants).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel("author", item.getModel())); + ); + add( + new ListView<>("authors", projectModel.map(Project::getProjectParticipants).map(ArrayList::new)) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel("author", item.getModel())); + } } - }); + ); } } private static class AvailableReviewersPanel extends GenericWebMarkupContainer { + @Inject private ReviewerAssignmentService reviewerAssignmentService; + @Inject private Clock clock; @@ -118,61 +136,80 @@ public class AdminAssignReviewerPage extends AbstractAdminProjectPage { public AvailableReviewersPanel(String id, IModel projectModel) { super(id, projectModel); - add(new FeedbackPanel("feedback")); reviewerCandidates = LoadableDetachableModel.of(() -> - reviewerAssignmentService.getCandidatesToReview(projectModel.getObject(), LocalDate.now(clock))); + reviewerAssignmentService.getCandidatesToReview(projectModel.getObject(), LocalDate.now(clock)) + ); IModel period = reviewerCandidates.map(ReviewerCandidates::period); add(new CurrentReviewerCard("current_reviewer", projectModel.map(Project::getReviewer), period)); - add(new AutoHidingListView<>("good_candidates", reviewerCandidates.map(ReviewerCandidates::good)) { - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("details", item.getModel(), period)); + add( + new AutoHidingListView<>("good_candidates", reviewerCandidates.map(ReviewerCandidates::good)) { + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("details", item.getModel(), period)); + } } - }); - add(new AutoHidingListView<>("wrong_research_area", reviewerCandidates.map(ReviewerCandidates::wrongResearchArea)) { - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("details", item.getModel(), period)); + ); + add( + new AutoHidingListView<>( + "wrong_research_area", + reviewerCandidates.map(ReviewerCandidates::wrongResearchArea) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("details", item.getModel(), period)); + } } - }); - add(new WebMarkupContainer("no_language_set") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(projectModel.getObject().getLanguage() == null); + ); + add( + new WebMarkupContainer("no_language_set") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(projectModel.getObject().getLanguage() == null); + } } - }); - add(new AutoHidingListView<>("wrong_language", reviewerCandidates.map(ReviewerCandidates::wrongLanguage)) { - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("details", item.getModel(), period)); + ); + add( + new AutoHidingListView<>("wrong_language", reviewerCandidates.map(ReviewerCandidates::wrongLanguage)) { + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("details", item.getModel(), period)); + } } - }); - add(new AutoHidingListView<>("busy_candidates", reviewerCandidates.map(ReviewerCandidates::busy)) { - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("details", item.getModel(), period)); + ); + add( + new AutoHidingListView<>("busy_candidates", reviewerCandidates.map(ReviewerCandidates::busy)) { + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("details", item.getModel(), period)); + } } - }); - add(new AutoHidingListView<>("unavailable_candidates", reviewerCandidates.map(ReviewerCandidates::unavailable)) { - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("details", item.getModel(), period)); + ); + add( + new AutoHidingListView<>( + "unavailable_candidates", + reviewerCandidates.map(ReviewerCandidates::unavailable) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("details", item.getModel(), period)); + } } - }); + ); } private class CurrentReviewerCard extends GenericWebMarkupContainer { + public CurrentReviewerCard(String id, IModel reviewer, IModel period) { super(id, reviewer); - IModel currentTarget = LoadableDetachableModel.of(() -> - reviewerAssignmentService.getCurrentTarget(reviewer.getObject(), LocalDate.now(clock))); + reviewerAssignmentService.getCurrentTarget(reviewer.getObject(), LocalDate.now(clock)) + ); add(new Label("assigned", currentTarget.map(ReviewerAssignmentService.CurrentTarget::assigned))); add(new Label("target", currentTarget.map(ReviewerAssignmentService.CurrentTarget::target))); @@ -181,32 +218,43 @@ public class AdminAssignReviewerPage extends AbstractAdminProjectPage { add(new UserProfileImage("image", reviewer, UserProfileImage.Size.MEDIUM)); add(new UserLabel("name", reviewer)); - add(new AutoHidingListView<>("research_areas", reviewer.map(User::getResearchAreas).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("research_area", item.getModel().map(ResearchArea::getTitle))); + add( + new AutoHidingListView<>( + "research_areas", + reviewer.map(User::getResearchAreas).map(ArrayList::new) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("research_area", item.getModel().map(ResearchArea::getTitle))); + } } - }); - add(new WebMarkupContainer("none") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(reviewer.getObject().getResearchAreas().isEmpty()); + ); + add( + new WebMarkupContainer("none") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(reviewer.getObject().getResearchAreas().isEmpty()); + } } - }); - add(new AutoHidingListView<>("languages", reviewer.map(User::getLanguages).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - item.add(new EnumLabel<>("language", item.getModel())); + ); + add( + new AutoHidingListView<>("languages", reviewer.map(User::getLanguages).map(ArrayList::new)) { + @Override + protected void populateItem(ListItem item) { + item.add(new EnumLabel<>("language", item.getModel())); + } } - }); - add(new Link<>("unassign", reviewer) { - @Override - public void onClick() { - reviewerAssignmentService.unassignReviewer(AvailableReviewersPanel.this.getModelObject()); - AvailableReviewersPanel.this.success(getString("reviewer_unassigned")); + ); + add( + new Link<>("unassign", reviewer) { + @Override + public void onClick() { + reviewerAssignmentService.unassignReviewer(AvailableReviewersPanel.this.getModelObject()); + AvailableReviewersPanel.this.success(getString("reviewer_unassigned")); + } } - }); + ); } @Override @@ -217,7 +265,12 @@ public class AdminAssignReviewerPage extends AbstractAdminProjectPage { } private class ReviewerCard extends Fragment { - public ReviewerCard(String id, IModel candidate, IModel period) { + + public ReviewerCard( + String id, + IModel candidate, + IModel period + ) { super(id, "reviewer_details", AvailableReviewersPanel.this, candidate); IModel reviewer = candidate.map(ReviewerCandidates.Candidate::reviewer); add(new UserProfileImage("image", reviewer, UserProfileImage.Size.MEDIUM)); @@ -227,56 +280,78 @@ public class AdminAssignReviewerPage extends AbstractAdminProjectPage { add(new Label("period_year", period.map(ReviewPeriod::year))); add(new EnumLabel<>("period_part", period.map(ReviewPeriod::part))); add(new Label("note", candidate.map(ReviewerCandidates.Candidate::note))); - add(new ListView<>("research_areas", reviewer.map(User::getResearchAreas).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("research_area", item.getModel().map(ResearchArea::getTitle))); + add( + new ListView<>("research_areas", reviewer.map(User::getResearchAreas).map(ArrayList::new)) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("research_area", item.getModel().map(ResearchArea::getTitle))); + } } - }); - add(new WebMarkupContainer("none") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(reviewer.getObject().getResearchAreas().isEmpty()); + ); + add( + new WebMarkupContainer("none") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(reviewer.getObject().getResearchAreas().isEmpty()); + } } - }); - add(new ListView<>("languages", reviewer.map(User::getLanguages).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - item.add(new EnumLabel<>("language", item.getModel())); + ); + add( + new ListView<>("languages", reviewer.map(User::getLanguages).map(ArrayList::new)) { + @Override + protected void populateItem(ListItem item) { + item.add(new EnumLabel<>("language", item.getModel())); + } } - }); + ); add(new AssignReviewerLink("assign", reviewer)); } } private class AssignReviewerLink extends Link { + public AssignReviewerLink(String id, IModel reviewer) { super(id, reviewer); - setBody(AvailableReviewersPanel.this.getModel().map(project -> { - if (project.getReviewer() == null) { - return "Assign"; - } else { - return "Switch to"; - } - })); + setBody( + AvailableReviewersPanel.this.getModel() + .map(project -> { + if (project.getReviewer() == null) { + return "Assign"; + } else { + return "Switch to"; + } + }) + ); } @Override public void onClick() { - ReviewerAssignmentService.ReviewerAssignment reviewerAssignment = reviewerAssignmentService.assignReviewer( + ReviewerAssignmentService.ReviewerAssignment reviewerAssignment = + reviewerAssignmentService.assignReviewer( AvailableReviewersPanel.this.getModelObject(), - getModelObject()); + getModelObject() + ); switch (reviewerAssignment) { // Put the feedback message in the parent container since this component will be // lost when the ListView recreates its ListItems - case OK -> AvailableReviewersPanel.this.success(AvailableReviewersPanel.this.getString("reviewer_assigned")); + case OK -> AvailableReviewersPanel.this.success( + AvailableReviewersPanel.this.getString("reviewer_assigned") + ); case WARNING_NO_REVIEW_REQUEST -> { - AvailableReviewersPanel.this.success(AvailableReviewersPanel.this.getString("reviewer_assigned")); - AvailableReviewersPanel.this.warn(AvailableReviewersPanel.this.getString("warning_no_review_request")); + AvailableReviewersPanel.this.success( + AvailableReviewersPanel.this.getString("reviewer_assigned") + ); + AvailableReviewersPanel.this.warn( + AvailableReviewersPanel.this.getString("warning_no_review_request") + ); } - case ERROR_IS_SUPERVISOR -> AvailableReviewersPanel.this.error(AvailableReviewersPanel.this.getString("error_reviewer_is_supervisor")); - case ERROR_IS_NOT_REVIEWER -> AvailableReviewersPanel.this.error(AvailableReviewersPanel.this.getString("error_reviewer_is_not_reviewer")); + case ERROR_IS_SUPERVISOR -> AvailableReviewersPanel.this.error( + AvailableReviewersPanel.this.getString("error_reviewer_is_supervisor") + ); + case ERROR_IS_NOT_REVIEWER -> AvailableReviewersPanel.this.error( + AvailableReviewersPanel.this.getString("error_reviewer_is_not_reviewer") + ); } // have to detach the model since fetching the model object for this component will // cause the model object for the ListItem which will cause the ListView to be loaded and diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectConfirmationPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectConfirmationPage.java index 0b3b45f8ae..34597a7c98 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectConfirmationPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectConfirmationPage.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.admin.pages; import jakarta.inject.Inject; +import java.util.*; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.link.Link; @@ -21,12 +23,13 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; import se.su.dsv.scipro.util.Pair; -import java.util.*; -import java.util.stream.Collectors; +public class AdminCreateProjectConfirmationPage + extends AbstractAdminProjectPage + implements MenuHighlightAdminProjectManagement { -public class AdminCreateProjectConfirmationPage extends AbstractAdminProjectPage implements MenuHighlightAdminProjectManagement { @Inject private NotificationController notificationController; + @Inject private ProjectService projectService; @@ -38,22 +41,30 @@ public class AdminCreateProjectConfirmationPage extends AbstractAdminProjectPage } private class CreateProjectForm extends Form { + public CreateProjectForm(String id, final IModel model) { super(id, model); - add(new Label("title", model.flatMap(SerializableProject::getTitle))); add(new Label("type", model.flatMap(SerializableProject::getProjectType).map(ProjectType::getName))); add(new Label("authors", model.flatMap(SerializableProject::getAuthors).map(this::userFullNames))); add(new Label("supervisor", model.flatMap(SerializableProject::getSupervisor).map(User::getFullName))); add(new Label("reviewers", model.flatMap(SerializableProject::getReviewers).map(this::userFullNames))); - add(new Label("coSupervisors", model.flatMap(SerializableProject::getCoSupervisors).map(this::userFullNames))); + add( + new Label( + "coSupervisors", + model.flatMap(SerializableProject::getCoSupervisors).map(this::userFullNames) + ) + ); - ListView> activeProjects = new ListView<>("pairs", new LoadableDetachableModel>>() { - @Override - protected List> load() { - return getAuthorsWithCurrentActiveProjects(); + ListView> activeProjects = new ListView<>( + "pairs", + new LoadableDetachableModel>>() { + @Override + protected List> load() { + return getAuthorsWithCurrentActiveProjects(); + } } - }) { + ) { @Override protected void populateItem(ListItem> item) { IModel student = item.getModel().map(Pair::getHead); @@ -65,19 +76,19 @@ public class AdminCreateProjectConfirmationPage extends AbstractAdminProjectPage }; add(activeProjects); - add(new Link("cancel") { - @Override - public void onClick() { - getSession().info(getString("canceled", CreateProjectForm.this.getModelObject().getTitle())); - setResponsePage(new AdminCreateProjectPage(CreateProjectForm.this.getModel())); + add( + new Link("cancel") { + @Override + public void onClick() { + getSession().info(getString("canceled", CreateProjectForm.this.getModelObject().getTitle())); + setResponsePage(new AdminCreateProjectPage(CreateProjectForm.this.getModel())); + } } - }); + ); } private String userFullNames(Collection users) { - return users.stream() - .map(User::getFullName) - .collect(Collectors.joining(", ")); + return users.stream().map(User::getFullName).collect(Collectors.joining(", ")); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPage.java index 2656b2ea90..1ddd02ef36 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.LambdaChoiceRenderer; @@ -29,10 +32,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchService; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - /** * Can't re-use AdminEditProjectPage due to it using a backing Project which will get serialized to * disk alongside its attributes which are all attached JPA entities. When trying to traverse the @@ -42,22 +41,34 @@ import java.util.*; * We have to use detachable models for all entity attributes, so they are loaded from the * EntityManager again on the next request, so they are attached and can be traversed. */ -@Authorization(authorizedRoles = {Roles.SYSADMIN}) -public class AdminCreateProjectPage extends AbstractAdminProjectPage - implements MenuHighlightAdminProjectManagement -{ +@Authorization(authorizedRoles = { Roles.SYSADMIN }) +public class AdminCreateProjectPage extends AbstractAdminProjectPage implements MenuHighlightAdminProjectManagement { + @Inject UserSearchService userSearchService; - @Inject UserService userService; - @Inject ProjectTypeService projectTypeService; - @Inject ResearchAreaService researchAreaService; - @Inject ProjectService projectService; - @Inject NotificationController notificationController; + + @Inject + UserService userService; + + @Inject + ProjectTypeService projectTypeService; + + @Inject + ResearchAreaService researchAreaService; + + @Inject + ProjectService projectService; + + @Inject + NotificationController notificationController; @SuppressWarnings("unused") // used by wicket bookmarkable links public AdminCreateProjectPage() { - final SerializableProject serializableProject = - new SerializableProject(userService, projectTypeService, researchAreaService); + final SerializableProject serializableProject = new SerializableProject( + userService, + projectTypeService, + researchAreaService + ); add(new CreateProjectForm("form", Model.of(serializableProject))); } @@ -66,75 +77,85 @@ public class AdminCreateProjectPage extends AbstractAdminProjectPage } private class CreateProjectForm extends Form { + public CreateProjectForm(String id, final IModel model) { super(id, model); - add(new FeedbackPanel("feedback")); - TextField titleField = new TextField<>( - "title", - getModel().flatMap(SerializableProject::getTitle)); + TextField titleField = new TextField<>("title", getModel().flatMap(SerializableProject::getTitle)); titleField.setRequired(true); add(titleField); DropDownChoice projectTypeChoice = new DropDownChoice<>( - "projectType", - getModel().flatMap(SerializableProject::getProjectType), - projectTypeService::findAllActive, - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); + "projectType", + getModel().flatMap(SerializableProject::getProjectType), + projectTypeService::findAllActive, + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); projectTypeChoice.setRequired(true); add(projectTypeChoice); TextField startDateField = new TextField<>( - "startDate", - getModel().flatMap(SerializableProject::getStartDate), - LocalDate.class); + "startDate", + getModel().flatMap(SerializableProject::getStartDate), + LocalDate.class + ); startDateField.add(new BootstrapDatePicker()); startDateField.setRequired(true); add(startDateField); TextField expectedEndDateField = new TextField<>( - "expectedEndDate", - getModel().flatMap(SerializableProject::getExpectedEndDate), - LocalDate.class); + "expectedEndDate", + getModel().flatMap(SerializableProject::getExpectedEndDate), + LocalDate.class + ); expectedEndDateField.add(new BootstrapDatePicker()); add(expectedEndDateField); - ChoiceProvider supervisorChoices = - new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.SUPERVISOR)); + ChoiceProvider supervisorChoices = new AutoCompleteRoleProvider( + userSearchService, + EnumSet.of(Roles.SUPERVISOR) + ); DefaultSelect2Choice supervisorField = new DefaultSelect2Choice<>( - "supervisor", - getModel().flatMap(SerializableProject::getSupervisor), - supervisorChoices); + "supervisor", + getModel().flatMap(SerializableProject::getSupervisor), + supervisorChoices + ); supervisorField.setRequired(true); add(supervisorField); - ChoiceProvider authorChoices = - new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.AUTHOR)); + ChoiceProvider authorChoices = new AutoCompleteRoleProvider( + userSearchService, + EnumSet.of(Roles.AUTHOR) + ); DefaultSelect2MultiChoice authorsField = new DefaultSelect2MultiChoice<>( - "authors", - getModel().flatMap(SerializableProject::getAuthors), - authorChoices); + "authors", + getModel().flatMap(SerializableProject::getAuthors), + authorChoices + ); authorsField.setRequired(true); add(authorsField); DefaultSelect2MultiChoice reviewersField = new DefaultSelect2MultiChoice<>( - "reviewers", - getModel().flatMap(SerializableProject::getReviewers), - supervisorChoices); + "reviewers", + getModel().flatMap(SerializableProject::getReviewers), + supervisorChoices + ); add(reviewersField); DefaultSelect2MultiChoice coSupervisorsField = new DefaultSelect2MultiChoice<>( - "coSupervisors", - getModel().flatMap(SerializableProject::getCoSupervisors), - supervisorChoices); + "coSupervisors", + getModel().flatMap(SerializableProject::getCoSupervisors), + supervisorChoices + ); add(coSupervisorsField); DropDownChoice researchAreaChoice = new DropDownChoice<>( - "researchArea", - getModel().flatMap(SerializableProject::getResearchArea), - researchAreaService::findNotDeleted, - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)); + "researchArea", + getModel().flatMap(SerializableProject::getResearchArea), + researchAreaService::findNotDeleted, + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ); researchAreaChoice.setNullValid(true); add(researchAreaChoice); } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPage.java index 618b425393..d34c954c7f 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPage.java @@ -1,233 +1,268 @@ -package se.su.dsv.scipro.admin.pages; - -import com.google.common.eventbus.EventBus; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.markup.html.form.*; -import org.apache.wicket.markup.html.panel.FeedbackPanel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.LambdaModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.components.*; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminProjectManagement; -import se.su.dsv.scipro.data.DetachableServiceModel; -import se.su.dsv.scipro.data.DetachableServiceModelCollection; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; -import se.su.dsv.scipro.mail.MailEvent; -import se.su.dsv.scipro.mail.MailEventService; -import se.su.dsv.scipro.notifications.NotificationController; -import se.su.dsv.scipro.notifications.dataobject.NotificationSource; -import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectService; -import se.su.dsv.scipro.project.ReviewerAssignedEvent; -import se.su.dsv.scipro.security.auth.Authorization; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.*; -import se.su.dsv.scipro.util.PageParameterKeys; - -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - -@Authorization(authorizedRoles = {Roles.SYSADMIN}) -public class AdminEditProjectPage extends AbstractAdminProjectPage implements MenuHighlightAdminProjectManagement { - - public static final String FEEDBACK = "feedback"; - public static final String TITLE_FIELD = "titleField"; - public static final String PROJECT_TYPE_SELECT = "projectTypeSelect"; - public static final String HEAD_SUPERVISOR_SELECT = "headSupervisorSelect"; - public static final String FORM = "form"; - public static final String AUTHORS = "authors"; - public static final String REVIEWERS = "reviewers"; - public static final String CO_SUPERVISORS = "coSupervisors"; - - @Inject - private ProjectTypeService projectTypeService; - @Inject - private ProjectService projectService; - @Inject - private NotificationController notificationController; - @Inject - private GeneralSystemSettingsService generalSystemSettingsService; - @Inject - private MailEventService mailEventService; - @Inject - private UserService userService; - @Inject - private EventBus eventBus; - @Inject - private ResearchAreaService researchAreaService; - @Inject - private UserSearchService userSearchService; - - public AdminEditProjectPage(PageParameters pp) { - final long id = pp.get(PageParameterKeys.MAP.get(Project.class)).toLong(0); - final Project project = projectService.findOne(id); - if (project == null) { - throw new RestartResponseException(AdminCreateProjectPage.class); - } - add(new ProjectForm(FORM, new DetachableServiceModel<>(projectService, project))); - } - - private class ProjectForm extends Form { - - private final FormComponent> authors; - private final FormComponent> coSupervisors; - private final FormComponent> reviewers; - - private Collection events = EnumSet.noneOf(ProjectEvent.Event.class); - - public ProjectForm(String id, final IModel model) { - super(id, model); - add(new FeedbackPanel(FEEDBACK)); - - add(new RequiredTextField<>(TITLE_FIELD, LambdaModel.of(model, Project::getTitle, Project::setTitle))); - - List types = projectTypeService.findAllActive(); - DropDownChoice projectTypeSelect = new DropDownChoice<>(PROJECT_TYPE_SELECT, - LambdaModel.of(model, Project::getProjectType, Project::setProjectType), types, new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); - projectTypeSelect.setRequired(true); - if (types.size() == 1) { - projectTypeSelect.setModelObject(types.get(0)); - } - add(projectTypeSelect); - - SupervisorAutoComplete headSupervisor = new SupervisorAutoComplete(HEAD_SUPERVISOR_SELECT, LambdaModel.of(model, Project::getHeadSupervisor, Project::setHeadSupervisor)) { - @Override - protected void onModelChanged() { - events.add(ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED); - } - }; - headSupervisor.setRequired(true); - add(headSupervisor); - IModel> authorsModel = new DetachableServiceModelCollection<>(userService); - authorsModel.setObject(getModelObject().getProjectParticipants()); - authors = new DefaultSelect2MultiChoice<>(AUTHORS, authorsModel, new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.AUTHOR))); - authors.setRequired(true); - add(authors); - IModel> reviewersModel = new DetachableServiceModelCollection<>(userService); - reviewersModel.setObject(getModelObject().getReviewers()); - reviewers = new DefaultSelect2MultiChoice<>(REVIEWERS, reviewersModel, new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.REVIEWER))); - add(reviewers); - IModel> coSupervisorModel = new DetachableServiceModelCollection<>(userService); - coSupervisorModel.setObject(getModelObject().getCoSupervisors()); - coSupervisors = new DefaultSelect2MultiChoice<>(CO_SUPERVISORS, coSupervisorModel, new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.SUPERVISOR))); - add(coSupervisors); - DropDownChoice researchArea = new DropDownChoice<>( - "researchArea", - LambdaModel.of(model, Project::getResearchArea, Project::setResearchArea), - new ResearchAreasModel(researchAreaService), - new ResearchAreaChoiceRenderer(this)); - researchArea.setNullValid(true); - add(researchArea); - FormComponent startDate = new TextField<>("startDate", LambdaModel.of(model, Project::getStartDate, Project::setStartDate), LocalDate.class); - startDate.add(new BootstrapDatePicker()); - startDate.setRequired(true); - add(startDate); - FormComponent endDate = new TextField<>("endDate", LambdaModel.of(model, Project::getExpectedEndDate, Project::setExpectedEndDate), LocalDate.class); - endDate.add(new BootstrapDatePicker()); - add(endDate); - add(new DatesValidator(startDate, endDate)); - } - - @Override - protected void onSubmit() { - projectService.save(getModelObject()); - info(getString("saved", getModel())); - - for (User reviewer : this.reviewers.getModelObject()) { - eventBus.post(new ReviewerAssignedEvent(getModelObject(), reviewer)); - } - for (ProjectEvent.Event event : events) { - notificationController.notifyProject(getModelObject(), event, new NotificationSource()); - if (event == ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED) { - createSupervisorChangeMail(); - } - } - events.clear(); - } - - private void createSupervisorChangeMail() { - GeneralSystemSettings settings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); - MailEvent mailEvent = new MailEvent(); - mailEvent.setFromEmail(settings.getSystemFromMail()); - mailEvent.setFromName(settings.getMailFromName()); - mailEvent.getNonUserRecipients().addAll(settings.getSupervisorChangeMails()); - mailEvent.setSubject(getString("supervisor.change.subject")); - mailEvent.setMessageBody(getString("supervisor.change.body", getModel())); - mailEventService.save(mailEvent); - } - - @Override - protected void onValidateModelObjects() { - validateSameUser(authors.getModelObject(), reviewers.getModelObject(), "reviewerAuthorSame"); - validateSameUser(authors.getModelObject(), coSupervisors.getModelObject(), "authorCoSame"); - validateSameUser(reviewers.getModelObject(), coSupervisors.getModelObject(), "reviewerCoSame"); - validateHeadSupervisorSameAs(coSupervisors.getModelObject(), "headCoSame"); - validateHeadSupervisorSameAs(reviewers.getModelObject(), "headReviewerSame"); - validateHeadSupervisorSameAs(authors.getModelObject(), "headAuthorSame"); - validateReviewerHasReviewerRole(reviewers.getModelObject(), "reviewerNotReviewer"); - notifyAuthorsChanged(); - notifyReviewersChanged(); - notifyCoSupervisorsChanged(); - TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); - projectParticipants.addAll(authors.getModelObject()); - getModelObject().setProjectParticipants(projectParticipants); - TreeSet coSupervisors = new TreeSet<>(new User.ByNameComparator()); - coSupervisors.addAll(this.coSupervisors.getModelObject()); - getModelObject().setCoSupervisors(coSupervisors); - TreeSet reviewers = new TreeSet<>(new User.ByNameComparator()); - reviewers.addAll(this.reviewers.getModelObject()); - getModelObject().setReviewers(reviewers); - } - - private void notifyCoSupervisorsChanged() { - for (User user : coSupervisors.getModelObject()) { - if (!getModelObject().isCoSupervisor(user)) { - events.add(ProjectEvent.Event.CO_SUPERVISOR_CHANGED); - } - } - } - - private void notifyReviewersChanged() { - for (User user : reviewers.getModelObject()) { - if (!getModelObject().isReviewer(user)) { - events.add(ProjectEvent.Event.REVIEWERS_CHANGED); - } - } - } - - private void notifyAuthorsChanged() { - for (User author : authors.getModelObject()) { - if (!getModelObject().isParticipant(author)) { - events.add(ProjectEvent.Event.AUTHORS_CHANGED); - } - } - } - - private void validateSameUser(Collection users, Collection otherUsers, String errorKey) { - for (User user : users) { - if (otherUsers.contains(user)) { - error(getString(errorKey)); - } - } - } - - private void validateHeadSupervisorSameAs(Collection users, String errorKey) { - for (User user : users) { - if (user.equals(getModelObject().getHeadSupervisor())) { - error(getString(errorKey)); - } - } - } - - private void validateReviewerHasReviewerRole(Collection users, String errorKey) { - for (User user : users) { - if (!user.getRoles().contains(Roles.REVIEWER)) { - error(getString(errorKey)); - } - } - } - } -} +package se.su.dsv.scipro.admin.pages; + +import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.markup.html.form.*; +import org.apache.wicket.markup.html.panel.FeedbackPanel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.LambdaModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import se.su.dsv.scipro.components.*; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminProjectManagement; +import se.su.dsv.scipro.data.DetachableServiceModel; +import se.su.dsv.scipro.data.DetachableServiceModelCollection; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; +import se.su.dsv.scipro.mail.MailEvent; +import se.su.dsv.scipro.mail.MailEventService; +import se.su.dsv.scipro.notifications.NotificationController; +import se.su.dsv.scipro.notifications.dataobject.NotificationSource; +import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectService; +import se.su.dsv.scipro.project.ReviewerAssignedEvent; +import se.su.dsv.scipro.security.auth.Authorization; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.util.PageParameterKeys; + +@Authorization(authorizedRoles = { Roles.SYSADMIN }) +public class AdminEditProjectPage extends AbstractAdminProjectPage implements MenuHighlightAdminProjectManagement { + + public static final String FEEDBACK = "feedback"; + public static final String TITLE_FIELD = "titleField"; + public static final String PROJECT_TYPE_SELECT = "projectTypeSelect"; + public static final String HEAD_SUPERVISOR_SELECT = "headSupervisorSelect"; + public static final String FORM = "form"; + public static final String AUTHORS = "authors"; + public static final String REVIEWERS = "reviewers"; + public static final String CO_SUPERVISORS = "coSupervisors"; + + @Inject + private ProjectTypeService projectTypeService; + + @Inject + private ProjectService projectService; + + @Inject + private NotificationController notificationController; + + @Inject + private GeneralSystemSettingsService generalSystemSettingsService; + + @Inject + private MailEventService mailEventService; + + @Inject + private UserService userService; + + @Inject + private EventBus eventBus; + + @Inject + private ResearchAreaService researchAreaService; + + @Inject + private UserSearchService userSearchService; + + public AdminEditProjectPage(PageParameters pp) { + final long id = pp.get(PageParameterKeys.MAP.get(Project.class)).toLong(0); + final Project project = projectService.findOne(id); + if (project == null) { + throw new RestartResponseException(AdminCreateProjectPage.class); + } + add(new ProjectForm(FORM, new DetachableServiceModel<>(projectService, project))); + } + + private class ProjectForm extends Form { + + private final FormComponent> authors; + private final FormComponent> coSupervisors; + private final FormComponent> reviewers; + + private Collection events = EnumSet.noneOf(ProjectEvent.Event.class); + + public ProjectForm(String id, final IModel model) { + super(id, model); + add(new FeedbackPanel(FEEDBACK)); + + add(new RequiredTextField<>(TITLE_FIELD, LambdaModel.of(model, Project::getTitle, Project::setTitle))); + + List types = projectTypeService.findAllActive(); + DropDownChoice projectTypeSelect = new DropDownChoice<>( + PROJECT_TYPE_SELECT, + LambdaModel.of(model, Project::getProjectType, Project::setProjectType), + types, + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); + projectTypeSelect.setRequired(true); + if (types.size() == 1) { + projectTypeSelect.setModelObject(types.get(0)); + } + add(projectTypeSelect); + + SupervisorAutoComplete headSupervisor = new SupervisorAutoComplete( + HEAD_SUPERVISOR_SELECT, + LambdaModel.of(model, Project::getHeadSupervisor, Project::setHeadSupervisor) + ) { + @Override + protected void onModelChanged() { + events.add(ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED); + } + }; + headSupervisor.setRequired(true); + add(headSupervisor); + IModel> authorsModel = new DetachableServiceModelCollection<>(userService); + authorsModel.setObject(getModelObject().getProjectParticipants()); + authors = new DefaultSelect2MultiChoice<>( + AUTHORS, + authorsModel, + new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.AUTHOR)) + ); + authors.setRequired(true); + add(authors); + IModel> reviewersModel = new DetachableServiceModelCollection<>(userService); + reviewersModel.setObject(getModelObject().getReviewers()); + reviewers = new DefaultSelect2MultiChoice<>( + REVIEWERS, + reviewersModel, + new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.REVIEWER)) + ); + add(reviewers); + IModel> coSupervisorModel = new DetachableServiceModelCollection<>(userService); + coSupervisorModel.setObject(getModelObject().getCoSupervisors()); + coSupervisors = new DefaultSelect2MultiChoice<>( + CO_SUPERVISORS, + coSupervisorModel, + new AutoCompleteRoleProvider(userSearchService, EnumSet.of(Roles.SUPERVISOR)) + ); + add(coSupervisors); + DropDownChoice researchArea = new DropDownChoice<>( + "researchArea", + LambdaModel.of(model, Project::getResearchArea, Project::setResearchArea), + new ResearchAreasModel(researchAreaService), + new ResearchAreaChoiceRenderer(this) + ); + researchArea.setNullValid(true); + add(researchArea); + FormComponent startDate = new TextField<>( + "startDate", + LambdaModel.of(model, Project::getStartDate, Project::setStartDate), + LocalDate.class + ); + startDate.add(new BootstrapDatePicker()); + startDate.setRequired(true); + add(startDate); + FormComponent endDate = new TextField<>( + "endDate", + LambdaModel.of(model, Project::getExpectedEndDate, Project::setExpectedEndDate), + LocalDate.class + ); + endDate.add(new BootstrapDatePicker()); + add(endDate); + add(new DatesValidator(startDate, endDate)); + } + + @Override + protected void onSubmit() { + projectService.save(getModelObject()); + info(getString("saved", getModel())); + + for (User reviewer : this.reviewers.getModelObject()) { + eventBus.post(new ReviewerAssignedEvent(getModelObject(), reviewer)); + } + for (ProjectEvent.Event event : events) { + notificationController.notifyProject(getModelObject(), event, new NotificationSource()); + if (event == ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED) { + createSupervisorChangeMail(); + } + } + events.clear(); + } + + private void createSupervisorChangeMail() { + GeneralSystemSettings settings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); + MailEvent mailEvent = new MailEvent(); + mailEvent.setFromEmail(settings.getSystemFromMail()); + mailEvent.setFromName(settings.getMailFromName()); + mailEvent.getNonUserRecipients().addAll(settings.getSupervisorChangeMails()); + mailEvent.setSubject(getString("supervisor.change.subject")); + mailEvent.setMessageBody(getString("supervisor.change.body", getModel())); + mailEventService.save(mailEvent); + } + + @Override + protected void onValidateModelObjects() { + validateSameUser(authors.getModelObject(), reviewers.getModelObject(), "reviewerAuthorSame"); + validateSameUser(authors.getModelObject(), coSupervisors.getModelObject(), "authorCoSame"); + validateSameUser(reviewers.getModelObject(), coSupervisors.getModelObject(), "reviewerCoSame"); + validateHeadSupervisorSameAs(coSupervisors.getModelObject(), "headCoSame"); + validateHeadSupervisorSameAs(reviewers.getModelObject(), "headReviewerSame"); + validateHeadSupervisorSameAs(authors.getModelObject(), "headAuthorSame"); + validateReviewerHasReviewerRole(reviewers.getModelObject(), "reviewerNotReviewer"); + notifyAuthorsChanged(); + notifyReviewersChanged(); + notifyCoSupervisorsChanged(); + TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); + projectParticipants.addAll(authors.getModelObject()); + getModelObject().setProjectParticipants(projectParticipants); + TreeSet coSupervisors = new TreeSet<>(new User.ByNameComparator()); + coSupervisors.addAll(this.coSupervisors.getModelObject()); + getModelObject().setCoSupervisors(coSupervisors); + TreeSet reviewers = new TreeSet<>(new User.ByNameComparator()); + reviewers.addAll(this.reviewers.getModelObject()); + getModelObject().setReviewers(reviewers); + } + + private void notifyCoSupervisorsChanged() { + for (User user : coSupervisors.getModelObject()) { + if (!getModelObject().isCoSupervisor(user)) { + events.add(ProjectEvent.Event.CO_SUPERVISOR_CHANGED); + } + } + } + + private void notifyReviewersChanged() { + for (User user : reviewers.getModelObject()) { + if (!getModelObject().isReviewer(user)) { + events.add(ProjectEvent.Event.REVIEWERS_CHANGED); + } + } + } + + private void notifyAuthorsChanged() { + for (User author : authors.getModelObject()) { + if (!getModelObject().isParticipant(author)) { + events.add(ProjectEvent.Event.AUTHORS_CHANGED); + } + } + } + + private void validateSameUser(Collection users, Collection otherUsers, String errorKey) { + for (User user : users) { + if (otherUsers.contains(user)) { + error(getString(errorKey)); + } + } + } + + private void validateHeadSupervisorSameAs(Collection users, String errorKey) { + for (User user : users) { + if (user.equals(getModelObject().getHeadSupervisor())) { + error(getString(errorKey)); + } + } + } + + private void validateReviewerHasReviewerRole(Collection users, String errorKey) { + for (User user : users) { + if (!user.getRoles().contains(Roles.REVIEWER)) { + error(getString(errorKey)); + } + } + } + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailLogPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailLogPage.java index 921e69bbe7..67a0cdb97e 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailLogPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailLogPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -23,13 +26,10 @@ import se.su.dsv.scipro.mail.MailEvent; import se.su.dsv.scipro.mail.MailEventService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public class AdminMailLogPage extends AbstractAdminMailPage { public static final String SUBJECT = "subject"; + @Inject private MailEventService mailEventService; @@ -53,33 +53,55 @@ public class AdminMailLogPage extends AbstractAdminMailPage { } private List> columns() { - return Arrays.asList(getMailEventDateColumn(), getTitleColumn(), getUserRecipientsColumn(), getNonUserRecipientsColumn()); + return Arrays.asList( + getMailEventDateColumn(), + getTitleColumn(), + getUserRecipientsColumn(), + getNonUserRecipientsColumn() + ); } private DateColumn getMailEventDateColumn() { - return new DateColumn<>(new ResourceModel("sent").wrapOnAssignment(this), MailEvent::getDateCreated, "dateCreated", DateStyle.DATETIME); + return new DateColumn<>( + new ResourceModel("sent").wrapOnAssignment(this), + MailEvent::getDateCreated, + "dateCreated", + DateStyle.DATETIME + ); } private MultipleUsersColumn getUserRecipientsColumn() { return new MultipleUsersColumn<>(new ResourceModel("recipients").wrapOnAssignment(this)) { @Override public IModel> getUsers(IModel rowModel) { - return new ListAdapterModel<>(LambdaModel.of(rowModel, MailEvent::getRecipients, MailEvent::setRecipients)); + return new ListAdapterModel<>( + LambdaModel.of(rowModel, MailEvent::getRecipients, MailEvent::setRecipients) + ); } }; } + private AbstractExportableColumn getNonUserRecipientsColumn() { return new AbstractExportableColumn<>(new ResourceModel("nonUserRecipients").wrapOnAssignment(this)) { @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, - new ListAdapterModel<>(LambdaModel.of(rowModel, MailEvent::getNonUserRecipients, MailEvent::setNonUserRecipients))) { - - @Override - public Component getComponent(String componentId, IModel t) { - return new Label(componentId, t); + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>( + LambdaModel.of(rowModel, MailEvent::getNonUserRecipients, MailEvent::setNonUserRecipients) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new Label(componentId, t); + } } - }); + ); } @Override @@ -93,12 +115,18 @@ public class AdminMailLogPage extends AbstractAdminMailPage { return new AbstractColumn<>(new ResourceModel("subject").wrapOnAssignment(this), SUBJECT) { @Override public void populateItem(Item> item, String s, IModel iModel) { - item.add(new AjaxLinkPanel<>(s, iModel, LambdaModel.of(iModel, MailEvent::getSubject, MailEvent::setSubject)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - openMailModal(model, target); + item.add( + new AjaxLinkPanel<>( + s, + iModel, + LambdaModel.of(iModel, MailEvent::getSubject, MailEvent::setSubject) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + openMailModal(model, target); + } } - }); + ); } }; } @@ -110,19 +138,37 @@ public class AdminMailLogPage extends AbstractAdminMailPage { } private static class FilterForm extends Form { + public FilterForm(String id, IModel model) { super(id, model); - - add(new TextField<>(SUBJECT, LambdaModel.of(model, MailEventService.Filter::getSubject, MailEventService.Filter::setSubject))); - add(new UserAutoComplete("user", LambdaModel.of(model, MailEventService.Filter::getUser, MailEventService.Filter::setUser)) { - @Override - protected void action(final AjaxRequestTarget target, final User object) { - // Not ajax + add( + new TextField<>( + SUBJECT, + LambdaModel.of(model, MailEventService.Filter::getSubject, MailEventService.Filter::setSubject) + ) + ); + add( + new UserAutoComplete( + "user", + LambdaModel.of(model, MailEventService.Filter::getUser, MailEventService.Filter::setUser) + ) { + @Override + protected void action(final AjaxRequestTarget target, final User object) { + // Not ajax + } } - }); - add(new DeactivatableDatePickerPanel("sentBetween", + ); + add( + new DeactivatableDatePickerPanel( + "sentBetween", LambdaModel.of(model, MailEventService.Filter::getSentAfter, MailEventService.Filter::setSentAfter), - LambdaModel.of(model, MailEventService.Filter::getSentBefore, MailEventService.Filter::setSentBefore))); + LambdaModel.of( + model, + MailEventService.Filter::getSentBefore, + MailEventService.Filter::setSentBefore + ) + ) + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailPage.java index c41c1e20d3..8c1e414009 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminMailPage.java @@ -1,16 +1,15 @@ package se.su.dsv.scipro.admin.pages; +import java.util.Set; import org.apache.wicket.model.Model; import se.su.dsv.scipro.admin.panels.AdminMailPanel; import se.su.dsv.scipro.system.User; -import java.util.Set; - public class AdminMailPage extends AbstractAdminMailPage { public AdminMailPage() { - add(new AdminMailPanel("newAdminMailPanel")); - } + add(new AdminMailPanel("newAdminMailPanel")); + } public AdminMailPage(Set users) { add(new AdminMailPanel("newAdminMailPanel", users)); diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminReviewerCapacityManagementPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminReviewerCapacityManagementPage.java index 6510ac7166..63bbc60915 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminReviewerCapacityManagementPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminReviewerCapacityManagementPage.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.time.Clock; +import java.time.Year; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; @@ -29,22 +37,16 @@ import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.Year; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; -import java.util.stream.Stream; - public class AdminReviewerCapacityManagementPage extends AbstractAdminProjectPage { + private static final int HOURS_PER_REVIEW = 3; @Inject ReviewerCapacityService reviewerCapacityService; + @Inject UnitService unitService; + @Inject Clock clock; @@ -54,42 +56,42 @@ public class AdminReviewerCapacityManagementPage extends AbstractAdminProjectPag private IModel selectedPeriod = new Model<>(); public AdminReviewerCapacityManagementPage() { - IModel> units = LoadableDetachableModel.of(() -> - reviewerCapacityService.getUnitsWithReviewers()); + IModel> units = LoadableDetachableModel.of(() -> reviewerCapacityService.getUnitsWithReviewers()); selectedUnit = new DetachableServiceModel<>(unitService); DropDownChoice unitDropDownChoice = new DropDownChoice<>( - "units", - selectedUnit, - units, - new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId)); + "units", + selectedUnit, + units, + new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId) + ); unitDropDownChoice.setNullValid(true); - unitDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(reviewerList); + unitDropDownChoice.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(reviewerList); + } } - }); + ); add(unitDropDownChoice); - DropDownChoice periods = new DropDownChoice<>( - "periods", - selectedPeriod, - getPeriods()); - periods.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(reviewerList); + DropDownChoice periods = new DropDownChoice<>("periods", selectedPeriod, getPeriods()); + periods.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(reviewerList); + } } - }); + ); add(periods); IModel> reviewers = LoadableDetachableModel.of(() -> { List users = new ArrayList<>(); if (selectedUnit.getObject() == null) { users.addAll(reviewerCapacityService.getAllActiveReviewers()); - } - else { + } else { users.addAll(reviewerCapacityService.getActiveReviewersOnUnit(selectedUnit.getObject())); } users.sort(Comparator.comparing(User::getLastName)); @@ -103,31 +105,31 @@ public class AdminReviewerCapacityManagementPage extends AbstractAdminProjectPag } }; reviewerList.add(new Label("period", selectedPeriod)); - reviewerList.add(new ListView<>("reviewers", reviewers) { - { - setReuseItems(true); - } + reviewerList.add( + new ListView<>("reviewers", reviewers) { + { + setReuseItems(true); + } - @Override - protected void populateItem(ListItem item) { - item.add(new ReviewerCard("reviewer", item.getModel())); + @Override + protected void populateItem(ListItem item) { + item.add(new ReviewerCard("reviewer", item.getModel())); + } } - }); + ); reviewerList.setOutputMarkupPlaceholderTag(true); add(reviewerList); } private List getPeriods() { Year current = Year.now(clock); - return Stream.iterate(current, year -> year.plusYears(1)) - .limit(3) - .toList(); + return Stream.iterate(current, year -> year.plusYears(1)).limit(3).toList(); } private class ReviewerCard extends WebMarkupContainer { + public ReviewerCard(String id, IModel reviewer) { super(id, reviewer); - add(new UserProfileImage("profile_image", reviewer, UserProfileImage.Size.MEDIUM)); add(new UserLabel("name", reviewer)); @@ -148,7 +150,9 @@ public class AdminReviewerCapacityManagementPage extends AbstractAdminProjectPag add(expandToggle); expanded.add(new AssignTargetForm("form", reviewer)); - IModel> history = LoadableDetachableModel.of(() -> reviewerCapacityService.getTargetHistory(reviewer.getObject(), selectedPeriod.getObject())); + IModel> history = LoadableDetachableModel.of(() -> + reviewerCapacityService.getTargetHistory(reviewer.getObject(), selectedPeriod.getObject()) + ); ListView historyComponent = new ListView<>("history", history) { @Override protected void populateItem(ListItem item) { @@ -164,49 +168,63 @@ public class AdminReviewerCapacityManagementPage extends AbstractAdminProjectPag } private class AssignTargetForm extends Form { + private IModel springTarget; private IModel autumnTarget; private IModel note; public AssignTargetForm(String id, IModel reviewer) { super(id, reviewer); - add(new FencedFeedbackPanel("feedback", this)); springTarget = LoadableDetachableModel.of(() -> - reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).spring()); + reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).spring() + ); Label springHours = new Label("springHours", springTarget.map(i -> i * HOURS_PER_REVIEW)); springHours.setOutputMarkupId(true); add(springHours); - NumberTextField springtargetField = new NumberTextField<>("springTarget", springTarget, Integer.class); + NumberTextField springtargetField = new NumberTextField<>( + "springTarget", + springTarget, + Integer.class + ); springtargetField.setMinimum(0); - springtargetField.add(AjaxFormComponentUpdatingBehavior.onUpdate("change", target -> target.add(springHours))); + springtargetField.add( + AjaxFormComponentUpdatingBehavior.onUpdate("change", target -> target.add(springHours)) + ); add(springtargetField); autumnTarget = LoadableDetachableModel.of(() -> - reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).autumn()); + reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).autumn() + ); Label autumnHours = new Label("autumnHours", autumnTarget.map(i -> i * HOURS_PER_REVIEW)); autumnHours.setOutputMarkupId(true); add(autumnHours); - NumberTextField autumnTargetField = new NumberTextField<>("autumnTarget", autumnTarget, Integer.class); + NumberTextField autumnTargetField = new NumberTextField<>( + "autumnTarget", + autumnTarget, + Integer.class + ); autumnTargetField.setMinimum(0); - autumnTargetField.add(AjaxFormComponentUpdatingBehavior.onUpdate("change", target -> target.add(autumnHours))); + autumnTargetField.add( + AjaxFormComponentUpdatingBehavior.onUpdate("change", target -> target.add(autumnHours)) + ); add(autumnTargetField); IModel remainingTargets = LoadableDetachableModel.of(() -> - reviewerCapacityService.getRemainingTargets( - reviewer.getObject(), - selectedPeriod.getObject())); + reviewerCapacityService.getRemainingTargets(reviewer.getObject(), selectedPeriod.getObject()) + ); add(new Label("remainingSpring", remainingTargets.map(RemainingTargets::spring))); add(new Label("remainingAutumn", remainingTargets.map(RemainingTargets::autumn))); note = LoadableDetachableModel.of(() -> - reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).note()); + reviewerCapacityService.getTarget(reviewer.getObject(), selectedPeriod.getObject()).note() + ); TextArea noteField = new TextArea<>("note", note); add(noteField); } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminStartPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminStartPage.java index c1e1560bab..a086e4430a 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminStartPage.java @@ -1,7 +1,6 @@ package se.su.dsv.scipro.admin.pages; public class AdminStartPage extends AbstractAdminPage { - - public static final String MAIN_MENU_LABEL = "Admin"; + public static final String MAIN_MENU_LABEL = "Admin"; } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyPage.java index 0c1aa1c26d..a27ee57ca9 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -22,10 +25,6 @@ import se.su.dsv.scipro.components.ConfirmationLink; import se.su.dsv.scipro.survey.Question; import se.su.dsv.scipro.survey.SurveyService; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public class AdminSurveyPage extends AbstractAdminProjectPage { @Inject @@ -54,88 +53,111 @@ public class AdminSurveyPage extends AbstractAdminProjectPage { surveyService.setAvailability(false); } }; - add(new AjaxCheckBox("available", surveyAvailability) { - @Override - protected void onUpdate(final AjaxRequestTarget ajaxRequestTarget) { - ajaxRequestTarget.addListener(new AjaxFeedbackPanelUpdater()); - success(getModelObject() ? getString("survey.made.available") : getString("survey.made.unavailable")); + add( + new AjaxCheckBox("available", surveyAvailability) { + @Override + protected void onUpdate(final AjaxRequestTarget ajaxRequestTarget) { + ajaxRequestTarget.addListener(new AjaxFeedbackPanelUpdater()); + success( + getModelObject() ? getString("survey.made.available") : getString("survey.made.unavailable") + ); + } } - }); + ); final IModel> questionModel = LoadableDetachableModel.of(surveyService::getQuestions); questionEditingForm = new QuestionEditingForm("addNew", Model.of(new Question())); add(questionEditingForm); - add(new AjaxLink<>("addNewButon") { - @Override - public void onClick(final AjaxRequestTarget target) { - questionEditingForm.setModelObject(new Question()); - target.add(questionEditingForm); - target.appendJavaScript("$('#add_part_modal').modal('show')"); + add( + new AjaxLink<>("addNewButon") { + @Override + public void onClick(final AjaxRequestTarget target) { + questionEditingForm.setModelObject(new Question()); + target.add(questionEditingForm); + target.appendJavaScript("$('#add_part_modal').modal('show')"); + } } - }); + ); - add(new ListView<>("questions", questionModel) { - { - setReuseItems(true); + add( + new ListView<>("questions", questionModel) { + { + setReuseItems(true); + } + + @Override + protected void populateItem(final ListItem item) { + item.setOutputMarkupId(true); + + item.add(new Label("text", item.getModel().map(Question::getText))); + item.add(new EnumLabel<>("type", item.getModel().map(Question::getType))); + item.add( + new ListView<>("answers", item.getModel().map(Question::getChoices)) { + @Override + protected void onConfigure() { + super.onConfigure(); + final Question.Type type = item.getModel().getObject().getType(); + setVisible( + type == Question.Type.MULTIPLE_CHOICE || type == Question.Type.SINGLE_CHOICE + ); + } + + @Override + protected void populateItem(final ListItem answerItem) { + answerItem.add(new Label("answer", answerItem.getModel())); + } + } + ); + + item.add( + new Link<>("up", item.getModel()) { + @Override + public void onClick() { + surveyService.moveUp(getModelObject()); + questionModel.detach(); + } + } + ); + + item.add( + new Link<>("down", item.getModel()) { + @Override + public void onClick() { + surveyService.moveDown(getModelObject()); + questionModel.detach(); + } + } + ); + + item.add( + new AjaxLink<>("edit", item.getModel()) { + @Override + public void onClick(final AjaxRequestTarget target) { + questionEditingForm.setModelObject(getModelObject()); + target.add(questionEditingForm); + target.appendJavaScript("$('#add_part_modal').modal('show')"); + } + } + ); + } } - - @Override - protected void populateItem(final ListItem item) { - item.setOutputMarkupId(true); - - item.add(new Label("text", item.getModel().map(Question::getText))); - item.add(new EnumLabel<>("type", item.getModel().map(Question::getType))); - item.add(new ListView<>("answers", item.getModel().map(Question::getChoices)) { - @Override - protected void onConfigure() { - super.onConfigure(); - final Question.Type type = item.getModel().getObject().getType(); - setVisible(type == Question.Type.MULTIPLE_CHOICE || type == Question.Type.SINGLE_CHOICE); - } - - @Override - protected void populateItem(final ListItem answerItem) { - answerItem.add(new Label("answer", answerItem.getModel())); - } - }); - - item.add(new Link<>("up", item.getModel()) { - @Override - public void onClick() { - surveyService.moveUp(getModelObject()); - questionModel.detach(); - } - }); - - item.add(new Link<>("down", item.getModel()) { - @Override - public void onClick() { - surveyService.moveDown(getModelObject()); - questionModel.detach(); - } - }); - - item.add(new AjaxLink<>("edit", item.getModel()) { - @Override - public void onClick(final AjaxRequestTarget target) { - questionEditingForm.setModelObject(getModelObject()); - target.add(questionEditingForm); - target.appendJavaScript("$('#add_part_modal').modal('show')"); - } - }); - } - }); + ); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnDomReadyHeaderItem.forScript("var sneaky = new ScrollSneak(location.hostname); $('.scrollSneak').click(sneaky.sneak);")); + response.render( + OnDomReadyHeaderItem.forScript( + "var sneaky = new ScrollSneak(location.hostname); $('.scrollSneak').click(sneaky.sneak);" + ) + ); } private class QuestionEditingForm extends Form { + public QuestionEditingForm(final String id, final IModel questionModel) { super(id, questionModel); final var choiceContainer = new WebMarkupContainer("choiceContainer") { @@ -143,18 +165,21 @@ public class AdminSurveyPage extends AbstractAdminProjectPage { protected void onConfigure() { super.onConfigure(); final Question.Type selectedType = questionModel.getObject().getType(); - setVisible(selectedType == Question.Type.MULTIPLE_CHOICE || selectedType == Question.Type.SINGLE_CHOICE); + setVisible( + selectedType == Question.Type.MULTIPLE_CHOICE || selectedType == Question.Type.SINGLE_CHOICE + ); } }; choiceContainer.setOutputMarkupPlaceholderTag(true); add(choiceContainer); - add(new RequiredTextField<>("text", - LambdaModel.of(getModel(), Question::getText, Question::setText))); - final var type = new AjaxDropDownChoice<>("type", - LambdaModel.of(getModel(), Question::getType, Question::setType), - Arrays.asList(Question.Type.values()), - new EnumChoiceRenderer<>(this)) { + add(new RequiredTextField<>("text", LambdaModel.of(getModel(), Question::getText, Question::setText))); + final var type = new AjaxDropDownChoice<>( + "type", + LambdaModel.of(getModel(), Question::getType, Question::setType), + Arrays.asList(Question.Type.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onNewSelection(final AjaxRequestTarget target, final Question.Type objectSelected) { target.add(choiceContainer); @@ -162,61 +187,75 @@ public class AdminSurveyPage extends AbstractAdminProjectPage { }; add(type); - choiceContainer.add(new ListView<>("choices", questionModel.map(Question::getChoices)) { - { - setReuseItems(true); + choiceContainer.add( + new ListView<>("choices", questionModel.map(Question::getChoices)) { + { + setReuseItems(true); + } + + @Override + protected void populateItem(final ListItem item) { + item.add(new TextField<>("text", item.getModel())); + var listView = this; + item.add( + new AjaxSubmitLink("remove") { + @Override + public void onSubmit(final AjaxRequestTarget target) { + addStateChange(); + + item.modelChanging(); + + // Remove item and invalidate listView + getList().remove(item.getIndex()); + + listView.modelChanged(); + listView.removeAll(); + + target.add(choiceContainer); + } + } + ); + } } - - @Override - protected void populateItem(final ListItem item) { - item.add(new TextField<>("text", item.getModel())); - var listView = this; - item.add(new AjaxSubmitLink("remove") { - @Override - public void onSubmit(final AjaxRequestTarget target) { - addStateChange(); - - item.modelChanging(); - - // Remove item and invalidate listView - getList().remove(item.getIndex()); - - listView.modelChanged(); - listView.removeAll(); - - target.add(choiceContainer); - } - }); + ); + choiceContainer.add( + new AjaxSubmitLink("add") { + @Override + public void onSubmit(final AjaxRequestTarget target) { + QuestionEditingForm.this.getModelObject().getChoices().add(""); + target.add(choiceContainer); + } } - }); - choiceContainer.add(new AjaxSubmitLink("add") { - @Override - public void onSubmit(final AjaxRequestTarget target) { - QuestionEditingForm.this.getModelObject().getChoices().add(""); - target.add(choiceContainer); - } - }); + ); - add(new Button("save") { - @Override - public void onSubmit() { - surveyService.saveQuestion(questionModel.getObject()); + add( + new Button("save") { + @Override + public void onSubmit() { + surveyService.saveQuestion(questionModel.getObject()); + } } - }); + ); - add(new ConfirmationLink<>("remove", questionModel, new StringResourceModel("delete.question.confirmation", questionModel)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(questionModel.getObject().getId() != null); - } + add( + new ConfirmationLink<>( + "remove", + questionModel, + new StringResourceModel("delete.question.confirmation", questionModel) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(questionModel.getObject().getId() != null); + } - @Override - public void onClick() { - surveyService.deleteQuestion(questionModel.getObject()); - questionModel.detach(); + @Override + public void onClick() { + surveyService.deleteQuestion(questionModel.getObject()); + questionModel.detach(); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyStatisticsPage.java index 74d431751d..aa2edf603f 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/AdminSurveyStatisticsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -20,10 +22,8 @@ import se.su.dsv.scipro.survey.SurveyStatistics; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.util.List; - public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { + @Inject SurveyService surveyService; @@ -31,12 +31,12 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { public AdminSurveyStatisticsPage() { super(); - FilterForm filterForm = new FilterForm("filter"); add(filterForm); IModel statistics = LoadableDetachableModel.of(() -> - surveyService.getStatistics(filterForm.getFilter())); + surveyService.getStatistics(filterForm.getFilter()) + ); this.statisticsContainer = new WebMarkupContainer("statistics"); this.statisticsContainer.setOutputMarkupPlaceholderTag(true); @@ -44,16 +44,24 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { this.statisticsContainer.add(new Label("respondents", statistics.map(SurveyStatistics::respondents))); - this.statisticsContainer.add(new ListView<>("questions", statistics.map(SurveyStatistics::questions)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("question", item.getModel().map(SurveyStatistics.Question::text))); + this.statisticsContainer.add( + new ListView<>("questions", statistics.map(SurveyStatistics::questions)) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("question", item.getModel().map(SurveyStatistics.Question::text))); - item.add(new SingleChoicePanel("single", item.getModel().as(SurveyStatistics.Question.Single.class))); - item.add(new MultiChoicePanel("multi", item.getModel().as(SurveyStatistics.Question.Multi.class))); - item.add(new FreeTextPanel("free_text", item.getModel().as(SurveyStatistics.Question.Text.class))); - } - }); + item.add( + new SingleChoicePanel("single", item.getModel().as(SurveyStatistics.Question.Single.class)) + ); + item.add( + new MultiChoicePanel("multi", item.getModel().as(SurveyStatistics.Question.Multi.class)) + ); + item.add( + new FreeTextPanel("free_text", item.getModel().as(SurveyStatistics.Question.Text.class)) + ); + } + } + ); } private static float getAverage(List choices) { @@ -69,22 +77,28 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { } private static class SingleChoicePanel extends WebMarkupContainer { + public SingleChoicePanel(String id, IModel model) { super(id, model); - - IModel totalAnswers = model.map(single -> single.choice().stream().mapToLong(SurveyStatistics.Question.Choice::count).sum()); + IModel totalAnswers = model.map(single -> + single.choice().stream().mapToLong(SurveyStatistics.Question.Choice::count).sum() + ); var choices = model.map(SurveyStatistics.Question.Single::choice); - add(new ListView<>("choices", choices) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("answer", item.getModel().map(SurveyStatistics.Question.Choice::answer))); - IModel count = item.getModel().map(SurveyStatistics.Question.Choice::count); - item.add(new Label("count", count)); + add( + new ListView<>("choices", choices) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("answer", item.getModel().map(SurveyStatistics.Question.Choice::answer))); + IModel count = item.getModel().map(SurveyStatistics.Question.Choice::count); + item.add(new Label("count", count)); - item.add(new Label("percent", totalAnswers.combineWith(count, (total, c) -> 100 * c / total))); + item.add( + new Label("percent", totalAnswers.combineWith(count, (total, c) -> (100 * c) / total)) + ); + } } - }); + ); add(new Label("average", choices.map(AdminSurveyStatisticsPage::getAverage))); } @@ -96,22 +110,28 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { } private static class MultiChoicePanel extends WebMarkupContainer { + public MultiChoicePanel(String id, IModel model) { super(id, model); - - IModel totalAnswers = model.map(single -> single.choice().stream().mapToLong(SurveyStatistics.Question.Choice::count).sum()); + IModel totalAnswers = model.map(single -> + single.choice().stream().mapToLong(SurveyStatistics.Question.Choice::count).sum() + ); var choices = model.map(SurveyStatistics.Question.Multi::choice); - add(new ListView<>("choices", choices) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("answer", item.getModel().map(SurveyStatistics.Question.Choice::answer))); - IModel count = item.getModel().map(SurveyStatistics.Question.Choice::count); - item.add(new Label("count", count)); + add( + new ListView<>("choices", choices) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("answer", item.getModel().map(SurveyStatistics.Question.Choice::answer))); + IModel count = item.getModel().map(SurveyStatistics.Question.Choice::count); + item.add(new Label("count", count)); - item.add(new Label("percent", totalAnswers.combineWith(count, (total, c) -> 100 * c / total))); + item.add( + new Label("percent", totalAnswers.combineWith(count, (total, c) -> (100 * c) / total)) + ); + } } - }); + ); add(new Label("average", choices.map(AdminSurveyStatisticsPage::getAverage))); } @@ -123,6 +143,7 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { } private class FilterForm extends Form { + @Inject UserService userService; @@ -130,14 +151,15 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { public FilterForm(String id) { super(id); - supervisorModel = new DetachableServiceModel<>(userService); - add(new EmployeeAutoComplete("supervisor", supervisorModel) { - @Override - protected void action(AjaxRequestTarget target, User object) { - target.add(statisticsContainer); + add( + new EmployeeAutoComplete("supervisor", supervisorModel) { + @Override + protected void action(AjaxRequestTarget target, User object) { + target.add(statisticsContainer); + } } - }); + ); } public SurveyService.Filter getFilter() { @@ -146,19 +168,22 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { } private class FreeTextPanel extends WebMarkupContainer { + public FreeTextPanel(String id, IModel model) { super(id, model); ModalWindowPlus dialog = new LargeModalWindow("dialog"); dialog.setTitle(model.map(SurveyStatistics.Question.Text::text)); add(dialog); - add(new AjaxLink<>("show") { - @Override - public void onClick(AjaxRequestTarget target) { - dialog.setContent(id -> new AllAnswers(id, model)); - dialog.show(target); + add( + new AjaxLink<>("show") { + @Override + public void onClick(AjaxRequestTarget target) { + dialog.setContent(id -> new AllAnswers(id, model)); + dialog.show(target); + } } - }); + ); } @Override @@ -168,15 +193,17 @@ public class AdminSurveyStatisticsPage extends AbstractAdminStatisticsPage { } private class AllAnswers extends Fragment { + public AllAnswers(String id, IModel model) { super(id, "answers", AdminSurveyStatisticsPage.this, model); - - add(new ListView<>("answers", model.map(SurveyStatistics.Question.Text::answers)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("answer", item.getModel())); + add( + new ListView<>("answers", model.map(SurveyStatistics.Question.Text::answers)) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("answer", item.getModel())); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/ProjectManagementPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/ProjectManagementPage.java index f6971b4286..114025fd98 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/ProjectManagementPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/ProjectManagementPage.java @@ -4,7 +4,7 @@ import se.su.dsv.scipro.datatables.project.ProjectDataPanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.ADMIN, Roles.STUDADM}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM }) public class ProjectManagementPage extends AbstractAdminProjectPage { public ProjectManagementPage() { diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/SerializableProject.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/SerializableProject.java index b2e71de665..57897aadb7 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/SerializableProject.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/SerializableProject.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -13,10 +15,8 @@ import se.su.dsv.scipro.system.ResearchAreaService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import java.time.LocalDate; -import java.util.*; - public class SerializableProject implements IDetachable { + private IModel title; private IModel projectType; private IModel startDate; @@ -27,7 +27,11 @@ public class SerializableProject implements IDetachable { private IModel> coSupervisors; private IModel researchArea; - public SerializableProject(UserService userService, ProjectTypeService projectTypeService, ResearchAreaService researchAreaService) { + public SerializableProject( + UserService userService, + ProjectTypeService projectTypeService, + ResearchAreaService researchAreaService + ) { this.title = Model.of(); this.projectType = new DetachableServiceModel<>(projectTypeService); this.startDate = Model.of(); diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePage.java index 6228da74af..b554ba0bf6 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePage.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.admin.pages; import com.google.common.collect.Lists; +import jakarta.inject.Inject; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; @@ -26,19 +31,14 @@ import se.su.dsv.scipro.workerthreads.Task; import se.su.dsv.scipro.workerthreads.WorkerData; import se.su.dsv.scipro.workerthreads.WorkerDataService; -import jakarta.inject.Inject; -import java.time.Duration; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class SystemMaintenancePage extends AbstractAdminSystemPage { private static final int REFRESH_TIMER = 120; @Inject private WorkerDataService workerDataService; + @Inject private Scheduler scheduler; @@ -50,16 +50,17 @@ public class SystemMaintenancePage extends AbstractAdminSystemPage { runningContainer.setOutputMarkupId(true); scheduledContainer.setOutputMarkupId(true); - runningContainer.add(new AjaxSelfUpdatingTimerBehavior(Duration.ofSeconds(REFRESH_TIMER)) { - - @Override - protected void onPostProcessTarget(AjaxRequestTarget target) { - if (target != null) { - target.add(runningContainer); + runningContainer.add( + new AjaxSelfUpdatingTimerBehavior(Duration.ofSeconds(REFRESH_TIMER)) { + @Override + protected void onPostProcessTarget(AjaxRequestTarget target) { + if (target != null) { + target.add(runningContainer); + } + super.onPostProcessTarget(target); } - super.onPostProcessTarget(target); } - }); + ); add(runningContainer); add(scheduledContainer); @@ -97,27 +98,44 @@ public class SystemMaintenancePage extends AbstractAdminSystemPage { private void updateScheduled() { scheduledContainer.removeAll(); - IModel> scheduleList = new ListAdapterModel<>(new LoadableDetachableModel<>() { - @Override - protected Set load() { - return scheduler.getTasks(); + IModel> scheduleList = new ListAdapterModel<>( + new LoadableDetachableModel<>() { + @Override + protected Set load() { + return scheduler.getTasks(); + } } - }); + ); ListView scheduleListView = new ListView<>("scheduleList", scheduleList) { @Override protected void populateItem(ListItem item) { - IModel wd = item.getModel().map(Task::getWorkerName).map(workerDataService::getWorkerDataByName); + IModel wd = item + .getModel() + .map(Task::getWorkerName) + .map(workerDataService::getWorkerDataByName); item.add(new DateLabel("lastRun", wd.map(WorkerData::getLastRun), DateStyle.DATETIME)); - item.add(new DateLabel("lastSuccessfulRun", wd.map(WorkerData::getLastSuccessfulRun), DateStyle.DATETIME)); - item.add(new Label("period", item.getModel().map(Task::getPeriod).map(SystemMaintenancePage::getElapsedTimeHoursMinutesSecondsString))); + item.add( + new DateLabel("lastSuccessfulRun", wd.map(WorkerData::getLastSuccessfulRun), DateStyle.DATETIME) + ); + item.add( + new Label( + "period", + item + .getModel() + .map(Task::getPeriod) + .map(SystemMaintenancePage::getElapsedTimeHoursMinutesSecondsString) + ) + ); item.add(new Label("descr", item.getModel().map(Task::getDescription))); - item.add(new AjaxFallbackLink<>("startLink", item.getModel()) { - @Override - public void onClick(Optional target) { - scheduler.execute(getModelObject()); - target.ifPresent(t -> t.add(runningContainer)); + item.add( + new AjaxFallbackLink<>("startLink", item.getModel()) { + @Override + public void onClick(Optional target) { + scheduler.execute(getModelObject()); + target.ifPresent(t -> t.add(runningContainer)); + } } - }); + ); } }; scheduledContainer.add(scheduleListView); @@ -125,7 +143,9 @@ public class SystemMaintenancePage extends AbstractAdminSystemPage { private static class SystemNoticeForm extends Form { - private final IModel noticeModel = Model.of(getApplication().getMetaData(SystemNoticePanel.SYSTEM_NOTICE)); + private final IModel noticeModel = Model.of( + getApplication().getMetaData(SystemNoticePanel.SYSTEM_NOTICE) + ); public SystemNoticeForm(String id) { super(id); @@ -141,4 +161,4 @@ public class SystemMaintenancePage extends AbstractAdminSystemPage { } } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateCreationPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateCreationPage.java index 0338617189..6fe634af45 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateCreationPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateCreationPage.java @@ -21,10 +21,13 @@ import se.su.dsv.scipro.report.ValidDateMustBeInTheFutureException; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -public class AdminGradingTemplateCreationPage extends AbstractAdminProjectPage implements MenuHighlightGradingTemplates { +public class AdminGradingTemplateCreationPage + extends AbstractAdminProjectPage + implements MenuHighlightGradingTemplates { @Inject GradingReportTemplateService gradingReportTemplateService; + @Inject ProjectTypeService projectTypeService; @@ -44,10 +47,13 @@ public class AdminGradingTemplateCreationPage extends AbstractAdminProjectPage i GradingReportTemplateUpdate update = AdminGradingTemplateEditPage.toUpdate(editingGradingTemplateModel); try { GradingReportTemplate gradingReportTemplate = gradingReportTemplateService.create( - projectTypeModel.getObject(), - update); + projectTypeModel.getObject(), + update + ); getSession().success(getString("template_created", projectTypeModel)); - PageParameters pageParameters = AdminGradingTemplateEditPage.getPageParameters(gradingReportTemplate); + PageParameters pageParameters = AdminGradingTemplateEditPage.getPageParameters( + gradingReportTemplate + ); throw new RestartResponseException(AdminGradingTemplateEditPage.class, pageParameters); } catch (ValidDateMustBeInTheFutureException e) { error(getString("valid_from_must_be_in_the_future", () -> e)); @@ -64,25 +70,33 @@ public class AdminGradingTemplateCreationPage extends AbstractAdminProjectPage i buttonContainer.setVisible(false); form.add(buttonContainer); - form.add(new AjaxDropDownChoice<>( + form.add( + new AjaxDropDownChoice<>( "project_type", projectTypeModel, gradingReportTemplateService.getProjectTypes(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ProjectType objectSelected) { - buttonContainer.setVisible(true); - target.add(form, buttonContainer); + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ProjectType objectSelected) { + buttonContainer.setVisible(true); + target.add(form, buttonContainer); + } } - }); + ); editingGradingTemplateModel = new EditingGradingTemplate(); - form.add(new EditingGradingTemplateComponentPanel("grading_template_component_panel", Model.of(editingGradingTemplateModel)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(projectTypeModel.getObject() != null); + form.add( + new EditingGradingTemplateComponentPanel( + "grading_template_component_panel", + Model.of(editingGradingTemplateModel) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(projectTypeModel.getObject() != null); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateEditPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateEditPage.java index d2ad546e0f..0b80c08570 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateEditPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplateEditPage.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.admin.pages.grading; import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -21,14 +23,11 @@ import se.su.dsv.scipro.report.TemplateLockedException; import se.su.dsv.scipro.report.ValidDateMustBeInTheFutureException; import se.su.dsv.scipro.system.ProjectType; -import java.util.ArrayList; -import java.util.List; - public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage implements MenuHighlightGradingTemplates { + private static final String GRADING_REPORT_TEMPLATE_ID_PARAMETER = "id"; - public static final GradingReportTemplateUpdate.Criteria.Requirement ZERO_REQUIREMENT = new GradingReportTemplateUpdate.Criteria.Requirement( - 0, - new LocalizedString("", "")); + public static final GradingReportTemplateUpdate.Criteria.Requirement ZERO_REQUIREMENT = + new GradingReportTemplateUpdate.Criteria.Requirement(0, new LocalizedString("", "")); private final WebMarkupContainer unsavedChangesAlert; @@ -45,7 +44,9 @@ public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage imple editingGradingTemplate = new EditingGradingTemplate(template); add(new FeedbackPanel("feedback")); - IModel model = LoadableDetachableModel.of(() -> gradingReportTemplateService.getTemplate(id)); + IModel model = LoadableDetachableModel.of(() -> + gradingReportTemplateService.getTemplate(id) + ); add(new Label("project_type_name", model.map(GradingReportTemplate::getProjectType).map(ProjectType::getName))); Form form = new Form<>("form") { @@ -53,8 +54,7 @@ public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage imple protected void onSubmit() { super.onSubmit(); try { - GradingReportTemplateUpdate update = toUpdate( - editingGradingTemplate); + GradingReportTemplateUpdate update = toUpdate(editingGradingTemplate); GradingReportTemplate newTemplate = gradingReportTemplateService.update(id, update); editingGradingTemplate = new EditingGradingTemplate(newTemplate); @@ -81,34 +81,37 @@ public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage imple form.add(unsavedChangesAlert); unsavedChangesAlert.setOutputMarkupPlaceholderTag(true); - form.add(new EditingGradingTemplateComponentPanel("editing", () -> editingGradingTemplate) { - @Override - protected void onTemplateChanged(AjaxRequestTarget target) { - super.onTemplateChanged(target); - target.add(unsavedChangesAlert); + form.add( + new EditingGradingTemplateComponentPanel("editing", () -> editingGradingTemplate) { + @Override + protected void onTemplateChanged(AjaxRequestTarget target) { + super.onTemplateChanged(target); + target.add(unsavedChangesAlert); + } } - }); + ); add(form); } static GradingReportTemplateUpdate toUpdate(EditingGradingTemplate editingGradingTemplate) { List gradeLimits = editingGradingTemplate - .getGradeLimits() - .getGradeLimits() - .stream() - .map(AdminGradingTemplateEditPage::toGrade) - .toList(); + .getGradeLimits() + .getGradeLimits() + .stream() + .map(AdminGradingTemplateEditPage::toGrade) + .toList(); List criteria = editingGradingTemplate - .getCriteria() - .stream() - .map(AdminGradingTemplateEditPage::toCriteria) - .toList(); + .getCriteria() + .stream() + .map(AdminGradingTemplateEditPage::toCriteria) + .toList(); return new GradingReportTemplateUpdate( - editingGradingTemplate.getValidFrom(), - editingGradingTemplate.getNote(), - editingGradingTemplate.getGradeLimits().getFailingGrade(), - gradeLimits, - criteria); + editingGradingTemplate.getValidFrom(), + editingGradingTemplate.getNote(), + editingGradingTemplate.getGradeLimits().getFailingGrade(), + gradeLimits, + criteria + ); } private static GradingReportTemplateUpdate.Criteria toCriteria(EditingGradingTemplate.Criteria criteria) { @@ -116,19 +119,23 @@ public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage imple requirements.add(ZERO_REQUIREMENT); for (int i = 0; i < criteria.getPoints().size(); i++) { EditingGradingTemplate.Criteria.Point point = criteria.getPoints().get(i); - requirements.add(new GradingReportTemplateUpdate.Criteria.Requirement( + requirements.add( + new GradingReportTemplateUpdate.Criteria.Requirement( i + 1, - new LocalizedString(point.getRequirementEn(), point.getRequirementSv()))); + new LocalizedString(point.getRequirementEn(), point.getRequirementSv()) + ) + ); } return new GradingReportTemplateUpdate.Criteria( - new LocalizedString(criteria.getTitleEn(), criteria.getTitleSv()), - switch (criteria.getType()) { - case PROJECT -> GradingReportTemplateUpdate.Criteria.Type.THESIS; - case INDIVIDUAL -> GradingReportTemplateUpdate.Criteria.Type.INDIVIDUAL; - }, - criteria.getPointsRequiredToPass(), - getFlag(criteria), - requirements); + new LocalizedString(criteria.getTitleEn(), criteria.getTitleSv()), + switch (criteria.getType()) { + case PROJECT -> GradingReportTemplateUpdate.Criteria.Type.THESIS; + case INDIVIDUAL -> GradingReportTemplateUpdate.Criteria.Type.INDIVIDUAL; + }, + criteria.getPointsRequiredToPass(), + getFlag(criteria), + requirements + ); } private static GradingReportTemplateUpdate.Criteria.Flag getFlag(EditingGradingTemplate.Criteria criteria) { @@ -143,9 +150,7 @@ public class AdminGradingTemplateEditPage extends AbstractAdminProjectPage imple } private static GradingReportTemplateUpdate.GradeLimit toGrade(GradeLimits.GradeLimit gradeLimit) { - return new GradingReportTemplateUpdate.GradeLimit( - gradeLimit.getGrade(), - gradeLimit.getLowerLimit()); + return new GradingReportTemplateUpdate.GradeLimit(gradeLimit.getGrade(), gradeLimit.getLowerLimit()); } public static PageParameters getPageParameters(GradingReportTemplate gradingReportTemplate) { diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatePage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatePage.java index f445f860ee..609ddc16f5 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatePage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatePage.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.admin.pages.grading; import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.GenericWebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -16,13 +21,8 @@ import se.su.dsv.scipro.report.GradingCriterionTemplate; import se.su.dsv.scipro.report.GradingReportTemplate; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - public class AdminGradingTemplatePage extends AbstractAdminProjectPage implements MenuHighlightGradingTemplates { + private static final String TEMPLATE_ID_PARAMETER = "id"; @Inject @@ -38,7 +38,8 @@ public class AdminGradingTemplatePage extends AbstractAdminProjectPage implement long templateId = parameters.get(TEMPLATE_ID_PARAMETER).toLong(); IModel template = LoadableDetachableModel.of(() -> - gradingReportTemplateService.getTemplate(templateId)); + gradingReportTemplateService.getTemplate(templateId) + ); if (template.getObject() == null) { throw new RestartResponseException(AdminGradingTemplatesOverviewPage.class); @@ -48,9 +49,9 @@ public class AdminGradingTemplatePage extends AbstractAdminProjectPage implement } private class TemplateDetailsPanel extends GenericWebMarkupContainer { + public TemplateDetailsPanel(String id, IModel model) { super(id, model); - add(new Label("project_type", model.map(GradingReportTemplate::getProjectType).map(ProjectType::getName))); IModel validPeriod = () -> { @@ -66,24 +67,33 @@ public class AdminGradingTemplatePage extends AbstractAdminProjectPage implement add(new Label("valid_period", validPeriod)); - add(new ListView<>("criteria", model.map(this::getCriteria)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("title", item.getModel().map(GradingCriterionTemplate::getTitle))); - item.add(new ListView<>( - "points", - item.getModel().map(GradingCriterionTemplate::getGradingCriterionPointTemplates)) - { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("point", item.getModel().map(GradingCriterionPointTemplate::getPoint))); - item.add(new Label( - "description", - item.getModel().map(GradingCriterionPointTemplate::getDescription))); - } - }); + add( + new ListView<>("criteria", model.map(this::getCriteria)) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("title", item.getModel().map(GradingCriterionTemplate::getTitle))); + item.add( + new ListView<>( + "points", + item.getModel().map(GradingCriterionTemplate::getGradingCriterionPointTemplates) + ) { + @Override + protected void populateItem(ListItem item) { + item.add( + new Label("point", item.getModel().map(GradingCriterionPointTemplate::getPoint)) + ); + item.add( + new Label( + "description", + item.getModel().map(GradingCriterionPointTemplate::getDescription) + ) + ); + } + } + ); + } } - }); + ); } private List getCriteria(GradingReportTemplate gradingReportTemplate) { diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatesOverviewPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatesOverviewPage.java index 7d994d340f..06d39bfb1d 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatesOverviewPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/AdminGradingTemplatesOverviewPage.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.admin.pages.grading; import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.GenericWebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -14,44 +15,62 @@ import se.su.dsv.scipro.grading.GradingReportTemplateService; import se.su.dsv.scipro.report.GradingReportTemplate; import se.su.dsv.scipro.system.ProjectType; -import java.util.List; - public class AdminGradingTemplatesOverviewPage extends AbstractAdminProjectPage { + @Inject private GradingReportTemplateService gradingReportTemplateService; public AdminGradingTemplatesOverviewPage() { - LoadableDetachableModel> projectTypes = - LoadableDetachableModel.of(gradingReportTemplateService::getProjectTypes); + LoadableDetachableModel> projectTypes = LoadableDetachableModel.of( + gradingReportTemplateService::getProjectTypes + ); - add(new ListView<>("project_types", projectTypes) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("name", item.getModel().map(ProjectType::getName))); - item.add(new TemplatesPanel("templates", item.getModel())); + add( + new ListView<>("project_types", projectTypes) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("name", item.getModel().map(ProjectType::getName))); + item.add(new TemplatesPanel("templates", item.getModel())); + } } - }); + ); } private class TemplatesPanel extends GenericWebMarkupContainer { + public TemplatesPanel(String id, IModel model) { super(id, model); - IModel currentTemplate = model.map(gradingReportTemplateService::getCurrentTemplate); add(new Label("valid_from", currentTemplate.map(GradingReportTemplate::getValidFrom))); add(new NonEmptyLabel("note", currentTemplate.map(GradingReportTemplate::getNote))); - add(new BookmarkablePageLink<>("view_template", AdminGradingTemplatePage.class, AdminGradingTemplatePage.getPageParameters(currentTemplate.getObject()))); + add( + new BookmarkablePageLink<>( + "view_template", + AdminGradingTemplatePage.class, + AdminGradingTemplatePage.getPageParameters(currentTemplate.getObject()) + ) + ); - IModel> upcomingTemplates = model.map(gradingReportTemplateService::getUpcomingTemplates); - add(new ListView<>("upcoming_templates", upcomingTemplates) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("valid_from", item.getModel().map(GradingReportTemplate::getValidFrom))); - item.add(new NonEmptyLabel("note", item.getModel().map(GradingReportTemplate::getNote))); - item.add(new BookmarkablePageLink<>("edit_template", AdminGradingTemplateEditPage.class, AdminGradingTemplateEditPage.getPageParameters(item.getModelObject()))); + IModel> upcomingTemplates = model.map( + gradingReportTemplateService::getUpcomingTemplates + ); + add( + new ListView<>("upcoming_templates", upcomingTemplates) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("valid_from", item.getModel().map(GradingReportTemplate::getValidFrom))); + item.add(new NonEmptyLabel("note", item.getModel().map(GradingReportTemplate::getNote))); + item.add( + new BookmarkablePageLink<>( + "edit_template", + AdminGradingTemplateEditPage.class, + AdminGradingTemplateEditPage.getPageParameters(item.getModelObject()) + ) + ); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplate.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplate.java index a56af9d4eb..41b7b808be 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplate.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplate.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.admin.pages.grading; -import se.su.dsv.scipro.report.GradingCriterionPointTemplate; -import se.su.dsv.scipro.report.GradingCriterionTemplate; -import se.su.dsv.scipro.report.GradingReportTemplate; - import java.io.Serializable; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.report.GradingCriterionPointTemplate; +import se.su.dsv.scipro.report.GradingCriterionTemplate; +import se.su.dsv.scipro.report.GradingReportTemplate; class EditingGradingTemplate implements Serializable { + private EditingGradingTemplate original; private String note; private LocalDate validFrom; @@ -33,7 +33,10 @@ class EditingGradingTemplate implements Serializable { * to be able to track changes made. * @param doNotCreateOriginal Only exists to differentiate the signature from the public constructor */ - private EditingGradingTemplate(GradingReportTemplate template, @SuppressWarnings("unused") Void doNotCreateOriginal) { + private EditingGradingTemplate( + GradingReportTemplate template, + @SuppressWarnings("unused") Void doNotCreateOriginal + ) { this.note = template.getNote(); this.validFrom = template.getValidFrom(); this.gradeLimits = new GradeLimits(template); @@ -70,9 +73,7 @@ class EditingGradingTemplate implements Serializable { } public int getMaxPointsAvailable() { - return criteria.stream() - .mapToInt(Criteria::getMaxPoints) - .sum(); + return criteria.stream().mapToInt(Criteria::getMaxPoints).sum(); } public Boolean hasChanges() { @@ -83,7 +84,6 @@ class EditingGradingTemplate implements Serializable { Criteria newCriteria = new Criteria(); newCriteria.points.add(newCriteria.new Point()); this.criteria.add(newCriteria); - } public String getProjectType() { @@ -92,12 +92,14 @@ class EditingGradingTemplate implements Serializable { @Override public boolean equals(Object o) { - return o instanceof EditingGradingTemplate that - && Objects.equals(note, that.note) - && Objects.equals(validFrom, that.validFrom) - && Objects.equals(criteria, that.criteria) - && Objects.equals(gradeLimits, that.gradeLimits) - && Objects.equals(projectType, that.projectType); + return ( + o instanceof EditingGradingTemplate that && + Objects.equals(note, that.note) && + Objects.equals(validFrom, that.validFrom) && + Objects.equals(criteria, that.criteria) && + Objects.equals(gradeLimits, that.gradeLimits) && + Objects.equals(projectType, that.projectType) + ); } @Override @@ -106,12 +108,15 @@ class EditingGradingTemplate implements Serializable { } class Criteria implements Serializable { + enum Flag { - OPPOSITION, REFLECTION + OPPOSITION, + REFLECTION, } enum Type { - PROJECT, INDIVIDUAL + PROJECT, + INDIVIDUAL, } private String titleSv; @@ -130,10 +135,12 @@ class EditingGradingTemplate implements Serializable { Point editingPoint = new Point(point); this.points.add(editingPoint); } - this.flag = criteria.getFlag() == null ? null : switch (criteria.getFlag()) { - case OPPOSITION -> Flag.OPPOSITION; - case REFLECTION -> Flag.REFLECTION; - }; + this.flag = criteria.getFlag() == null + ? null + : switch (criteria.getFlag()) { + case OPPOSITION -> Flag.OPPOSITION; + case REFLECTION -> Flag.REFLECTION; + }; } private Criteria() {} @@ -192,13 +199,15 @@ class EditingGradingTemplate implements Serializable { @Override public boolean equals(Object o) { - return o instanceof Criteria criterion - && pointsRequiredToPass == criterion.pointsRequiredToPass - && Objects.equals(titleSv, criterion.titleSv) - && Objects.equals(titleEn, criterion.titleEn) - && Objects.equals(points, criterion.points) - && flag == criterion.flag - && type == criterion.type; + return ( + o instanceof Criteria criterion && + pointsRequiredToPass == criterion.pointsRequiredToPass && + Objects.equals(titleSv, criterion.titleSv) && + Objects.equals(titleEn, criterion.titleEn) && + Objects.equals(points, criterion.points) && + flag == criterion.flag && + type == criterion.type + ); } @Override @@ -207,6 +216,7 @@ class EditingGradingTemplate implements Serializable { } class Point implements Serializable { + private String requirementEn; private String requirementSv; @@ -238,9 +248,11 @@ class EditingGradingTemplate implements Serializable { @Override public boolean equals(Object o) { - return o instanceof Point point - && Objects.equals(requirementEn, point.requirementEn) - && Objects.equals(requirementSv, point.requirementSv); + return ( + o instanceof Point point && + Objects.equals(requirementEn, point.requirementEn) && + Objects.equals(requirementSv, point.requirementSv) + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplateComponentPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplateComponentPanel.java index 6a59cfa2f5..f9712113c6 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplateComponentPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/EditingGradingTemplateComponentPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages.grading; +import java.time.LocalDate; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -18,112 +20,141 @@ import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.components.AjaxDropDownChoice; import se.su.dsv.scipro.components.BootstrapDatePicker; -import java.time.LocalDate; -import java.util.List; - class EditingGradingTemplateComponentPanel extends GenericPanel { private final Label maxPointsAvailable; - EditingGradingTemplateComponentPanel( - String id, - IModel editingGradingTemplateModel) - { + EditingGradingTemplateComponentPanel(String id, IModel editingGradingTemplateModel) { super(id, editingGradingTemplateModel); - setOutputMarkupId(true); - TextField validFromField = new RequiredTextField<>("valid_from", - LambdaModel.of(editingGradingTemplateModel, - EditingGradingTemplate::getValidFrom, - EditingGradingTemplate::setValidFrom), - LocalDate.class); + TextField validFromField = new RequiredTextField<>( + "valid_from", + LambdaModel.of( + editingGradingTemplateModel, + EditingGradingTemplate::getValidFrom, + EditingGradingTemplate::setValidFrom + ), + LocalDate.class + ); validFromField.add(new BootstrapDatePicker()); validFromField.add(new AutoSave("changeDate")); add(validFromField); - add(new TextArea<>("note", LambdaModel.of( - editingGradingTemplateModel, - EditingGradingTemplate::getNote, - EditingGradingTemplate::setNote)) { - { - add(new AutoSave()); + add( + new TextArea<>( + "note", + LambdaModel.of( + editingGradingTemplateModel, + EditingGradingTemplate::getNote, + EditingGradingTemplate::setNote + ) + ) { + { + add(new AutoSave()); + } } - }); + ); - add(new GradeLimitsPanel("grade_limits", editingGradingTemplateModel.map(EditingGradingTemplate::getGradeLimits))); + add( + new GradeLimitsPanel( + "grade_limits", + editingGradingTemplateModel.map(EditingGradingTemplate::getGradeLimits) + ) + ); - maxPointsAvailable = new Label("max_points_available", editingGradingTemplateModel.map(EditingGradingTemplate::getMaxPointsAvailable)); + maxPointsAvailable = new Label( + "max_points_available", + editingGradingTemplateModel.map(EditingGradingTemplate::getMaxPointsAvailable) + ); maxPointsAvailable.setOutputMarkupId(true); add(maxPointsAvailable); + add( + new ListView<>("criteria", editingGradingTemplateModel.map(EditingGradingTemplate::getCriteria)) { + { + setReuseItems(true); + } - add(new ListView<>("criteria", editingGradingTemplateModel.map(EditingGradingTemplate::getCriteria)) { - { - setReuseItems(true); + @Override + protected void populateItem(ListItem item) { + item.add( + new AjaxLink<>("remove") { + @Override + public void onClick(AjaxRequestTarget target) { + editingGradingTemplateModel.getObject().getCriteria().remove(item.getModelObject()); + target.add(EditingGradingTemplateComponentPanel.this); + onTemplateChanged(target); + } + } + ); + item.add(new CriteriaEditingPanel("criteria", item.getModel())); + } } + ); - @Override - protected void populateItem(ListItem item) { - item.add(new AjaxLink<>("remove") { - @Override - public void onClick(AjaxRequestTarget target) { - editingGradingTemplateModel.getObject().getCriteria().remove(item.getModelObject()); - target.add(EditingGradingTemplateComponentPanel.this); - onTemplateChanged(target); - } - }); - item.add(new CriteriaEditingPanel("criteria", item.getModel())); + add( + new AjaxLink<>("add_criteria") { + @Override + public void onClick(AjaxRequestTarget target) { + editingGradingTemplateModel.getObject().addCriteria(); + target.add(EditingGradingTemplateComponentPanel.this); + onTemplateChanged(target); + } } - }); - - add(new AjaxLink<>("add_criteria") { - @Override - public void onClick(AjaxRequestTarget target) { - editingGradingTemplateModel.getObject().addCriteria(); - target.add(EditingGradingTemplateComponentPanel.this); - onTemplateChanged(target); - } - }); + ); } class CriteriaEditingPanel extends GenericWebMarkupContainer { + CriteriaEditingPanel(String id, IModel model) { super(id, model); - setOutputMarkupId(true); - add(new RequiredTextField<>("title_sv", LambdaModel.of( - model, - EditingGradingTemplate.Criteria::getTitleSv, - EditingGradingTemplate.Criteria::setTitleSv)) { - { - add(new AutoSave()); + add( + new RequiredTextField<>( + "title_sv", + LambdaModel.of( + model, + EditingGradingTemplate.Criteria::getTitleSv, + EditingGradingTemplate.Criteria::setTitleSv + ) + ) { + { + add(new AutoSave()); + } } - }); - add(new RequiredTextField<>("title_en", LambdaModel.of( - model, - EditingGradingTemplate.Criteria::getTitleEn, - EditingGradingTemplate.Criteria::setTitleEn)) { - { - add(new AutoSave()); + ); + add( + new RequiredTextField<>( + "title_en", + LambdaModel.of( + model, + EditingGradingTemplate.Criteria::getTitleEn, + EditingGradingTemplate.Criteria::setTitleEn + ) + ) { + { + add(new AutoSave()); + } } - }); + ); AjaxDropDownChoice typeChoice = new AjaxDropDownChoice<>( - "type", - LambdaModel.of( - model, - EditingGradingTemplate.Criteria::getType, - EditingGradingTemplate.Criteria::setType), - List.of(EditingGradingTemplate.Criteria.Type.values()), - new EnumChoiceRenderer<>(this)) - { + "type", + LambdaModel.of( + model, + EditingGradingTemplate.Criteria::getType, + EditingGradingTemplate.Criteria::setType + ), + List.of(EditingGradingTemplate.Criteria.Type.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onNewSelection( - AjaxRequestTarget target, - EditingGradingTemplate.Criteria.Type objectSelected) - { + AjaxRequestTarget target, + EditingGradingTemplate.Criteria.Type objectSelected + ) { // auto save onTemplateChanged(target); } @@ -132,31 +163,34 @@ class EditingGradingTemplateComponentPanel extends GenericPanel pointsRequiredToPass = new NumberTextField<>( - "points_required_to_pass", - LambdaModel.of( - model, - EditingGradingTemplate.Criteria::getPointsRequiredToPass, - EditingGradingTemplate.Criteria::setPointsRequiredToPass), - Integer.class); + "points_required_to_pass", + LambdaModel.of( + model, + EditingGradingTemplate.Criteria::getPointsRequiredToPass, + EditingGradingTemplate.Criteria::setPointsRequiredToPass + ), + Integer.class + ); pointsRequiredToPass.setMinimum(0); pointsRequiredToPass.setRequired(true); pointsRequiredToPass.add(new AutoSave()); add(pointsRequiredToPass); AjaxDropDownChoice flagChoice = new AjaxDropDownChoice<>( - "flag", - LambdaModel.of( - model, - EditingGradingTemplate.Criteria::getFlag, - EditingGradingTemplate.Criteria::setFlag), - List.of(EditingGradingTemplate.Criteria.Flag.values()), - new EnumChoiceRenderer<>(this)) - { + "flag", + LambdaModel.of( + model, + EditingGradingTemplate.Criteria::getFlag, + EditingGradingTemplate.Criteria::setFlag + ), + List.of(EditingGradingTemplate.Criteria.Flag.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onNewSelection( - AjaxRequestTarget target, - EditingGradingTemplate.Criteria.Flag objectSelected) - { + AjaxRequestTarget target, + EditingGradingTemplate.Criteria.Flag objectSelected + ) { // auto save onTemplateChanged(target); } @@ -164,142 +198,171 @@ class EditingGradingTemplateComponentPanel extends GenericPanel("points", model.map(EditingGradingTemplate.Criteria::getPoints)) { - { - setReuseItems(true); - } + add( + new ListView<>("points", model.map(EditingGradingTemplate.Criteria::getPoints)) { + { + setReuseItems(true); + } - @Override - protected void populateItem(ListItem item) { - item.add(new PointEditingPanel("point", item)); + @Override + protected void populateItem(ListItem item) { + item.add(new PointEditingPanel("point", item)); + } } - }); + ); - add(new Label("new_point", model - .map(criteria -> criteria.getPoints().size()) - .map(size -> "Requirement for " + (size + 1) + " points"))); + add( + new Label( + "new_point", + model + .map(criteria -> criteria.getPoints().size()) + .map(size -> "Requirement for " + (size + 1) + " points") + ) + ); - add(new AjaxLink<>("add_new_point") { - @Override - public void onClick(AjaxRequestTarget target) { - EditingGradingTemplate.Criteria criteria = model.getObject(); - EditingGradingTemplate.Criteria.Point newPoint = criteria.new Point(); - criteria.getPoints().add(newPoint); - target.add(CriteriaEditingPanel.this); - target.add(maxPointsAvailable); - onTemplateChanged(target); + add( + new AjaxLink<>("add_new_point") { + @Override + public void onClick(AjaxRequestTarget target) { + EditingGradingTemplate.Criteria criteria = model.getObject(); + EditingGradingTemplate.Criteria.Point newPoint = criteria.new Point(); + criteria.getPoints().add(newPoint); + target.add(CriteriaEditingPanel.this); + target.add(maxPointsAvailable); + onTemplateChanged(target); + } } - }); + ); } private class PointEditingPanel extends GenericWebMarkupContainer { + public PointEditingPanel(String id, ListItem item) { super(id, item.getModel()); - IModel model = item.getModel(); add(new Label("point", () -> item.getIndex() + 1)); - TextArea englishRequirement = new TextArea<>("requirement_en", LambdaModel.of( + TextArea englishRequirement = new TextArea<>( + "requirement_en", + LambdaModel.of( model, EditingGradingTemplate.Criteria.Point::getRequirementEn, - EditingGradingTemplate.Criteria.Point::setRequirementEn)); + EditingGradingTemplate.Criteria.Point::setRequirementEn + ) + ); englishRequirement.setRequired(true); englishRequirement.add(new AutoSave()); add(englishRequirement); - TextArea swedishRequirement = new TextArea<>("requirement_sv", LambdaModel.of( + TextArea swedishRequirement = new TextArea<>( + "requirement_sv", + LambdaModel.of( model, EditingGradingTemplate.Criteria.Point::getRequirementSv, - EditingGradingTemplate.Criteria.Point::setRequirementSv)); + EditingGradingTemplate.Criteria.Point::setRequirementSv + ) + ); swedishRequirement.setRequired(true); swedishRequirement.add(new AutoSave()); add(swedishRequirement); - add(new AjaxLink<>("remove") { - @Override - public void onClick(AjaxRequestTarget target) { - EditingGradingTemplate.Criteria criteria = CriteriaEditingPanel.this.getModelObject(); - criteria.getPoints().remove(model.getObject()); - target.add(CriteriaEditingPanel.this); - onTemplateChanged(target); + add( + new AjaxLink<>("remove") { + @Override + public void onClick(AjaxRequestTarget target) { + EditingGradingTemplate.Criteria criteria = CriteriaEditingPanel.this.getModelObject(); + criteria.getPoints().remove(model.getObject()); + target.add(CriteriaEditingPanel.this); + onTemplateChanged(target); + } } - }); + ); } } } private class GradeLimitsPanel extends GenericWebMarkupContainer { + public GradeLimitsPanel(String id, IModel model) { super(id, model); - setOutputMarkupId(true); - add(new RequiredTextField<>("failing_grade", LambdaModel.of( - model, - GradeLimits::getFailingGrade, - GradeLimits::setFailingGrade)) { - { - add(new AutoSave()); + add( + new RequiredTextField<>( + "failing_grade", + LambdaModel.of(model, GradeLimits::getFailingGrade, GradeLimits::setFailingGrade) + ) { + { + add(new AutoSave()); + } } - }); + ); - add(new ListView<>("grade_limits", model.map(GradeLimits::getGradeLimits)) { - { - setReuseItems(true); - } + add( + new ListView<>("grade_limits", model.map(GradeLimits::getGradeLimits)) { + { + setReuseItems(true); + } - @Override - protected void populateItem(ListItem item) { - item.add(new GradeLimitEditingPanel("grade_limit", item.getModel())); + @Override + protected void populateItem(ListItem item) { + item.add(new GradeLimitEditingPanel("grade_limit", item.getModel())); + } } - }); + ); - add(new AjaxLink<>("add") { - @Override - public void onClick(AjaxRequestTarget target) { - GradeLimits gradeLimits = GradeLimitsPanel.this.getModelObject(); - gradeLimits.addNewLimit(); - target.add(GradeLimitsPanel.this); - onTemplateChanged(target); + add( + new AjaxLink<>("add") { + @Override + public void onClick(AjaxRequestTarget target) { + GradeLimits gradeLimits = GradeLimitsPanel.this.getModelObject(); + gradeLimits.addNewLimit(); + target.add(GradeLimitsPanel.this); + onTemplateChanged(target); + } } - }); + ); } private class GradeLimitEditingPanel extends GenericWebMarkupContainer { + public GradeLimitEditingPanel(String id, IModel model) { super(id, model); - - NumberTextField minimum = new NumberTextField<>("minimum", LambdaModel.of( - model, - GradeLimits.GradeLimit::getLowerLimit, - GradeLimits.GradeLimit::setLowerLimit), Integer.class); + NumberTextField minimum = new NumberTextField<>( + "minimum", + LambdaModel.of(model, GradeLimits.GradeLimit::getLowerLimit, GradeLimits.GradeLimit::setLowerLimit), + Integer.class + ); minimum.setRequired(true); minimum.add(new AutoSave()); add(minimum); - TextField grade = new TextField<>("grade", LambdaModel.of( - model, - GradeLimits.GradeLimit::getGrade, - GradeLimits.GradeLimit::setGrade)); + TextField grade = new TextField<>( + "grade", + LambdaModel.of(model, GradeLimits.GradeLimit::getGrade, GradeLimits.GradeLimit::setGrade) + ); grade.setRequired(true); grade.add(new AutoSave()); add(grade); - add(new AjaxLink<>("remove") { - @Override - public void onClick(AjaxRequestTarget target) { - GradeLimits gradeLimits = GradeLimitsPanel.this.getModelObject(); - gradeLimits.getGradeLimits().remove(model.getObject()); - target.add(GradeLimitsPanel.this); - onTemplateChanged(target); + add( + new AjaxLink<>("remove") { + @Override + public void onClick(AjaxRequestTarget target) { + GradeLimits gradeLimits = GradeLimitsPanel.this.getModelObject(); + gradeLimits.getGradeLimits().remove(model.getObject()); + target.add(GradeLimitsPanel.this); + onTemplateChanged(target); + } } - }); + ); } } } private class AutoSave extends AjaxFormComponentUpdatingBehavior { + public AutoSave() { super("input"); } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/GradeLimits.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/GradeLimits.java index dae5812f7a..095b37d366 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/GradeLimits.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/GradeLimits.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.admin.pages.grading; -import se.su.dsv.scipro.report.GradingReportTemplate; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import se.su.dsv.scipro.report.GradingReportTemplate; class GradeLimits implements Serializable { + private List gradeLimits; private String failingGrade; @@ -44,10 +44,11 @@ class GradeLimits implements Serializable { @Override public boolean equals(Object o) { - - return o instanceof GradeLimits that - && Objects.equals(gradeLimits, that.gradeLimits) - && Objects.equals(failingGrade, that.failingGrade); + return ( + o instanceof GradeLimits that && + Objects.equals(gradeLimits, that.gradeLimits) && + Objects.equals(failingGrade, that.failingGrade) + ); } @Override @@ -56,6 +57,7 @@ class GradeLimits implements Serializable { } class GradeLimit implements Serializable { + private String grade; private int lowerLimit; @@ -77,9 +79,7 @@ class GradeLimits implements Serializable { @Override public boolean equals(Object o) { - return o instanceof GradeLimit that - && lowerLimit == that.lowerLimit - && Objects.equals(grade, that.grade); + return (o instanceof GradeLimit that && lowerLimit == that.lowerLimit && Objects.equals(grade, that.grade)); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/MenuHighlightGradingTemplates.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/MenuHighlightGradingTemplates.java index 0ff8cfc851..40d8dcf08c 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/MenuHighlightGradingTemplates.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/grading/MenuHighlightGradingTemplates.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.admin.pages.grading; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlight; -public interface MenuHighlightGradingTemplates extends MenuHighlight { -} +public interface MenuHighlightGradingTemplates extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPage.java index 14491beac9..a6e04ec1b7 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPage.java @@ -8,8 +8,8 @@ import se.su.dsv.scipro.admin.panels.AdminEditFooterAddressPanel; import se.su.dsv.scipro.admin.panels.AdminEditFooterColumnPanel; import se.su.dsv.scipro.system.FooterColumn; - public class AdminFooterSettingsPage extends AbstractAdminSystemPage { + public AdminFooterSettingsPage() { add(new EnumLabel<>("firstTab", FooterColumn.FIRST)); add(new EnumLabel<>("secondTab", FooterColumn.SECOND)); diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPage.java index d460d34769..299e0a688b 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.pages.settings; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.extensions.model.AbstractCheckBoxModel; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; @@ -14,10 +17,6 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public class AdminProjectModuleSettingsPage extends AbstractAdminSystemPage { public static final String PROJECT_TYPE_LIST = "projectTypeList"; @@ -42,25 +41,35 @@ public class AdminProjectModuleSettingsPage extends AbstractAdminSystemPage { } }; add(form); - form.add(new ListView<>(HEADER_LIST, form.getModel()) { - - @Override - protected void populateItem(ListItem item) { - item.add(new Label(HEADER_NAME, item.getModel().map(ProjectType::getName))); + form.add( + new ListView<>(HEADER_LIST, form.getModel()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(HEADER_NAME, item.getModel().map(ProjectType::getName))); + } } - }); - form.add(new ListView<>(MODULE_LIST, Arrays.asList(ProjectModule.values())) { - @Override - protected void populateItem(final ListItem moduleItem) { - moduleItem.add(new EnumLabel<>(NAME, moduleItem.getModel())); - moduleItem.add(new ListView<>(PROJECT_TYPE_LIST, form.getModel()) { - @Override - protected void populateItem(ListItem item) { - item.add(new CheckBox(CHECKBOX, new ModuleModel(item.getModel(), moduleItem.getModelObject()))); - } - }); + ); + form.add( + new ListView<>(MODULE_LIST, Arrays.asList(ProjectModule.values())) { + @Override + protected void populateItem(final ListItem moduleItem) { + moduleItem.add(new EnumLabel<>(NAME, moduleItem.getModel())); + moduleItem.add( + new ListView<>(PROJECT_TYPE_LIST, form.getModel()) { + @Override + protected void populateItem(ListItem item) { + item.add( + new CheckBox( + CHECKBOX, + new ModuleModel(item.getModel(), moduleItem.getModelObject()) + ) + ); + } + } + ); + } } - }); + ); } private LoadableDetachableModel> getProjectTypes() { @@ -97,6 +106,4 @@ public class AdminProjectModuleSettingsPage extends AbstractAdminSystemPage { projectTypeModel.getObject().removeModule(projectModule); } } - - } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPage.java index 9f68227ffa..52e304fb15 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.pages.settings; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -15,9 +17,6 @@ import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.List; - public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { @Inject @@ -28,7 +27,6 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { add(modalWindowPlus); IModel> activeProjectType = new LoadableDetachableModel<>() { - @Override protected List load() { return projectTypeService.findAllActive(); @@ -48,7 +46,6 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { item.add(new MultiLineLabel("desc", model.getObject().getDescription())); AjaxLink editLink = new AjaxLink<>("editLink") { - @Override public void onClick(AjaxRequestTarget target) { modalWindowPlus.setContent(new AdminProjectTypePanel(modalWindowPlus.getContentId(), model)); @@ -58,12 +55,10 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { }; item.add(editLink); } - }; activeWmc.add(listView); final IModel> deletedProjectType = new LoadableDetachableModel<>() { - @Override protected List load() { return projectTypeService.findAllDeleted(); @@ -83,7 +78,6 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { item.add(new MultiLineLabel("descDel", model.getObject().getDescription())); AjaxLink undeleteLink = new AjaxLink<>("undeleteLink") { - @Override public void onClick(AjaxRequestTarget target) { model.getObject().setDeleted(false); @@ -96,7 +90,6 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { }; item.add(undeleteLink); } - }; deletedWmc.add(listViewDeleted); @@ -110,5 +103,4 @@ public class AdminProjectTypeSettingsPage extends AbstractAdminSystemPage { }; add(createLink); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPage.java index 4c508708f1..cca02082e0 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.admin.pages.settings; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.model.IModel; @@ -9,9 +10,6 @@ import se.su.dsv.scipro.admin.pages.AbstractAdminSystemPage; import se.su.dsv.scipro.reviewing.ReviewerDeadlineSettings; import se.su.dsv.scipro.reviewing.ReviewerDeadlineSettingsService; -import jakarta.inject.Inject; - - public class AdminReviewerDeadlineSettingsPage extends AbstractAdminSystemPage { @Inject @@ -31,17 +29,42 @@ public class AdminReviewerDeadlineSettingsPage extends AbstractAdminSystemPage { } private class ReviewerDeadlineSettingsForm extends Form { + public ReviewerDeadlineSettingsForm(String id, IModel model) { super(id, model); - add(new RequiredTextField<>("roughDraftApproval", - LambdaModel.of(model, ReviewerDeadlineSettings::getRoughDraftApproval, ReviewerDeadlineSettings::setRoughDraftApproval), - Integer.class)); - add(new RequiredTextField<>("finalSeminarApproval", - LambdaModel.of(model, ReviewerDeadlineSettings::getFinalSeminarApproval, ReviewerDeadlineSettings::setFinalSeminarApproval), - Integer.class)); - add(new RequiredTextField<>("finalGrading", - LambdaModel.of(model, ReviewerDeadlineSettings::getFinalGrading, ReviewerDeadlineSettings::setFinalGrading), - Integer.class)); + add( + new RequiredTextField<>( + "roughDraftApproval", + LambdaModel.of( + model, + ReviewerDeadlineSettings::getRoughDraftApproval, + ReviewerDeadlineSettings::setRoughDraftApproval + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + "finalSeminarApproval", + LambdaModel.of( + model, + ReviewerDeadlineSettings::getFinalSeminarApproval, + ReviewerDeadlineSettings::setFinalSeminarApproval + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + "finalGrading", + LambdaModel.of( + model, + ReviewerDeadlineSettings::getFinalGrading, + ReviewerDeadlineSettings::setFinalGrading + ), + Integer.class + ) + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminUrkundSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminUrkundSettingsPage.java index acccdd4e39..be971e9b7a 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminUrkundSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/pages/settings/AdminUrkundSettingsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.admin.pages.settings; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; @@ -10,9 +11,8 @@ import se.su.dsv.scipro.admin.pages.AbstractAdminSystemPage; import se.su.dsv.scipro.plagiarism.urkund.UrkundSettings; import se.su.dsv.scipro.plagiarism.urkund.UrkundSettingsRepository; -import jakarta.inject.Inject; - public class AdminUrkundSettingsPage extends AbstractAdminSystemPage { + @Inject private UrkundSettingsRepository urkundSettingsRepository; @@ -30,12 +30,24 @@ public class AdminUrkundSettingsPage extends AbstractAdminSystemPage { } private class UrkundSettingsForm extends Form { + public UrkundSettingsForm(final String id, final IModel settings) { super(id, settings); - - add(new CheckBox("enabled", LambdaModel.of(settings, UrkundSettings::isEnabled, UrkundSettings::setEnabled))); - add(new TextField<>("username", LambdaModel.of(settings, UrkundSettings::getUsername, UrkundSettings::setUsername))); - add(new TextField<>("password", LambdaModel.of(settings, UrkundSettings::getPassword, UrkundSettings::setPassword))); + add( + new CheckBox("enabled", LambdaModel.of(settings, UrkundSettings::isEnabled, UrkundSettings::setEnabled)) + ); + add( + new TextField<>( + "username", + LambdaModel.of(settings, UrkundSettings::getUsername, UrkundSettings::setUsername) + ) + ); + add( + new TextField<>( + "password", + LambdaModel.of(settings, UrkundSettings::getPassword, UrkundSettings::setPassword) + ) + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanel.java index eb36d66e9e..0a879b3261 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanel.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.admin.panels; +import jakarta.inject.Inject; import jakarta.transaction.Transactional; +import java.util.List; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.panel.Panel; @@ -10,9 +12,6 @@ import org.apache.wicket.model.Model; import se.su.dsv.scipro.system.FooterAddress; import se.su.dsv.scipro.system.FooterAddressRepo; -import jakarta.inject.Inject; -import java.util.List; - public class AdminEditFooterAddressPanel extends Panel { @Inject @@ -32,10 +31,15 @@ public class AdminEditFooterAddressPanel extends Panel { public AddressForm(String form, IModel footerAddressModel) { super(form, footerAddressModel); - - title = new RequiredTextField<>("title", LambdaModel.of(footerAddressModel, FooterAddress::getTitle, FooterAddress::setTitle)); + title = new RequiredTextField<>( + "title", + LambdaModel.of(footerAddressModel, FooterAddress::getTitle, FooterAddress::setTitle) + ); add(title); - address = new RequiredTextField<>("address", LambdaModel.of(footerAddressModel, FooterAddress::getAddress, FooterAddress::setAddress)); + address = new RequiredTextField<>( + "address", + LambdaModel.of(footerAddressModel, FooterAddress::getAddress, FooterAddress::setAddress) + ); add(address); } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanel.java index b6338863af..ab1349ac1d 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.panels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -18,9 +20,6 @@ import se.su.dsv.scipro.system.FooterColumn; import se.su.dsv.scipro.system.FooterLink; import se.su.dsv.scipro.system.FooterLinkService; -import jakarta.inject.Inject; -import java.util.List; - public class AdminEditFooterColumnPanel extends Panel { @Inject @@ -30,7 +29,6 @@ public class AdminEditFooterColumnPanel extends Panel { public AdminEditFooterColumnPanel(final String id, final FooterColumn column) { super(id); - final AddFooterLinkForm addForm = new AddFooterLinkForm("new", column); add(addForm); @@ -44,43 +42,57 @@ public class AdminEditFooterColumnPanel extends Panel { @Override protected void populateItem(final ListItem item) { final IModel footerLinkModel = item.getModel(); - item.add(new ExternalLink("link", LambdaModel.of(footerLinkModel, FooterLink::getUrl, FooterLink::setUrl), LambdaModel.of(footerLinkModel, FooterLink::getTitle, FooterLink::setTitle))); + item.add( + new ExternalLink( + "link", + LambdaModel.of(footerLinkModel, FooterLink::getUrl, FooterLink::setUrl), + LambdaModel.of(footerLinkModel, FooterLink::getTitle, FooterLink::setTitle) + ) + ); // Using a form so the user stays on the correct tab after deleting. - item.add(new Form<>("delete", footerLinkModel) { - @Override - public void onSubmit() { - if (addForm.getModelObject().equals(item.getModelObject())) { - FooterLink footerLink = new FooterLink(); - footerLink.setFooterColumn(column); - footerLink.setTitle(""); - footerLink.setUrl(""); - addForm.setModel(Model.of(footerLink)); + item.add( + new Form<>("delete", footerLinkModel) { + @Override + public void onSubmit() { + if (addForm.getModelObject().equals(item.getModelObject())) { + FooterLink footerLink = new FooterLink(); + footerLink.setFooterColumn(column); + footerLink.setTitle(""); + footerLink.setUrl(""); + addForm.setModel(Model.of(footerLink)); + } + footerLinkService.delete(getModelObject()); + AdminEditFooterColumnPanel.this.info(getString("deleted", getModel())); + refreshLinks(); } - footerLinkService.delete(getModelObject()); - AdminEditFooterColumnPanel.this.info(getString("deleted", getModel())); - refreshLinks(); } - }); - item.add(new Form<>("edit", footerLinkModel) { - @Override - protected void onSubmit() { - addForm.setModel(getModel()); + ); + item.add( + new Form<>("edit", footerLinkModel) { + @Override + protected void onSubmit() { + addForm.setModel(getModel()); + } } - }); - item.add(new Form<>("up", footerLinkModel) { - @Override - protected void onSubmit() { - footerLinkService.moveUp(getModelObject()); - refreshLinks(); + ); + item.add( + new Form<>("up", footerLinkModel) { + @Override + protected void onSubmit() { + footerLinkService.moveUp(getModelObject()); + refreshLinks(); + } } - }); - item.add(new Form<>("down", footerLinkModel) { - @Override - protected void onSubmit() { - footerLinkService.moveDown(getModelObject()); - refreshLinks(); + ); + item.add( + new Form<>("down", footerLinkModel) { + @Override + protected void onSubmit() { + footerLinkService.moveDown(getModelObject()); + refreshLinks(); + } } - }); + ); } }; add(links); @@ -92,6 +104,7 @@ public class AdminEditFooterColumnPanel extends Panel { } private class AddFooterLinkForm extends Form { + private FooterColumn footerColumn; private final WebMarkupContainer toggle; @@ -101,7 +114,9 @@ public class AdminEditFooterColumnPanel extends Panel { super(id); this.footerColumn = footerColumn; setModel(Model.of(new FooterLink())); - add(new RequiredTextField<>("title", LambdaModel.of(getModel(), FooterLink::getTitle, FooterLink::setTitle))); + add( + new RequiredTextField<>("title", LambdaModel.of(getModel(), FooterLink::getTitle, FooterLink::setTitle)) + ); add(new RequiredTextField<>("url", LambdaModel.of(getModel(), FooterLink::getUrl, FooterLink::setUrl))); help = new WebMarkupContainer("urlHelp"); @@ -113,7 +128,9 @@ public class AdminEditFooterColumnPanel extends Panel { @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forComponent(toggle, "click", String.format("$('#%s').toggle();", help.getMarkupId()))); + response.render( + OnEventHeaderItem.forComponent(toggle, "click", String.format("$('#%s').toggle();", help.getMarkupId())) + ); response.render(OnDomReadyHeaderItem.forScript(String.format("$('#%s').hide();", help.getMarkupId()))); } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminMailPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminMailPanel.java index 35c9cc82ab..bd487d2cb4 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminMailPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminMailPanel.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.admin.panels; import com.google.common.collect.Lists; +import jakarta.inject.Inject; +import java.time.Instant; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; @@ -52,11 +56,6 @@ import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.CopyTextPanel; -import jakarta.inject.Inject; -import java.time.Instant; -import java.time.ZonedDateTime; -import java.util.*; - public class AdminMailPanel extends Panel { public static final int MONTHS = 6; @@ -64,10 +63,13 @@ public class AdminMailPanel extends Panel { @Inject private MailEventService mailEventService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; + @Inject private ProjectTypeService projectTypeService; + @Inject private MailFacade mailFacade; @@ -126,10 +128,14 @@ public class AdminMailPanel extends Panel { } private void setUpProjectTypeSelection() { - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectType", - projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectType", + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { projectTypeList.clear(); @@ -197,7 +203,6 @@ public class AdminMailPanel extends Panel { private void addChoiceBehaviors() { AjaxFormChoiceComponentUpdatingBehavior projectChoiceBehavior = new AjaxFormChoiceComponentUpdatingBehavior() { - @Override protected void onUpdate(AjaxRequestTarget target) { selectedRecipientSet = projectChoice.getModelObject(); @@ -205,16 +210,13 @@ public class AdminMailPanel extends Panel { } }; AjaxFormChoiceComponentUpdatingBehavior ideaChoiceBehavior = new AjaxFormChoiceComponentUpdatingBehavior() { - @Override protected void onUpdate(AjaxRequestTarget target) { selectedRecipientSet = ideaChoice.getModelObject(); updateUserSet(target); } - }; AjaxFormChoiceComponentUpdatingBehavior mainChoiceBehavior = new AjaxFormChoiceComponentUpdatingBehavior() { - @Override protected void onUpdate(AjaxRequestTarget target) { if (choice.getModelObject().equals(PROJECTS)) { @@ -256,6 +258,7 @@ public class AdminMailPanel extends Panel { } public class MailForm extends Form { + private TextField mailSubjectField; private TextArea mailBodyField; private String fromName; @@ -267,16 +270,21 @@ public class AdminMailPanel extends Panel { fromName = gsettings.getMailFromName(); fromEmail = gsettings.getSystemFromMail(); - Label disabledLabel = new Label("disabledLabel", - "Sending of e-mail through SciPro is inactivated. Please activate it under Admin -> System Settings, if you want to use this feature."); + Label disabledLabel = new Label( + "disabledLabel", + "Sending of e-mail through SciPro is inactivated. Please activate it under Admin -> System Settings, if you want to use this feature." + ); disabledLabel.setVisible(!gsettings.isMailNotifications()); add(disabledLabel); Button submitButton = new Button("submitButton"); submitButton.setEnabled(gsettings.isMailNotifications()); - submitButton.add(AttributeModifier.replace( + submitButton.add( + AttributeModifier.replace( "onclick", - "if (!confirm('Are you sure you want to send this e-mail to the selected recipients?')){ return false; }")); + "if (!confirm('Are you sure you want to send this e-mail to the selected recipients?')){ return false; }" + ) + ); add(submitButton); mailSubjectField = new TextField<>("mailSubjectField", presetSubject); mailSubjectField.setRequired(true); @@ -307,48 +315,64 @@ public class AdminMailPanel extends Panel { } }; - palette = new CSPPalette<>("palette", Model.ofList(new ArrayList()), getUserList(), icr, 5, false, false) { + palette = new CSPPalette<>( + "palette", + Model.ofList(new ArrayList()), + getUserList(), + icr, + 5, + false, + false + ) { @Override protected Recorder newRecorderComponent() { Recorder recorder = super.newRecorderComponent(); - recorder.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(total); + recorder.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(total); + } } - }); + ); return recorder; } - }; palette.setOutputMarkupId(true); add(palette); - total = new Label("totalRecipients", new LoadableDetachableModel() { - @Override - protected Integer load() { - return palette.getModelCollection().size(); + total = new Label( + "totalRecipients", + new LoadableDetachableModel() { + @Override + protected Integer load() { + return palette.getModelCollection().size(); + } } - }); + ); total.setOutputMarkupId(true); add(total); modalWindowPlus = new ModalWindowPlus("dialog"); add(modalWindowPlus); - add(new AjaxLink("copy") { - @Override - public void onClick(AjaxRequestTarget target) { - String separator = System.getProperty("line.separator"); - StringBuilder str = new StringBuilder(); - Collection selectedChoices = palette.getModelCollection(); - for (Recipient user : selectedChoices) { - str.append(user.accept(new DisplayingVisitor())).append(',').append(separator); + add( + new AjaxLink("copy") { + @Override + public void onClick(AjaxRequestTarget target) { + String separator = System.getProperty("line.separator"); + StringBuilder str = new StringBuilder(); + Collection selectedChoices = palette.getModelCollection(); + for (Recipient user : selectedChoices) { + str.append(user.accept(new DisplayingVisitor())).append(',').append(separator); + } + modalWindowPlus.setContent( + new CopyTextPanel(modalWindowPlus.getContentId(), Model.of(str.toString())) + ); + modalWindowPlus.show(target); } - modalWindowPlus.setContent(new CopyTextPanel(modalWindowPlus.getContentId(), Model.of(str.toString()))); - modalWindowPlus.show(target); } - }); + ); } @Override @@ -357,7 +381,13 @@ public class AdminMailPanel extends Panel { List selected = SciProUtilities.copyIterator(palette.getSelectedChoices()); if (!selected.isEmpty()) { for (List list : Lists.partition(selected, RECIPIENTS_PER_MAIL)) { - MailEvent me = new MailEvent(mailSubjectField.getInput(), mailBodyField.getInput(), Collections.emptySet(), fromName, fromEmail); + MailEvent me = new MailEvent( + mailSubjectField.getInput(), + mailBodyField.getInput(), + Collections.emptySet(), + fromName, + fromEmail + ); me.addRecipients(list); mailEventService.save(me); } @@ -381,6 +411,7 @@ public class AdminMailPanel extends Panel { } private static class DisplayingVisitor implements RecipientVisitor { + @Override public String visit(final EmailRecipient emailRecipient) { return emailRecipient.getEmail(); diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanel.java index 8284ab8966..e7b5403e75 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.admin.panels; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.markup.html.form.*; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; @@ -11,9 +13,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.ProjectTypeSettings; -import jakarta.inject.Inject; -import java.util.Arrays; - public class AdminProjectTypePanel extends Panel { @Inject @@ -21,13 +20,11 @@ public class AdminProjectTypePanel extends Panel { public AdminProjectTypePanel(final String id) { super(id); - add(new ProjectTypeSettingsForm("projectTypeForm", new Model<>(new ProjectType()), false)); } public AdminProjectTypePanel(String id, IModel model) { super(id); - add(new ProjectTypeSettingsForm("projectTypeForm", model, true)); } @@ -37,65 +34,90 @@ public class AdminProjectTypePanel extends Panel { public ProjectTypeSettingsForm(String id, final IModel model, final boolean editMode) { super(id, model); - projectTypeModel = model; - add(new FeedbackPanel("feedback")); + add(new FeedbackPanel("feedback")); - TextField name = new TextField<>("name", LambdaModel.of(model, ProjectType::getName, ProjectType::setName)); - add(name.setRequired(true)); - add(new TextArea<>("description", LambdaModel.of(model, ProjectType::getDescription, ProjectType::setDescription))); - DropDownChoice degreeType = new DropDownChoice<>("degreeType", LambdaModel.of(model, ProjectType::getDegreeType, ProjectType::setDegreeType), Arrays.asList(DegreeType.values())); - degreeType.setRequired(true); - add(degreeType); - add(new CheckBox("reviewed", LambdaModel.of(model, ProjectType::isReviewed, ProjectType::setReviewed)).setOutputMarkupId(true)); + TextField name = new TextField<>( + "name", + LambdaModel.of(model, ProjectType::getName, ProjectType::setName) + ); + add(name.setRequired(true)); + add( + new TextArea<>( + "description", + LambdaModel.of(model, ProjectType::getDescription, ProjectType::setDescription) + ) + ); + DropDownChoice degreeType = new DropDownChoice<>( + "degreeType", + LambdaModel.of(model, ProjectType::getDegreeType, ProjectType::setDegreeType), + Arrays.asList(DegreeType.values()) + ); + degreeType.setRequired(true); + add(degreeType); + add( + new CheckBox( + "reviewed", + LambdaModel.of(model, ProjectType::isReviewed, ProjectType::setReviewed) + ).setOutputMarkupId(true) + ); IModel settings = model.map(ProjectType::getProjectTypeSettings); NumberTextField minimumOppositionsToBeGraded = new NumberTextField<>( - "minimum_oppositions_to_be_graded", - LambdaModel.of(settings, - ProjectTypeSettings::getMinOppositionsToBeGraded, - ProjectTypeSettings::setMinOppositionsToBeGraded), - Integer.class); + "minimum_oppositions_to_be_graded", + LambdaModel.of( + settings, + ProjectTypeSettings::getMinOppositionsToBeGraded, + ProjectTypeSettings::setMinOppositionsToBeGraded + ), + Integer.class + ); minimumOppositionsToBeGraded.setMinimum(0); add(minimumOppositionsToBeGraded); NumberTextField minimumActiveParticipationsToBeGraded = new NumberTextField<>( - "minimum_active_participations_to_be_graded", - LambdaModel.of(settings, - ProjectTypeSettings::getMinActiveParticipationsToBeGraded, - ProjectTypeSettings::setMinActiveParticipationsToBeGraded), - Integer.class); + "minimum_active_participations_to_be_graded", + LambdaModel.of( + settings, + ProjectTypeSettings::getMinActiveParticipationsToBeGraded, + ProjectTypeSettings::setMinActiveParticipationsToBeGraded + ), + Integer.class + ); minimumActiveParticipationsToBeGraded.setMinimum(0); add(minimumActiveParticipationsToBeGraded); NumberTextField minimumAuthors = new NumberTextField<>( - "minimum_authors", - LambdaModel.of(settings, ProjectTypeSettings::getMinAuthors, ProjectTypeSettings::setMinAuthors), - Integer.class); + "minimum_authors", + LambdaModel.of(settings, ProjectTypeSettings::getMinAuthors, ProjectTypeSettings::setMinAuthors), + Integer.class + ); minimumAuthors.setMinimum(1); minimumAuthors.setRequired(true); add(minimumAuthors); NumberTextField maximumAuthors = new NumberTextField<>( - "maximum_authors", - LambdaModel.of(settings, ProjectTypeSettings::getMaxAuthors, ProjectTypeSettings::setMaxAuthors), - Integer.class); + "maximum_authors", + LambdaModel.of(settings, ProjectTypeSettings::getMaxAuthors, ProjectTypeSettings::setMaxAuthors), + Integer.class + ); maximumAuthors.setMinimum(1); maximumAuthors.setRequired(true); add(maximumAuthors); TextField reviewProcessInformationUrl = new UrlTextField( - "review_process_information_url", - LambdaModel.of( - settings, - ProjectTypeSettings::getReviewProcessInformationUrl, - ProjectTypeSettings::setReviewProcessInformationUrl)); + "review_process_information_url", + LambdaModel.of( + settings, + ProjectTypeSettings::getReviewProcessInformationUrl, + ProjectTypeSettings::setReviewProcessInformationUrl + ) + ); add(reviewProcessInformationUrl); Button createButton = new Button("createButton") { - @Override + @Override public void onSubmit() { - if (editMode) { ProjectType pc = projectTypeService.save(projectTypeModel.getObject()); projectTypeModel.setObject(pc); @@ -110,7 +132,6 @@ public class AdminProjectTypePanel extends Panel { add(createButton); Button deleteButton = new Button("deleteButton") { - @Override public void onSubmit() { projectTypeModel.getObject().setDeleted(true); @@ -122,5 +143,4 @@ public class AdminProjectTypePanel extends Panel { deleteButton.setEnabled(editMode); } } - } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanel.java index 0996c0ee14..54b6898d86 100644 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanel.java @@ -9,7 +9,6 @@ public class AdminViewMailPanel extends Panel { public AdminViewMailPanel(String id, IModel model) { super(id, model); - add(new SmartLinkMultiLineLabel("mailContent", model.map(MailEvent::getMessageBody))); } } diff --git a/view/src/main/java/se/su/dsv/scipro/admin/panels/PeerRequestStatsPanel.java b/view/src/main/java/se/su/dsv/scipro/admin/panels/PeerRequestStatsPanel.java index f264894abf..c0fe5e2b4d 100755 --- a/view/src/main/java/se/su/dsv/scipro/admin/panels/PeerRequestStatsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/admin/panels/PeerRequestStatsPanel.java @@ -1,34 +1,31 @@ package se.su.dsv.scipro.admin.panels; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import se.su.dsv.scipro.peer.PeerRequestService; import se.su.dsv.scipro.peer.RequestStatus; -import jakarta.inject.Inject; - public class PeerRequestStatsPanel extends Panel { - @Inject - private PeerRequestService peerRequestService; - - public PeerRequestStatsPanel(String id) { - super(id); - - final long countRequests = peerRequestService.count(); - add(new Label("allRequests", String.valueOf(countRequests))); - - final long waitingRequests = peerRequestService.countByStatus(RequestStatus.WAITING); - add(new Label("waitingRequests", String.valueOf(waitingRequests))); - - final long takenRequests = peerRequestService.countByStatus(RequestStatus.TAKEN); - add(new Label("takenRequests", String.valueOf(takenRequests))); - - final long finishedRequests = peerRequestService.countByStatus(RequestStatus.FINISHED); - add(new Label("finishedRequests", String.valueOf(finishedRequests))); - - final long canceledRequests = peerRequestService.countByStatus(RequestStatus.CANCELED); - add(new Label("canceledRequests", String.valueOf(canceledRequests))); - } + @Inject + private PeerRequestService peerRequestService; + public PeerRequestStatsPanel(String id) { + super(id); + final long countRequests = peerRequestService.count(); + add(new Label("allRequests", String.valueOf(countRequests))); + + final long waitingRequests = peerRequestService.countByStatus(RequestStatus.WAITING); + add(new Label("waitingRequests", String.valueOf(waitingRequests))); + + final long takenRequests = peerRequestService.countByStatus(RequestStatus.TAKEN); + add(new Label("takenRequests", String.valueOf(takenRequests))); + + final long finishedRequests = peerRequestService.countByStatus(RequestStatus.FINISHED); + add(new Label("finishedRequests", String.valueOf(finishedRequests))); + + final long canceledRequests = peerRequestService.countByStatus(RequestStatus.CANCELED); + add(new Label("canceledRequests", String.valueOf(canceledRequests))); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanel.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanel.java index 5b87f995ee..307d7858f3 100755 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -30,19 +34,17 @@ import se.su.dsv.scipro.match.*; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - public class AdminApplicationPeriodsPanel extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(AdminApplicationPeriodsPanel.class); private final ExportableDataPanel dp; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private ApplicationPeriodFacade applicationPeriodFacade; + @Inject private ApplicationPeriodProjectTypeService applicationPeriodProjectTypeService; @@ -51,7 +53,6 @@ public class AdminApplicationPeriodsPanel extends Panel { public AdminApplicationPeriodsPanel(String id) { super(id); - feedback = new FencedFeedbackPanel("feedback", this); feedback.setOutputMarkupId(true); add(feedback); @@ -59,12 +60,14 @@ public class AdminApplicationPeriodsPanel extends Panel { modalWindowPlus = new ModalWindowPlus("dialog"); add(modalWindowPlus); - add(new Link("createLink") { - @Override - public void onClick() { - setResponsePage(new AdminEditApplicationPeriodPage(new PageParameters())); + add( + new Link("createLink") { + @Override + public void onClick() { + setResponsePage(new AdminEditApplicationPeriodPage(new PageParameters())); + } } - }); + ); GenericDataProvider provider = new GenericDataProvider<>(applicationPeriodService); provider.setSort("startDate", SortOrder.DESCENDING); dp = new ExportableDataPanel<>("dp", createColumns(), provider); @@ -74,24 +77,30 @@ public class AdminApplicationPeriodsPanel extends Panel { private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new LambdaColumn<>(Model.of("Start"), "startDate", ApplicationPeriod::getStartDate) { - @Override - public String getCssClass() { - return "text-nowrap"; + columns.add( + new LambdaColumn<>(Model.of("Start"), "startDate", ApplicationPeriod::getStartDate) { + @Override + public String getCssClass() { + return "text-nowrap"; + } } - }); - columns.add(new LambdaColumn<>(Model.of("End"), "endDate", ApplicationPeriod::getEndDate) { - @Override - public String getCssClass() { - return "text-nowrap"; + ); + columns.add( + new LambdaColumn<>(Model.of("End"), "endDate", ApplicationPeriod::getEndDate) { + @Override + public String getCssClass() { + return "text-nowrap"; + } } - }); - columns.add(new LambdaColumn<>(Model.of("Course start"), "courseStartDate", ApplicationPeriod::getCourseStartDate) { - @Override - public String getCssClass() { - return "text-nowrap"; + ); + columns.add( + new LambdaColumn<>(Model.of("Course start"), "courseStartDate", ApplicationPeriod::getCourseStartDate) { + @Override + public String getCssClass() { + return "text-nowrap"; + } } - }); + ); addTypesColumn(columns); columns.add(new LambdaColumn<>(Model.of("Name"), "name", ApplicationPeriod::getName)); addEditColumn(columns); @@ -103,138 +112,205 @@ public class AdminApplicationPeriodsPanel extends Panel { } private void addTypesColumn(List> columns) { - columns.add(new AbstractExportableColumn<>(Model.of("Types")) { - @Override - public void populateItem(Item> item, String s, IModel iModel) { - item.add(new DisplayMultiplesPanel<>(s, new ListAdapterModel<>(LambdaModel.of(iModel, ApplicationPeriod::getProjectTypes, ApplicationPeriod::setProjectTypes))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new Label(componentId, LambdaModel.of(t, ProjectType::getName, ProjectType::setName)); - } - }); - } - - @Override - public IModel getDataModel(IModel rowModel) { - StringBuilder s = new StringBuilder(); - Set projectTypes = rowModel.getObject().getProjectTypes(); - for (ProjectType projectType : projectTypes) { - s.append(projectType.getName()).append(", "); + columns.add( + new AbstractExportableColumn<>(Model.of("Types")) { + @Override + public void populateItem( + Item> item, + String s, + IModel iModel + ) { + item.add( + new DisplayMultiplesPanel<>( + s, + new ListAdapterModel<>( + LambdaModel.of( + iModel, + ApplicationPeriod::getProjectTypes, + ApplicationPeriod::setProjectTypes + ) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new Label( + componentId, + LambdaModel.of(t, ProjectType::getName, ProjectType::setName) + ); + } + } + ); + } + + @Override + public IModel getDataModel(IModel rowModel) { + StringBuilder s = new StringBuilder(); + Set projectTypes = rowModel.getObject().getProjectTypes(); + for (ProjectType projectType : projectTypes) { + s.append(projectType.getName()).append(", "); + } + return Model.of(s.toString()); } - return Model.of(s.toString()); } - }); + ); } private void addEditColumn(List> columns) { - columns.add(new ClickableIconColumn<>(Model.of("Edit"), null, ClickableIconColumn.EDIT) { - @Override - protected void onClick(IModel applicationPeriodModel, AjaxRequestTarget target) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), applicationPeriodModel.getObject().getId()); - setResponsePage(new AdminEditApplicationPeriodPage(pp)); + columns.add( + new ClickableIconColumn<>(Model.of("Edit"), null, ClickableIconColumn.EDIT) { + @Override + protected void onClick(IModel applicationPeriodModel, AjaxRequestTarget target) { + PageParameters pp = new PageParameters(); + pp.add( + PageParameterKeys.MAP.get(ApplicationPeriod.class), + applicationPeriodModel.getObject().getId() + ); + setResponsePage(new AdminEditApplicationPeriodPage(pp)); + } } - }); + ); } private void addTotalRemainingColumn(List> columns) { - columns.add(new AbstractExportableColumn<>(Model.of("Targets (total/remaining)")) { - @Override - public void populateItem(Item> item, String s, IModel iModel) { - item.add(new AddTargetLinkPanel(s, iModel)); - } + columns.add( + new AbstractExportableColumn<>(Model.of("Targets (total/remaining)")) { + @Override + public void populateItem( + Item> item, + String s, + IModel iModel + ) { + item.add(new AddTargetLinkPanel(s, iModel)); + } - @Override - public IModel getDataModel(IModel rowModel) { - ApplicationPeriod object = rowModel.getObject(); - StringBuilder s = new StringBuilder(); - Set projectTypes = object.getProjectTypes(); - for (ProjectType projectType : projectTypes) { - s.append(projectType.getName()).append(": ") + @Override + public IModel getDataModel(IModel rowModel) { + ApplicationPeriod object = rowModel.getObject(); + StringBuilder s = new StringBuilder(); + Set projectTypes = object.getProjectTypes(); + for (ProjectType projectType : projectTypes) { + s + .append(projectType.getName()) + .append(": ") .append(applicationPeriodFacade.totalTargets(object, projectType)) .append('/') .append(applicationPeriodFacade.remainingTargets(object, projectType)) .append(' '); - } + } - return Model.of(s.toString()); + return Model.of(s.toString()); + } } - }); + ); } private void addActivityPlanTemplateColumn(List> columns) { - columns.add(new AbstractExportableColumn<>(Model.of("Activity plan templates")) { - @Override - public void populateItem(Item> item, final String s, final IModel iModel) { - item.add(new ApplicationPeriodActivityPlanTemplateColumnPanel(s, iModel) { - @Override - public void onClick(AjaxRequestTarget target) { - iModel.setObject(applicationPeriodService.findOne(iModel.getObject().getId())); - modalWindowPlus.setContent(new EditApplicationPeriodActivityPlanTemplatePanel(modalWindowPlus.getContentId(), iModel)); - modalWindowPlus.setTitle("Edit activity plan templates"); - modalWindowPlus.show(target); - } - }); - } - - @Override - public IModel getDataModel(IModel rowModel) { - StringBuilder s = new StringBuilder(); - Set projectTypes = rowModel.getObject().getProjectTypes(); - for (ProjectType projectType : projectTypes) { - ApplicationPeriodProjectType applicationPeriodProjectType = - applicationPeriodProjectTypeService.findOne(rowModel.getObject(), projectType); - ActivityPlanTemplate activityPlanTemplate = applicationPeriodProjectType.getActivityPlanTemplate(); - s.append(projectType.getName()).append(": ") - .append(activityPlanTemplate != null ? activityPlanTemplate.getTitle() : "None").append(' '); + columns.add( + new AbstractExportableColumn<>(Model.of("Activity plan templates")) { + @Override + public void populateItem( + Item> item, + final String s, + final IModel iModel + ) { + item.add( + new ApplicationPeriodActivityPlanTemplateColumnPanel(s, iModel) { + @Override + public void onClick(AjaxRequestTarget target) { + iModel.setObject(applicationPeriodService.findOne(iModel.getObject().getId())); + modalWindowPlus.setContent( + new EditApplicationPeriodActivityPlanTemplatePanel( + modalWindowPlus.getContentId(), + iModel + ) + ); + modalWindowPlus.setTitle("Edit activity plan templates"); + modalWindowPlus.show(target); + } + } + ); + } + + @Override + public IModel getDataModel(IModel rowModel) { + StringBuilder s = new StringBuilder(); + Set projectTypes = rowModel.getObject().getProjectTypes(); + for (ProjectType projectType : projectTypes) { + ApplicationPeriodProjectType applicationPeriodProjectType = + applicationPeriodProjectTypeService.findOne(rowModel.getObject(), projectType); + ActivityPlanTemplate activityPlanTemplate = + applicationPeriodProjectType.getActivityPlanTemplate(); + s + .append(projectType.getName()) + .append(": ") + .append(activityPlanTemplate != null ? activityPlanTemplate.getTitle() : "None") + .append(' '); + } + return Model.of(s.toString()); } - return Model.of(s.toString()); } - }); + ); } private void addDeleteColumn(List> columns) { - columns.add(new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE, "Are you sure you want to delete this application period?") { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - try { - applicationPeriodService.delete(clicked.getObject().getId()); - info("Deleted application period"); - } catch (Exception e) { - String message = "Could not delete application period"; - error(message); - LOGGER.info(message, e); + columns.add( + new ClickableIconColumn<>( + Model.of("Delete"), + null, + ClickableIconColumn.DELETE, + "Are you sure you want to delete this application period?" + ) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + try { + applicationPeriodService.delete(clicked.getObject().getId()); + info("Deleted application period"); + } catch (Exception e) { + String message = "Could not delete application period"; + error(message); + LOGGER.info(message, e); + } + target.add(feedback); + target.add(dp); } - target.add(feedback); - target.add(dp); } - }); + ); } private void addExemptionsColumn(List> columns) { - columns.add(new AbstractExportableColumn<>(Model.of("Exemptions")) { - @Override - public void populateItem(Item> item, String componentId, final IModel model) { - item.add(new LabelAndLinkColumn<>(componentId, model, "Edit exemptions", true) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), model.getObject().getId()); - setResponsePage(AdminEditApplicationPeriodExemptionsPage.class, pp); - } + columns.add( + new AbstractExportableColumn<>(Model.of("Exemptions")) { + @Override + public void populateItem( + Item> item, + String componentId, + final IModel model + ) { + item.add( + new LabelAndLinkColumn<>(componentId, model, "Edit exemptions", true) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), model.getObject().getId()); + setResponsePage(AdminEditApplicationPeriodExemptionsPage.class, pp); + } - @Override - public String labelString() { - ApplicationPeriod object = model.getObject(); - return object.noOfExemptions() + " (" + object.noOfExemptedStudents() + " student(s)) "; - } - }); - } + @Override + public String labelString() { + ApplicationPeriod object = model.getObject(); + return ( + object.noOfExemptions() + " (" + object.noOfExemptedStudents() + " student(s)) " + ); + } + } + ); + } - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(rowModel.getObject().noOfExemptions()); + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(rowModel.getObject().noOfExemptions()); + } } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPage.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPage.java index a66f718d02..b5f468bfa8 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -31,14 +37,10 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; +public class AdminEditApplicationPeriodExemptionsPage + extends AbstractAdminMatchPage + implements MenuHighlightAdminApplicationPeriod { -public class AdminEditApplicationPeriodExemptionsPage extends AbstractAdminMatchPage implements MenuHighlightAdminApplicationPeriod { public static final String EXEMPTIONS = "exemptions"; public static final String ADD_FORM = "addForm"; public static final String AUTHOR = "author"; @@ -51,65 +53,80 @@ public class AdminEditApplicationPeriodExemptionsPage extends AbstractAdminMatch private ApplicationPeriodService applicationPeriodService; public AdminEditApplicationPeriodExemptionsPage(PageParameters pp) { - final IModel model = - new DetachableServiceModel<>(applicationPeriodService, pp.get(PageParameterKeys.MAP.get(ApplicationPeriod.class)).toLong()); + final IModel model = new DetachableServiceModel<>( + applicationPeriodService, + pp.get(PageParameterKeys.MAP.get(ApplicationPeriod.class)).toLong() + ); add(new Label("applicationPeriod", model.map(ApplicationPeriod::getName))); final IModel> exemptionsModel = model - .map(ApplicationPeriod::getApplicationPeriodExemptions) - .map(ArrayList::new) - .map(list -> { - list.sort(Comparator.comparing(ApplicationPeriodExemption::getGrantedOn).reversed()); - return list; - }); + .map(ApplicationPeriod::getApplicationPeriodExemptions) + .map(ArrayList::new) + .map(list -> { + list.sort(Comparator.comparing(ApplicationPeriodExemption::getGrantedOn).reversed()); + return list; + }); add(new AddExemptionForm(ADD_FORM, model)); - add(new ListView<>(EXEMPTIONS, exemptionsModel) { - @Override - protected void populateItem(final ListItem item) { - item.add(new UserLinkPanel("user", item.getModel().map(ApplicationPeriodExemption::getUser))); - item.add(new EnumLabel<>("type", item.getModel().map(ApplicationPeriodExemption::getType))); - item.add(new NoBreakLabel("newDate", item.getModel().map(ApplicationPeriodExemption::getEndDate))); - item.add(new MultiLineLabel("comment", item.getModel().map(ApplicationPeriodExemption::getComment))); - item.add(new UserLinkPanel("grantedBy", item.getModel().map(ApplicationPeriodExemption::getGrantedBy))); - item.add(new NoBreakLabel("grantedOn", item.getModel().map(ApplicationPeriodExemption::getGrantedOn))); + add( + new ListView<>(EXEMPTIONS, exemptionsModel) { + @Override + protected void populateItem(final ListItem item) { + item.add(new UserLinkPanel("user", item.getModel().map(ApplicationPeriodExemption::getUser))); + item.add(new EnumLabel<>("type", item.getModel().map(ApplicationPeriodExemption::getType))); + item.add(new NoBreakLabel("newDate", item.getModel().map(ApplicationPeriodExemption::getEndDate))); + item.add( + new MultiLineLabel("comment", item.getModel().map(ApplicationPeriodExemption::getComment)) + ); + item.add( + new UserLinkPanel("grantedBy", item.getModel().map(ApplicationPeriodExemption::getGrantedBy)) + ); + item.add( + new NoBreakLabel("grantedOn", item.getModel().map(ApplicationPeriodExemption::getGrantedOn)) + ); - item.add(new Link<>(DELETE, item.getModel()) { - @Override - public void onClick() { - model.getObject().removeApplicationPeriodExemption(item.getModelObject()); - applicationPeriodService.save(model.getObject()); - getSession().info(getString("deleted")); - setResponsePage(getPageClass(), getPageParameters()); - } - }); + item.add( + new Link<>(DELETE, item.getModel()) { + @Override + public void onClick() { + model.getObject().removeApplicationPeriodExemption(item.getModelObject()); + applicationPeriodService.save(model.getObject()); + getSession().info(getString("deleted")); + setResponsePage(getPageClass(), getPageParameters()); + } + } + ); + } } - }); + ); - add(new Label(EMPTY, new ResourceModel("empty")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!model.getObject().hasApplicationPeriodExemptions()); + add( + new Label(EMPTY, new ResourceModel("empty")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!model.getObject().hasApplicationPeriodExemptions()); + } } - }); + ); } private class AddExemptionForm extends Form { + public AddExemptionForm(String id, final IModel model) { super(id, model); - add(new FeedbackPanel("feedback")); final Model exemptionModel = Model.of(new ApplicationPeriodExemption()); final AuthorAutoComplete exemptedAuthor = new AuthorAutoComplete("author") { @Override - protected void action(AjaxRequestTarget target, User object) { - } + protected void action(AjaxRequestTarget target, User object) {} }; exemptedAuthor.setRequired(true); - exemptedAuthor.setModel(LambdaModel.of(exemptionModel, ApplicationPeriodExemption::getUser, ApplicationPeriodExemption::setUser)); + exemptedAuthor.setModel( + LambdaModel.of(exemptionModel, ApplicationPeriodExemption::getUser, ApplicationPeriodExemption::setUser) + ); add(exemptedAuthor); final WebMarkupContainer dateContainer = new WebMarkupContainer("dateContainer"); @@ -120,68 +137,98 @@ public class AdminEditApplicationPeriodExemptionsPage extends AbstractAdminMatch dateContainer.add(new Label("periodEnd", model.map(ApplicationPeriod::getEndDate))); dateContainer.add(new Label("courseStart", model.map(ApplicationPeriod::getCourseStartDate))); - TextField newDate = new TextField<>("endDate", LambdaModel.of(exemptionModel, ApplicationPeriodExemption::getEndDate, ApplicationPeriodExemption::setEndDate), LocalDate.class); + TextField newDate = new TextField<>( + "endDate", + LambdaModel.of( + exemptionModel, + ApplicationPeriodExemption::getEndDate, + ApplicationPeriodExemption::setEndDate + ), + LocalDate.class + ); newDate.setRequired(true); newDate.add(new BootstrapDatePicker()); dateContainer.add(newDate); final DropDownChoice exemptionType = new DropDownChoice<>( - "type", - LambdaModel.of(exemptionModel, ApplicationPeriodExemption::getType, ApplicationPeriodExemption::setType), - List.of(ApplicationPeriodExemption.Type.values()), - new EnumChoiceRenderer<>(this)); + "type", + LambdaModel.of( + exemptionModel, + ApplicationPeriodExemption::getType, + ApplicationPeriodExemption::setType + ), + List.of(ApplicationPeriodExemption.Type.values()), + new EnumChoiceRenderer<>(this) + ); exemptionType.setRequired(true); - exemptionType.add(new AjaxFormComponentUpdatingBehavior("input") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - dateContainer.setVisible(exemptionType.getConvertedInput().requiresEndDate()); - if (dateContainer.isVisible()) { - newDate.setModelObject(getModelObject().getEndDate()); + exemptionType.add( + new AjaxFormComponentUpdatingBehavior("input") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + dateContainer.setVisible(exemptionType.getConvertedInput().requiresEndDate()); + if (dateContainer.isVisible()) { + newDate.setModelObject(getModelObject().getEndDate()); + } else { + // Have to clear or there'll be an end date even when the input is hidden + newDate.setModelObject(null); + } + target.add(dateContainer); } - else { - // Have to clear or there'll be an end date even when the input is hidden - newDate.setModelObject(null); - } - target.add(dateContainer); } - }); + ); add(exemptionType); - TextArea comment = new TextArea<>(COMMENT, LambdaModel.of(exemptionModel, ApplicationPeriodExemption::getComment, ApplicationPeriodExemption::setComment)); + TextArea comment = new TextArea<>( + COMMENT, + LambdaModel.of( + exemptionModel, + ApplicationPeriodExemption::getComment, + ApplicationPeriodExemption::setComment + ) + ); add(comment); add(new UniqueValidator(exemptedAuthor, exemptionType)); - add(new Button(ADD_EXEMPTION) { - @Override - public void onSubmit() { - super.onSubmit(); - final ApplicationPeriodExemption exemption = exemptionModel.getObject(); - ApplicationPeriod applicationPeriodModel = model.getObject(); - exemption.setApplicationPeriod(applicationPeriodModel); - exemption.setGrantedBy(SciProSession.get().getUser()); - exemption.setGrantedOn(LocalDateTime.now()); - model.getObject().addApplicationPeriodExemption(exemption); - applicationPeriodService.save(model.getObject()); - exemptionModel.setObject(new ApplicationPeriodExemption()); - info(getString("added")); + add( + new Button(ADD_EXEMPTION) { + @Override + public void onSubmit() { + super.onSubmit(); + final ApplicationPeriodExemption exemption = exemptionModel.getObject(); + ApplicationPeriod applicationPeriodModel = model.getObject(); + exemption.setApplicationPeriod(applicationPeriodModel); + exemption.setGrantedBy(SciProSession.get().getUser()); + exemption.setGrantedOn(LocalDateTime.now()); + model.getObject().addApplicationPeriodExemption(exemption); + applicationPeriodService.save(model.getObject()); + exemptionModel.setObject(new ApplicationPeriodExemption()); + info(getString("added")); + } } - }); + ); } private class UniqueValidator extends AbstractFormValidator { + private final FormComponent author; private final FormComponent exemptionType; - public UniqueValidator(FormComponent author, FormComponent exemptionType) { + public UniqueValidator( + FormComponent author, + FormComponent exemptionType + ) { this.author = author; this.exemptionType = exemptionType; } @Override public void validate(Form form) { - for (ApplicationPeriodExemption ape : getModelObject().getApplicationPeriodExemptions()){ - if (ape.getUser().equals(author.getConvertedInput()) && ape.getType().equals(exemptionType.getConvertedInput())) { + for (ApplicationPeriodExemption ape : getModelObject().getApplicationPeriodExemptions()) { + if ( + ape.getUser().equals(author.getConvertedInput()) && + ape.getType().equals(exemptionType.getConvertedInput()) + ) { error(author); } } @@ -189,9 +236,8 @@ public class AdminEditApplicationPeriodExemptionsPage extends AbstractAdminMatch @Override public FormComponent[] getDependentFormComponents() { - return new FormComponent[]{author, exemptionType}; + return new FormComponent[] { author, exemptionType }; } } - } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPage.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPage.java index bbb588c1a2..2409d13d83 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPage.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.List; import org.apache.wicket.extensions.model.AbstractCheckBoxModel; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.basic.Label; @@ -23,12 +27,9 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.List; - -public class AdminEditApplicationPeriodPage extends AbstractAdminMatchPage implements MenuHighlightAdminApplicationPeriod { +public class AdminEditApplicationPeriodPage + extends AbstractAdminMatchPage + implements MenuHighlightAdminApplicationPeriod { public static final String PROJECT_TYPES = "projectTypes"; public static final String FORM = "form"; @@ -42,6 +43,7 @@ public class AdminEditApplicationPeriodPage extends AbstractAdminMatchPage imple @Inject private ProjectTypeService projectTypeService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -54,22 +56,51 @@ public class AdminEditApplicationPeriodPage extends AbstractAdminMatchPage imple public EditForm(String id, IModel model) { super(id, model); add(new ComponentFeedbackPanel("formFeedback", this)); - RequiredTextField title = new RequiredTextField<>(TITLE, LambdaModel.of(getModel(), ApplicationPeriod::getName, ApplicationPeriod::setName)); + RequiredTextField title = new RequiredTextField<>( + TITLE, + LambdaModel.of(getModel(), ApplicationPeriod::getName, ApplicationPeriod::setName) + ); add(new ComponentFeedbackPanel(TITLE_FEEDBACK, title)); add(title); - add(new ListView<>(PROJECT_TYPES, availableProjectTypes()) { - @Override - protected void populateItem(ListItem item) { - item.add(new CheckBox(CHECKBOX, new ProjectTypeSelectionModel(item.getModel())).setOutputMarkupId(true)); - item.add(new Label("name", item.getModel().map(ProjectType::getName))); + add( + new ListView<>(PROJECT_TYPES, availableProjectTypes()) { + @Override + protected void populateItem(ListItem item) { + item.add( + new CheckBox(CHECKBOX, new ProjectTypeSelectionModel(item.getModel())).setOutputMarkupId( + true + ) + ); + item.add(new Label("name", item.getModel().map(ProjectType::getName))); + } } - }); - final FormComponent startDate = addDateField(START_DATE, LambdaModel.of(getModel(), ApplicationPeriod::getStartDate, ApplicationPeriod::setStartDate)); - final FormComponent endDate = addDateField(END_DATE, LambdaModel.of(getModel(), ApplicationPeriod::getEndDate, ApplicationPeriod::setEndDate)); - final FormComponent courseStartDate = addDateField(COURSE_START_DATE, LambdaModel.of(getModel(), ApplicationPeriod::getCourseStartDate, ApplicationPeriod::setCourseStartDate)); - final FormComponent courseEndDate = addDateField("courseEndDate", LambdaModel.of(getModel(), ApplicationPeriod::getCourseEndDate, ApplicationPeriod::setCourseEndDate)); + ); + final FormComponent startDate = addDateField( + START_DATE, + LambdaModel.of(getModel(), ApplicationPeriod::getStartDate, ApplicationPeriod::setStartDate) + ); + final FormComponent endDate = addDateField( + END_DATE, + LambdaModel.of(getModel(), ApplicationPeriod::getEndDate, ApplicationPeriod::setEndDate) + ); + final FormComponent courseStartDate = addDateField( + COURSE_START_DATE, + LambdaModel.of(getModel(), ApplicationPeriod::getCourseStartDate, ApplicationPeriod::setCourseStartDate) + ); + final FormComponent courseEndDate = addDateField( + "courseEndDate", + LambdaModel.of(getModel(), ApplicationPeriod::getCourseEndDate, ApplicationPeriod::setCourseEndDate) + ); courseEndDate.setRequired(false); - final RequiredTextField courseStartTime = new RequiredTextField<>("courseStartTime", LambdaModel.of(getModel(), ApplicationPeriod::getCourseStartTime, ApplicationPeriod::setCourseStartTime), LocalTime.class); + final RequiredTextField courseStartTime = new RequiredTextField<>( + "courseStartTime", + LambdaModel.of( + getModel(), + ApplicationPeriod::getCourseStartTime, + ApplicationPeriod::setCourseStartTime + ), + LocalTime.class + ); courseStartTime.add(new BootstrapTimePicker()); add(courseStartTime); add(new FencedFeedbackPanel("courseStartTimeFeedback", courseStartTime)); @@ -110,6 +141,7 @@ public class AdminEditApplicationPeriodPage extends AbstractAdminMatchPage imple } private class ProjectTypeSelectionModel extends AbstractCheckBoxModel { + private final IModel model; public ProjectTypeSelectionModel(IModel model) { @@ -133,16 +165,18 @@ public class AdminEditApplicationPeriodPage extends AbstractAdminMatchPage imple } } - private LoadableDetachableModel getLoaded(final PageParameters pp){ + private LoadableDetachableModel getLoaded(final PageParameters pp) { return new LoadableDetachableModel<>() { @Override protected ApplicationPeriod load() { if (pp.get(PageParameterKeys.MAP.get(ApplicationPeriod.class)).isNull()) { return new ApplicationPeriod(); } else { - return applicationPeriodService.findOne(pp.get(PageParameterKeys.MAP.get(ApplicationPeriod.class)).toLong()); + return applicationPeriodService.findOne( + pp.get(PageParameterKeys.MAP.get(ApplicationPeriod.class)).toLong() + ); } } }; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPage.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPage.java index 18e80cc2c5..6e4af88c9c 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.util.*; +import java.util.stream.Collectors; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -28,10 +31,6 @@ import se.su.dsv.scipro.springdata.services.SupervisorService.FilterParams; import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.*; -import java.util.stream.Collectors; - public class AdminEditTargetsPage extends AbstractAdminMatchPage implements MenuHighlightAdminApplicationPeriod { private static final String FILTER_FORM = "filterForm"; @@ -40,12 +39,16 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu @Inject private SupervisorService supervisorService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private IdeaService ideaService; + @Inject private UnitService unitService; + @Inject private ResearchAreaService researchAreaService; @@ -55,7 +58,6 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu private Link sendMailLink; public AdminEditTargetsPage(IModel model) { - this.current = model; table = new WebMarkupContainer("table"); table.setOutputMarkupId(true); @@ -72,12 +74,13 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu return supervisorService.findAll(filter.getObject(), pageAdapter); }); - sendMailLink = new Link("sendMail"){ + sendMailLink = new Link("sendMail") { @Override protected void onConfigure() { super.onConfigure(); setVisibilityAllowed(!supervisors.getObject().isEmpty()); } + @Override public void onClick() { Set listOfUsers = new HashSet<>(supervisors.getObject()); @@ -87,63 +90,108 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu sendMailLink.setOutputMarkupPlaceholderTag(true); add(sendMailLink); final IModel> periods = LoadableDetachableModel.of(() -> { - final Collection previousPeriods = applicationPeriodService.getPreviousPeriods(model.getObject(), 2); + final Collection previousPeriods = applicationPeriodService.getPreviousPeriods( + model.getObject(), + 2 + ); final List all = new ArrayList<>(previousPeriods); all.add(0, model.getObject()); return all; }); - table.add(new ListView<>("applicationPeriodHeader", periods) { - @Override - protected void populateItem(ListItem item) { - final IModel applicationPeriod = item.getModel(); - final Label name = new Label("name", applicationPeriod.map(ApplicationPeriod::getName)); - name.add(AttributeModifier.replace("colspan", - applicationPeriod.map(ApplicationPeriod::getProjectTypes).map(Set::size))); - item.add(name); + table.add( + new ListView<>("applicationPeriodHeader", periods) { + @Override + protected void populateItem(ListItem item) { + final IModel applicationPeriod = item.getModel(); + final Label name = new Label("name", applicationPeriod.map(ApplicationPeriod::getName)); + name.add( + AttributeModifier.replace( + "colspan", + applicationPeriod.map(ApplicationPeriod::getProjectTypes).map(Set::size) + ) + ); + item.add(name); + } } - }); - table.add(new ListView<>("projectTypeHeader", periods) { - @Override - protected void populateItem(ListItem item) { - item.add(new ListView<>("projectTypes", new ListAdapterModel<>(item.getModel().map(ApplicationPeriod::getProjectTypes))) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("name", item.getModel().map(ProjectType::getName))); - } - }); - } - }); - - table.add(new ListView<>("supervisors", supervisors) { - @Override - protected void populateItem(ListItem item) { - final IModel user = item.getModel(); - item.add(new UserLabel("name", user)); - item.add(new Label("unit", user.map(User::getUnit).map(Unit::getTitle))); - item.add(new Label("researchAreas", user.map(user_ -> getGetResearchAreaNames(user_)))); - item.add(new ListView<>("applicationPeriods", periods) { - @Override - protected void populateItem(ListItem item) { - final IModel applicationPeriod = item.getModel(); - item.add(new ListView<>("projectTypes", new ListAdapterModel<>(applicationPeriod.map(ApplicationPeriod::getProjectTypes))) { + ); + table.add( + new ListView<>("projectTypeHeader", periods) { + @Override + protected void populateItem(ListItem item) { + item.add( + new ListView<>( + "projectTypes", + new ListAdapterModel<>(item.getModel().map(ApplicationPeriod::getProjectTypes)) + ) { @Override protected void populateItem(ListItem item) { - final IModel projectType = item.getModel(); - final boolean currentPeriod = applicationPeriod.getObject().equals(model.getObject()); - item.add(new EditTargetPanel("target", applicationPeriod, user, projectType, currentPeriod) { - @Override - public void update(AjaxRequestTarget ajaxTarget, User e) { - success(getString("saved", user)); - ajaxTarget.add(feedback); - } - }); - item.add(new Label("matched", () -> ideaService.countMatched(applicationPeriod.getObject(), user.getObject(), projectType.getObject()))); + item.add(new Label("name", item.getModel().map(ProjectType::getName))); } - }); - } - }); + } + ); + } } - }); + ); + + table.add( + new ListView<>("supervisors", supervisors) { + @Override + protected void populateItem(ListItem item) { + final IModel user = item.getModel(); + item.add(new UserLabel("name", user)); + item.add(new Label("unit", user.map(User::getUnit).map(Unit::getTitle))); + item.add(new Label("researchAreas", user.map(user_ -> getGetResearchAreaNames(user_)))); + item.add( + new ListView<>("applicationPeriods", periods) { + @Override + protected void populateItem(ListItem item) { + final IModel applicationPeriod = item.getModel(); + item.add( + new ListView<>( + "projectTypes", + new ListAdapterModel<>( + applicationPeriod.map(ApplicationPeriod::getProjectTypes) + ) + ) { + @Override + protected void populateItem(ListItem item) { + final IModel projectType = item.getModel(); + final boolean currentPeriod = applicationPeriod + .getObject() + .equals(model.getObject()); + item.add( + new EditTargetPanel( + "target", + applicationPeriod, + user, + projectType, + currentPeriod + ) { + @Override + public void update(AjaxRequestTarget ajaxTarget, User e) { + success(getString("saved", user)); + ajaxTarget.add(feedback); + } + } + ); + item.add( + new Label("matched", () -> + ideaService.countMatched( + applicationPeriod.getObject(), + user.getObject(), + projectType.getObject() + ) + ) + ); + } + } + ); + } + } + ); + } + } + ); } private void addFeedback() { @@ -167,49 +215,76 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu } private String getGetResearchAreaNames(User user) { - return user.getResearchAreas() - .stream() - .map(ResearchArea::getTitle) - .collect(Collectors.joining(", ")); + return user.getResearchAreas().stream().map(ResearchArea::getTitle).collect(Collectors.joining(", ")); } private class FilterForm extends Form { + public FilterForm(String id, final IModel model) { super(id, model); - add(new AjaxCheckBoxMultipleChoice<>("languages", LambdaModel.of(model, FilterParams::getLanguages, FilterParams::setLanguages), Arrays.asList(Language.values()), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(table, sendMailLink); + add( + new AjaxCheckBoxMultipleChoice<>( + "languages", + LambdaModel.of(model, FilterParams::getLanguages, FilterParams::setLanguages), + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(table, sendMailLink); + } } - }); - add(new AjaxDropDownChoice<>("unit", LambdaModel.of(model, FilterParams::getUnit, FilterParams::setUnit), unitService.findAll(), new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, Unit objectSelected) { - target.add(table, sendMailLink); + ); + add( + new AjaxDropDownChoice<>( + "unit", + LambdaModel.of(model, FilterParams::getUnit, FilterParams::setUnit), + unitService.findAll(), + new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, Unit objectSelected) { + target.add(table, sendMailLink); + } + }.setNullValid(true) + ); + add( + new AjaxDropDownChoice<>( + "researchArea", + LambdaModel.of(model, FilterParams::getResearchArea, FilterParams::setResearchArea), + researchAreaService.findNotDeleted(), + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { + target.add(table, sendMailLink); + } + }.setNullValid(true) + ); + add( + new EmployeeAutoComplete( + "supervisor", + LambdaModel.of(model, FilterParams::getSupervisor, FilterParams::setSupervisor) + ) { + @Override + protected void action(AjaxRequestTarget target, User object) { + target.add(table, sendMailLink); + } } - }.setNullValid(true)); - add(new AjaxDropDownChoice<>("researchArea", LambdaModel.of(model, FilterParams::getResearchArea, FilterParams::setResearchArea), researchAreaService.findNotDeleted(), new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { - target.add(table, sendMailLink); + ); + add( + new AjaxCheckBox("hasTargetsInApplicationPeriod", new TargetCheckBoxModel(model)) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(table, sendMailLink); + } } - }.setNullValid(true)); - add(new EmployeeAutoComplete("supervisor", LambdaModel.of(model, FilterParams::getSupervisor, FilterParams::setSupervisor)) { - @Override - protected void action(AjaxRequestTarget target, User object) { - target.add(table, sendMailLink); - } - }); - add(new AjaxCheckBox("hasTargetsInApplicationPeriod", new TargetCheckBoxModel(model)) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(table, sendMailLink); - } - }); + ); } } private class TargetCheckBoxModel extends AbstractCheckBoxModel { + private IModel filter; TargetCheckBoxModel(IModel filter) { @@ -218,7 +293,7 @@ public class AdminEditTargetsPage extends AbstractAdminMatchPage implements Menu @Override public boolean isSelected() { - return filter.getObject().getHasTargetsInApplicationPeriod() != null; + return (filter.getObject().getHasTargetsInApplicationPeriod() != null); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanel.java index c73b21edb9..461d938f53 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.util.ArrayList; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.basic.Label; @@ -12,10 +14,8 @@ import se.su.dsv.scipro.match.ApplicationPeriodProjectType; import se.su.dsv.scipro.match.ApplicationPeriodProjectTypeService; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.util.ArrayList; - public abstract class ApplicationPeriodActivityPlanTemplateColumnPanel extends Panel { + public static final String LIST = "list"; public static final String PC = "pc"; public static final String TEMPLATE = "template"; @@ -34,16 +34,28 @@ public abstract class ApplicationPeriodActivityPlanTemplateColumnPanel extends P @Override protected void populateItem(ListItem item) { item.add(new Label(PC, item.getModelObject().getName())); - ApplicationPeriodProjectType applicationPeriodProjectType = applicationPeriodProjectTypeService.findOne(model.getObject(), item.getModelObject()); - item.add(new Label(TEMPLATE, applicationPeriodProjectType.getActivityPlanTemplate() != null ? applicationPeriodProjectType.getActivityPlanTemplate().getTitle() : "None")); + ApplicationPeriodProjectType applicationPeriodProjectType = applicationPeriodProjectTypeService.findOne( + model.getObject(), + item.getModelObject() + ); + item.add( + new Label( + TEMPLATE, + applicationPeriodProjectType.getActivityPlanTemplate() != null + ? applicationPeriodProjectType.getActivityPlanTemplate().getTitle() + : "None" + ) + ); } }; add(list); - add(new AjaxLink(LINK) { - @Override - public void onClick(AjaxRequestTarget target) { - ApplicationPeriodActivityPlanTemplateColumnPanel.this.onClick(target); + add( + new AjaxLink(LINK) { + @Override + public void onClick(AjaxRequestTarget target) { + ApplicationPeriodActivityPlanTemplateColumnPanel.this.onClick(target); + } } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanel.java index cca7dad8b3..7dfa15c1cc 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanel.java @@ -10,6 +10,7 @@ import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.system.ProjectType; public class ApplicationPeriodInfoPanel extends Panel { + static final String PROJECT_TYPES = "projectTypes"; static final String START_DATE = "startDate"; static final String END_DATE = "endDate"; @@ -20,12 +21,17 @@ public class ApplicationPeriodInfoPanel extends Panel { super(id, applicationPeriod); add(new Label(NAME, applicationPeriod.map(ApplicationPeriod::getName))); - add(new ListView<>(PROJECT_TYPES, new ListAdapterModel<>(applicationPeriod.map(ApplicationPeriod::getProjectTypes))) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(NAME, item.getModel().map(ProjectType::getName))); + add( + new ListView<>( + PROJECT_TYPES, + new ListAdapterModel<>(applicationPeriod.map(ApplicationPeriod::getProjectTypes)) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(NAME, item.getModel().map(ProjectType::getName))); + } } - }); + ); add(new Label(START_DATE, applicationPeriod.map(ApplicationPeriod::getStartDate))); add(new Label(END_DATE, applicationPeriod.map(ApplicationPeriod::getEndDate))); diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanel.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanel.java index 480c6e1a1d..fa9024caee 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -13,14 +16,11 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class ApplicationPeriodSupervisorPanel extends Panel { @Inject private IdeaService ideaService; + @Inject private TargetService targetService; @@ -35,31 +35,42 @@ public class ApplicationPeriodSupervisorPanel extends Panel { public ApplicationPeriodSupervisorPanel(String id, final IModel model) { super(id, model); - this.model = model; employee = SciProSession.get().getUser(); List projectTypes = new ArrayList<>(model.getObject().getProjectTypes()); - add(new ListView<>(LIST, projectTypes) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(PROJECT_TYPE, item.getModel().map(ProjectType::getName))); - item.add(new Label(TARGET, Integer.toString(getTarget(item.getModelObject())))); - item.add(new Label(CURRENT, Long.toString(getCurrent(item.getModelObject())))); + add( + new ListView<>(LIST, projectTypes) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(PROJECT_TYPE, item.getModel().map(ProjectType::getName))); + item.add(new Label(TARGET, Integer.toString(getTarget(item.getModelObject())))); + item.add(new Label(CURRENT, Long.toString(getCurrent(item.getModelObject())))); - final int ideasLeftToCreateToMeetTarget = targetService.ideasLeftToCreateToMeetTarget(model.getObject(), employee, item.getModelObject()); + final int ideasLeftToCreateToMeetTarget = targetService.ideasLeftToCreateToMeetTarget( + model.getObject(), + employee, + item.getModelObject() + ); - - item.add(new Label(INFO, new StringResourceModel("info", this, item.getModel()).setParameters(ideasLeftToCreateToMeetTarget)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(ideasLeftToCreateToMeetTarget > 0); - } - }); + item.add( + new Label( + INFO, + new StringResourceModel("info", this, item.getModel()).setParameters( + ideasLeftToCreateToMeetTarget + ) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(ideasLeftToCreateToMeetTarget > 0); + } + } + ); + } } - }); + ); } private int getTarget(ProjectType pc) { diff --git a/view/src/main/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanel.java index 56b71bcd45..bb25245768 100644 --- a/view/src/main/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.applicationperiod; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; @@ -18,10 +20,8 @@ import se.su.dsv.scipro.match.ApplicationPeriodProjectType; import se.su.dsv.scipro.match.ApplicationPeriodService; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.util.List; - public class EditApplicationPeriodActivityPlanTemplatePanel extends Panel { + public static final String LIST = "list"; public static final String PC = "pc"; public static final String DROPDOWN = "dropdown"; @@ -29,6 +29,7 @@ public class EditApplicationPeriodActivityPlanTemplatePanel extends Panel { @Inject private ActivityPlanTemplateService activityPlanTemplateService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -40,17 +41,30 @@ public class EditApplicationPeriodActivityPlanTemplatePanel extends Panel { } protected class EditForm extends Form { + public EditForm(String id, IModel model) { super(id, model); list = new ListView<>(LIST, getProjectTypes(model)) { @Override protected void populateItem(ListItem item) { - item.add(new Label(PC, item.getModel().map(ApplicationPeriodProjectType::getProjectType).map(ProjectType::getName))); - item.add(new DropDownChoice<>(DROPDOWN, - LambdaModel.of(item.getModel(), ApplicationPeriodProjectType::getActivityPlanTemplate, ApplicationPeriodProjectType::setActivityPlanTemplate), + item.add( + new Label( + PC, + item.getModel().map(ApplicationPeriodProjectType::getProjectType).map(ProjectType::getName) + ) + ); + item.add( + new DropDownChoice<>( + DROPDOWN, + LambdaModel.of( + item.getModel(), + ApplicationPeriodProjectType::getActivityPlanTemplate, + ApplicationPeriodProjectType::setActivityPlanTemplate + ), new ListAdapterModel<>(getTemplates()), - new LambdaChoiceRenderer<>(ActivityPlanTemplate::getTitle, ActivityPlanTemplate::getId)) - .setNullValid(true)); + new LambdaChoiceRenderer<>(ActivityPlanTemplate::getTitle, ActivityPlanTemplate::getId) + ).setNullValid(true) + ); } }; add(list); @@ -70,9 +84,9 @@ public class EditApplicationPeriodActivityPlanTemplatePanel extends Panel { } @Override - protected void onSubmit(){ + protected void onSubmit() { applicationPeriodService.save(getModelObject()); success(getString("saved")); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/BasePage.java b/view/src/main/java/se/su/dsv/scipro/basepages/BasePage.java index 832fcaa82d..1b7275afff 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/BasePage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/BasePage.java @@ -14,38 +14,52 @@ import se.su.dsv.scipro.basepanels.SystemNoticePanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(requiresLoggedInUser = true, authorizedRoles = {Roles.AUTHOR, Roles.ADMIN, Roles.SUPERVISOR, Roles.SYSADMIN}) +@Authorization( + requiresLoggedInUser = true, + authorizedRoles = { Roles.AUTHOR, Roles.ADMIN, Roles.SUPERVISOR, Roles.SYSADMIN } +) public abstract class BasePage extends WebPage implements IAjaxIndicatorAware { - - public BasePage(){ - super(); - } - - public BasePage(PageParameters pp){ - super(pp); - } + + public BasePage() { + super(); + } + + public BasePage(PageParameters pp) { + super(pp); + } @Override - protected void onInitialize(){ + protected void onInitialize() { super.onInitialize(); - add(new SystemNoticePanel("systemNotice")); - } + add(new SystemNoticePanel("systemNotice")); + } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(CssHeaderItem.forReference(new WebjarsJavaScriptResourceReference("bootstrap/current/css/bootstrap.min.css"))); - response.render(CssHeaderItem.forReference(new ContextRelativeResourceReference("css/scipro_m.css", false))); - response.render(JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings() - .getJQueryReference())); - response.render(JavaScriptHeaderItem.forReference(new ContextRelativeResourceReference("js/scroll-sneak.js", false))); + response.render( + CssHeaderItem.forReference( + new WebjarsJavaScriptResourceReference("bootstrap/current/css/bootstrap.min.css") + ) + ); + response.render(CssHeaderItem.forReference(new ContextRelativeResourceReference("css/scipro_m.css", false))); + response.render( + JavaScriptHeaderItem.forReference(getApplication().getJavaScriptLibrarySettings().getJQueryReference()) + ); + response.render( + JavaScriptHeaderItem.forReference(new ContextRelativeResourceReference("js/scroll-sneak.js", false)) + ); response.render(JavaScriptHeaderItem.forReference(new ContextRelativeResourceReference("js/scipro.js", false))); - response.render(JavaScriptHeaderItem.forReference(new WebjarsJavaScriptResourceReference("bootstrap/current/js/bootstrap.bundle.min.js"))); - } + response.render( + JavaScriptHeaderItem.forReference( + new WebjarsJavaScriptResourceReference("bootstrap/current/js/bootstrap.bundle.min.js") + ) + ); + } @Override - public String getAjaxIndicatorMarkupId() { - return "ajax-loader"; - } -} \ No newline at end of file + public String getAjaxIndicatorMarkupId() { + return "ajax-loader"; + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/MenuPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/MenuPage.java index 4e42ec4c79..9dfc487d4b 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/MenuPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/MenuPage.java @@ -9,29 +9,30 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; public abstract class MenuPage extends BasePage { + private Component headerPanel; - public MenuPage(){ - super(); - setUp(); - } - - public MenuPage(PageParameters pp){ - super(pp); - setUp(); - } - - private void setUp(){ + public MenuPage() { + super(); + setUp(); + } + + public MenuPage(PageParameters pp) { + super(pp); + setUp(); + } + + private void setUp() { headerPanel = new HeaderPanel("headerPanel", this.getClass()); add(headerPanel); headerPanel.setOutputMarkupId(true); - FooterPanel footerPanel = new FooterPanel("footerPanel"); - add(footerPanel); - } + FooterPanel footerPanel = new FooterPanel("footerPanel"); + add(footerPanel); + } protected User loggedInUser() { - return SciProSession.get().getUser(); - } + return SciProSession.get().getUser(); + } public void updateHeader(AjaxRequestTarget target) { target.add(headerPanel); diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/PublicPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/PublicPage.java index 1ee1764672..183c4142dc 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/PublicPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/PublicPage.java @@ -4,6 +4,6 @@ import se.su.dsv.scipro.security.auth.Authorization; @Authorization(requiresLoggedInUser = false) public class PublicPage extends BasePage { - protected PublicPage() { - } + + protected PublicPage() {} } diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPage.java index ba8455ab32..0701a2483a 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPage.java @@ -3,7 +3,8 @@ package se.su.dsv.scipro.basepages.errorpages; import static java.net.HttpURLConnection.HTTP_FORBIDDEN; public class AccessDeniedPage extends AbstractErrorPage { - public AccessDeniedPage(){ - super(HTTP_FORBIDDEN); - } + + public AccessDeniedPage() { + super(HTTP_FORBIDDEN); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPage.java index 0ab9dfc251..8fc7d37519 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPage.java @@ -3,7 +3,8 @@ package se.su.dsv.scipro.basepages.errorpages; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; public class InternalErrorPage extends AbstractErrorPage { - public InternalErrorPage() { - super(HTTP_INTERNAL_ERROR); - } + + public InternalErrorPage() { + super(HTTP_INTERNAL_ERROR); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPage.java index ef755229e5..87b43e3a24 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPage.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.basepages.errorpages; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; public class NotFoundPage extends AbstractErrorPage { + public NotFoundPage() { super(HTTP_NOT_FOUND); } diff --git a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPage.java b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPage.java index 4e8dd8c282..7bec75731d 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPage.java +++ b/view/src/main/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPage.java @@ -3,7 +3,8 @@ package se.su.dsv.scipro.basepages.errorpages; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; public class PageExpiredPage extends AbstractErrorPage { - public PageExpiredPage(){ - super(HTTP_INTERNAL_ERROR); - } + + public PageExpiredPage() { + super(HTTP_INTERNAL_ERROR); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/basepanels/FooterPanel.java b/view/src/main/java/se/su/dsv/scipro/basepanels/FooterPanel.java index fdd554dc11..642dd88f91 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepanels/FooterPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/basepanels/FooterPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.basepanels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; @@ -12,18 +14,16 @@ import org.apache.wicket.model.LoadableDetachableModel; import se.su.dsv.scipro.components.AutoHidingListView; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.List; - public class FooterPanel extends Panel { + @Inject private FooterLinkService footerLinkService; + @Inject private FooterAddressRepo footerAddressRepo; public FooterPanel(String id) { super(id); - add(new FooterLinks("first", FooterColumn.FIRST)); add(new FooterLinks("second", FooterColumn.SECOND)); add(new FooterLinks("third", FooterColumn.THIRD)); @@ -35,7 +35,6 @@ public class FooterPanel extends Panel { public FooterAddressPart(String id) { super(id, "footerAddress", FooterPanel.this); - final IModel footerAddress = new LoadableDetachableModel<>() { @Override protected FooterAddress load() { @@ -45,8 +44,15 @@ public class FooterPanel extends Panel { }; WebMarkupContainer wmc = new WebMarkupContainer("addresses"); wmc.setOutputMarkupId(true); - wmc.add(new Label("title", LambdaModel.of(footerAddress, FooterAddress::getTitle, FooterAddress::setTitle))); - wmc.add(new Label("address", LambdaModel.of(footerAddress, FooterAddress::getAddress, FooterAddress::setAddress))); + wmc.add( + new Label("title", LambdaModel.of(footerAddress, FooterAddress::getTitle, FooterAddress::setTitle)) + ); + wmc.add( + new Label( + "address", + LambdaModel.of(footerAddress, FooterAddress::getAddress, FooterAddress::setAddress) + ) + ); add(wmc); } } @@ -55,21 +61,26 @@ public class FooterPanel extends Panel { public FooterLinks(final String id, final FooterColumn column) { super(id, "footerLinks", FooterPanel.this); - final IModel> links = new LoadableDetachableModel<>() { @Override protected List load() { return footerLinkService.getLinks(column); } }; - add(new AutoHidingListView<>("links", links) { - @Override - protected void populateItem(final ListItem item) { - item.add(new ExternalLink("link", - LambdaModel.of(item.getModel(), FooterLink::getUrl, FooterLink::setUrl), - LambdaModel.of(item.getModel(), FooterLink::getTitle, FooterLink::setTitle))); + add( + new AutoHidingListView<>("links", links) { + @Override + protected void populateItem(final ListItem item) { + item.add( + new ExternalLink( + "link", + LambdaModel.of(item.getModel(), FooterLink::getUrl, FooterLink::setUrl), + LambdaModel.of(item.getModel(), FooterLink::getTitle, FooterLink::setTitle) + ) + ); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/basepanels/HeaderPanel.java b/view/src/main/java/se/su/dsv/scipro/basepanels/HeaderPanel.java index ae893f1a4f..f3eca3eba2 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepanels/HeaderPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/basepanels/HeaderPanel.java @@ -15,10 +15,10 @@ import se.su.dsv.scipro.system.User; public class HeaderPanel extends Panel { - public HeaderPanel(String id, Class containerClass) { - super(id); - add(new BookmarkablePageLink("homeLink", getApplication().getHomePage())); - add(new RolesMenuPanel("mainMenuPanel", containerClass)); + public HeaderPanel(String id, Class containerClass) { + super(id); + add(new BookmarkablePageLink("homeLink", getApplication().getHomePage())); + add(new RolesMenuPanel("mainMenuPanel", containerClass)); add(new BookmarkablePageLink<>("notes", NotesPage.class)); final IModel currentUser = new LoadableDetachableModel<>() { @Override @@ -30,15 +30,17 @@ public class HeaderPanel extends Panel { add(new UserProfileImage("picture", currentUser, UserProfileImage.Size.TINY)); add(new NotificationsMenuPanel("notificationsMenuPanel")); add(new BookmarkablePageLink("editProfile", BasicProfilePage.class)); - add(new BookmarkablePageLink("logOut", LogoutPage.class) { - @Override - protected void onConfigure() { - super.onConfigure(); - User user = currentUser.getObject(); - // How the fuck is user null here? Why doesn't Wicket's authorization work? - setVisible(user != null && user.getIdentifier() == null); + add( + new BookmarkablePageLink("logOut", LogoutPage.class) { + @Override + protected void onConfigure() { + super.onConfigure(); + User user = currentUser.getObject(); + // How the fuck is user null here? Why doesn't Wicket's authorization work? + setVisible(user != null && user.getIdentifier() == null); + } } - }); + ); setOutputMarkupPlaceholderTag(true); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/basepanels/NotificationsMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/basepanels/NotificationsMenuPanel.java index ce3a95f5b7..1deabf1acc 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepanels/NotificationsMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/basepanels/NotificationsMenuPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.basepanels; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.Panel; @@ -9,9 +10,8 @@ import se.su.dsv.scipro.notifications.NotificationService; import se.su.dsv.scipro.notifications.pages.NotificationsPage; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class NotificationsMenuPanel extends Panel { + @Inject private NotificationService notificationService; diff --git a/view/src/main/java/se/su/dsv/scipro/basepanels/RolesMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/basepanels/RolesMenuPanel.java index 5b00f2533d..23e4927557 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepanels/RolesMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/basepanels/RolesMenuPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.basepanels; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -17,14 +19,10 @@ import se.su.dsv.scipro.reviewer.ReviewerStartPage; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorPage; import se.su.dsv.scipro.supervisor.pages.SupervisorStartPage; -import java.util.ArrayList; -import java.util.List; - public class RolesMenuPanel extends Panel { private final Class containerClass; - public RolesMenuPanel(String id, Class containerClass) { super(id); this.containerClass = containerClass; @@ -35,7 +33,10 @@ public class RolesMenuPanel extends Panel { final ListView rolesListView = new ListView<>("rolesList", getItemList()) { @Override protected void populateItem(ListItem item) { - BookmarkablePageLink roleItem = new BookmarkablePageLink<>("roleItem", item.getModelObject().getTargetClass()); + BookmarkablePageLink roleItem = new BookmarkablePageLink<>( + "roleItem", + item.getModelObject().getTargetClass() + ); roleItem.add(new Label("linkText", item.getModelObject().getName())); item.add(roleItem); } @@ -74,6 +75,7 @@ public class RolesMenuPanel extends Panel { } protected static class MenuItem implements IClusterable { + private String name; private Class targetClass; @@ -90,4 +92,4 @@ public class RolesMenuPanel extends Panel { return targetClass; } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/basepanels/SystemNoticePanel.java b/view/src/main/java/se/su/dsv/scipro/basepanels/SystemNoticePanel.java index d45f551337..ceced3defa 100755 --- a/view/src/main/java/se/su/dsv/scipro/basepanels/SystemNoticePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/basepanels/SystemNoticePanel.java @@ -6,12 +6,10 @@ import org.apache.wicket.markup.html.panel.Panel; public class SystemNoticePanel extends Panel { - public static final MetaDataKey SYSTEM_NOTICE = new MetaDataKey<>() { - }; - - public SystemNoticePanel(String id) { - super(id); + public static final MetaDataKey SYSTEM_NOTICE = new MetaDataKey<>() {}; + public SystemNoticePanel(String id) { + super(id); add(new Label("systemNotice", () -> getApplication().getMetaData(SYSTEM_NOTICE))); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/AdminChecklistPage.java b/view/src/main/java/se/su/dsv/scipro/checklists/AdminChecklistPage.java index 60feae319c..6f13ac745a 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/AdminChecklistPage.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/AdminChecklistPage.java @@ -5,10 +5,10 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminChecklist; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.SYSADMIN, Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN, Roles.ADMIN }) public class AdminChecklistPage extends AbstractAdminProjectPage implements MenuHighlightAdminChecklist { public AdminChecklistPage() { - add(new ChecklistTemplateDataPanel("datapanel")); + add(new ChecklistTemplateDataPanel("datapanel")); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePage.java b/view/src/main/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePage.java index c02e81f30f..4b597d35df 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePage.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxButton; @@ -30,10 +33,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage implements MenuHighlightAdminChecklist { public static final String FEEDBACK = "feedback"; @@ -45,8 +44,10 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp @Inject private ChecklistCategoryRepo checklistCategoryRepo; + @Inject private ProjectTypeService projectTypeService; + @Inject private ChecklistTemplateService checklistTemplateService; @@ -54,10 +55,12 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp add(new FencedFeedbackPanel(FEEDBACK, this)); final IModel model = new DetachableServiceModel<>(checklistTemplateService); - if (pp.get(PageParameterKeys.MAP.get(ChecklistTemplate.class)).isNull()){ + if (pp.get(PageParameterKeys.MAP.get(ChecklistTemplate.class)).isNull()) { model.setObject(new ChecklistTemplate()); } else { - model.setObject(checklistTemplateService.findOne(pp.get(PageParameterKeys.MAP.get(ChecklistTemplate.class)).toLong())); + model.setObject( + checklistTemplateService.findOne(pp.get(PageParameterKeys.MAP.get(ChecklistTemplate.class)).toLong()) + ); } add(new EditForm(FORM, model)); @@ -70,18 +73,39 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp public EditForm(String id, final IModel model) { super(id, model); - questionList.addAll(getModelObject().getQuestions()); - RequiredTextField title = new RequiredTextField<>(TITLE, LambdaModel.of(getModel(), ChecklistTemplate::getName, ChecklistTemplate::setName)); + RequiredTextField title = new RequiredTextField<>( + TITLE, + LambdaModel.of(getModel(), ChecklistTemplate::getName, ChecklistTemplate::setName) + ); title.add(StringValidator.minimumLength(ChecklistTemplate.MIN_TITLE_LENGTH)); add(title); - add(new TextArea<>(DESCRIPTION, LambdaModel.of(model, ChecklistTemplate::getDescription, ChecklistTemplate::setDescription))); + add( + new TextArea<>( + DESCRIPTION, + LambdaModel.of(model, ChecklistTemplate::getDescription, ChecklistTemplate::setDescription) + ) + ); - add(new BootstrapCheckBoxMultipleChoice<>(CATEGORIES, LambdaModel.of(model, ChecklistTemplate::getCategories, ChecklistTemplate::setCategories), checklistCategoryRepo.findAll(), new LambdaChoiceRenderer<>(ChecklistCategory::getCategoryName, ChecklistCategory::getId))); + add( + new BootstrapCheckBoxMultipleChoice<>( + CATEGORIES, + LambdaModel.of(model, ChecklistTemplate::getCategories, ChecklistTemplate::setCategories), + checklistCategoryRepo.findAll(), + new LambdaChoiceRenderer<>(ChecklistCategory::getCategoryName, ChecklistCategory::getId) + ) + ); - add(new BootstrapCheckBoxMultipleChoice<>(PROJECT_TYPES, LambdaModel.of(model, ChecklistTemplate::getProjectTypes, ChecklistTemplate::setProjectTypes), getRelevantProjectTypes(), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId))); + add( + new BootstrapCheckBoxMultipleChoice<>( + PROJECT_TYPES, + LambdaModel.of(model, ChecklistTemplate::getProjectTypes, ChecklistTemplate::setProjectTypes), + getRelevantProjectTypes(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) + ); wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); @@ -89,49 +113,58 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp wmc.add(new NewQuestionForm("newQuestionForm")); - wmc.add(new ListView<>("questions", questionList) { - @Override - protected void populateItem(final ListItem item) { + wmc.add( + new ListView<>("questions", questionList) { + @Override + protected void populateItem(final ListItem item) { + item.add( + new AjaxLink("up") { + @Override + public void onClick(AjaxRequestTarget target) { + swapQuestions(item.getIndex(), item.getIndex() - 1); + target.add(wmc); + } - item.add(new AjaxLink("up") { - @Override - public void onClick(AjaxRequestTarget target) { - swapQuestions(item.getIndex(), item.getIndex()-1); - target.add(wmc); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(item.getIndex()!=0); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(item.getIndex() != 0); + } + } + ); - item.add(new AjaxLink("down") { - @Override - public void onClick(AjaxRequestTarget target) { - swapQuestions(item.getIndex(), item.getIndex()+1); - target.add(wmc); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(item.getIndex()!=(getList().size()-1)); - } - }); + item.add( + new AjaxLink("down") { + @Override + public void onClick(AjaxRequestTarget target) { + swapQuestions(item.getIndex(), item.getIndex() + 1); + target.add(wmc); + } - item.add(new EditQuestionForm("edit", item.getModel())); - item.add(new AjaxLink("delete") { - @Override - public void onClick(AjaxRequestTarget target) { - questionList.remove(item.getModelObject()); - target.add(wmc); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(item.getIndex() != (getList().size() - 1)); + } + } + ); + + item.add(new EditQuestionForm("edit", item.getModel())); + item.add( + new AjaxLink("delete") { + @Override + public void onClick(AjaxRequestTarget target) { + questionList.remove(item.getModelObject()); + target.add(wmc); + } + } + ); + } } - }); + ); } - private void swapQuestions(int index1, int index2){ + private void swapQuestions(int index1, int index2) { String s1 = questionList.get(index1); String s2 = questionList.get(index2); @@ -155,10 +188,10 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp template.clearQuestions(); template.setQuestions(questionList); - if (template.getCreator()==null){ + if (template.getCreator() == null) { template.setCreator(SciProSession.get().getUser()); } - if (template.getTemplateNumber() == ChecklistTemplate.DEFAULT_TEMPLATE_NUMBER){ + if (template.getTemplateNumber() == ChecklistTemplate.DEFAULT_TEMPLATE_NUMBER) { template.setTemplateNumber(SciProUtilities.safeLongToInt(checklistTemplateService.count())); } setModelObject(checklistTemplateService.save(EditForm.this.getModelObject())); @@ -171,21 +204,23 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp } private class NewQuestionForm extends Form { + public NewQuestionForm(String id) { super(id); final TextField newQuestion = new TextField<>("newQuestion", Model.of("")); add(newQuestion); - add(new AjaxButton("addNewQuestion") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - questionList.add(newQuestion.getModelObject()); - newQuestion.setModelObject(""); - target.add(wmc); + add( + new AjaxButton("addNewQuestion") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + questionList.add(newQuestion.getModelObject()); + newQuestion.setModelObject(""); + target.add(wmc); + } } - }); + ); } } - } private static class EditQuestionForm extends Form { @@ -194,52 +229,61 @@ public class AdminEditChecklistTemplatePage extends AbstractAdminProjectPage imp public EditQuestionForm(String id, IModel model) { super(id, model); - final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); add(wmc); - wmc.add(new Label("questionLabel", getModel()){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!editMode); + wmc.add( + new Label("questionLabel", getModel()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!editMode); + } } - }); + ); - wmc.add(new AjaxLink("edit") { - @Override - public void onClick(AjaxRequestTarget target) { - editMode = !editMode; - target.add(wmc); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!editMode); - } - }); + wmc.add( + new AjaxLink("edit") { + @Override + public void onClick(AjaxRequestTarget target) { + editMode = !editMode; + target.add(wmc); + } - wmc.add(new TextField<>("questionField", getModel()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(editMode); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!editMode); + } } - }); + ); - wmc.add(new AjaxButton("doEdit") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - editMode = !editMode; - target.add(wmc); + wmc.add( + new TextField<>("questionField", getModel()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(editMode); + } } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(editMode); + ); + + wmc.add( + new AjaxButton("doEdit") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + editMode = !editMode; + target.add(wmc); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(editMode); + } } - }); + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/AnswerPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/AnswerPanel.java index a300022d1b..47cd8b60dd 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/AnswerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/AnswerPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.checklists; +import java.util.EnumMap; +import java.util.Map; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.image.ContextImage; @@ -13,9 +15,6 @@ import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import java.util.EnumMap; -import java.util.Map; - public abstract class AnswerPanel extends Panel { public abstract void hook(); @@ -50,12 +49,14 @@ public abstract class AnswerPanel extends Panel { final AjaxLink answerLink = new AjaxLink<>("answerLink", answer) { @Override public void onClick(AjaxRequestTarget target) { - dialog.setContent(new EditAnswerPanel(dialog.getContentId(), question, answer) { - @Override - public void submitHook() { - hook(); + dialog.setContent( + new EditAnswerPanel(dialog.getContentId(), question, answer) { + @Override + public void submitHook() { + hook(); + } } - }); + ); dialog.show(target); } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanel.java index 4720259fca..aa890618d4 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.checklists; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -11,8 +12,6 @@ import se.su.dsv.scipro.checklist.ChecklistAnswer; import se.su.dsv.scipro.checklist.ChecklistQuestion; import se.su.dsv.scipro.profile.UserLabel; -import java.util.List; - public class ChecklistAnswerCommentPanel extends Panel { static final String TABLE = "table"; @@ -22,8 +21,11 @@ public class ChecklistAnswerCommentPanel extends Panel { public ChecklistAnswerCommentPanel(String id, IModel question) { super(id, question); - - final IModel> answers = LambdaModel.of(question, ChecklistQuestion::getAnswers, ChecklistQuestion::setAnswers); + final IModel> answers = LambdaModel.of( + question, + ChecklistQuestion::getAnswers, + ChecklistQuestion::setAnswers + ); WebMarkupContainer table = new WebMarkupContainer(TABLE) { @Override protected void onConfigure() { @@ -32,14 +34,16 @@ public class ChecklistAnswerCommentPanel extends Panel { } }; - table.add(new ListView<>(ANSWERS, answers) { - @Override - protected void populateItem(final ListItem item) { - item.add(new UserLabel(NAME, item.getModel().map(ChecklistAnswer::getUser))); - item.add(new Label(COMMENT, item.getModel().map(ChecklistAnswer::getComment))); - item.setVisibilityAllowed(hasComment(item)); + table.add( + new ListView<>(ANSWERS, answers) { + @Override + protected void populateItem(final ListItem item) { + item.add(new UserLabel(NAME, item.getModel().map(ChecklistAnswer::getUser))); + item.add(new Label(COMMENT, item.getModel().map(ChecklistAnswer::getComment))); + item.setVisibilityAllowed(hasComment(item)); + } } - }); + ); add(table); } @@ -48,5 +52,4 @@ public class ChecklistAnswerCommentPanel extends Panel { String comment = item.getModelObject().getComment(); return comment != null && !comment.isEmpty(); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanel.java index 250d82e7e7..3fab1fc4c8 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -13,12 +18,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.system.ProjectModule; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - @ProjectModuleComponent(ProjectModule.CHECKLIST) public class ChecklistOverviewPanel extends GenericPanel { @@ -29,8 +28,6 @@ public class ChecklistOverviewPanel extends GenericPanel { public ChecklistOverviewPanel(String id, IModel model) { super(id, model); - - map = new EnumMap<>(ChecklistAnswerEnum.class); Long totalAnswered = 0L; Long totalUnanswered = 0L; @@ -52,23 +49,26 @@ public class ChecklistOverviewPanel extends GenericPanel { final Long finalTotalAnswered = totalAnswered; final List answers = Arrays.asList( - ChecklistAnswerEnum.GREEN, - ChecklistAnswerEnum.YELLOW, - ChecklistAnswerEnum.RED, - ChecklistAnswerEnum.NOT_APPLICABLE); - add(new ListView<>("answersBreakdown", answers) { - @Override - protected void populateItem(ListItem item) { - item.add(new EnumLabel<>("label", item.getModel())); - item.add(new Label("count", map.get(item.getModelObject()))); - } + ChecklistAnswerEnum.GREEN, + ChecklistAnswerEnum.YELLOW, + ChecklistAnswerEnum.RED, + ChecklistAnswerEnum.NOT_APPLICABLE + ); + add( + new ListView<>("answersBreakdown", answers) { + @Override + protected void populateItem(ListItem item) { + item.add(new EnumLabel<>("label", item.getModel())); + item.add(new Label("count", map.get(item.getModelObject()))); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(finalTotalAnswered > 0); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(finalTotalAnswered > 0); + } } - }); + ); } private LoadableDetachableModel countAnswers(final ChecklistAnswerEnum checklistAnswerEnum) { @@ -88,4 +88,4 @@ public class ChecklistOverviewPanel extends GenericPanel { } }; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanel.java index a5733d7be1..0788a57d45 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -23,9 +25,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class ChecklistQuestionPanel extends GenericPanel { public static final String QUESTION_LABEL = "questionLabel"; @@ -37,6 +36,7 @@ public class ChecklistQuestionPanel extends GenericPanel { @Inject private ActivityPlanFacade activityPlanFacade; + @Inject private NotificationController notificationController; @@ -50,22 +50,26 @@ public class ChecklistQuestionPanel extends GenericPanel { wmc.add(new Label("title", getModel().map(Checklist::getName))); wmc.add(new MultiLineLabel("description", getModel().map(Checklist::getDescription))); - wmc.add(new ListView<>(MEMBERS, getAuthors()) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(MEMBER_NAME, item.getModel())); + wmc.add( + new ListView<>(MEMBERS, getAuthors()) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(MEMBER_NAME, item.getModel())); + } } - }); - wmc.add(new ListView<>(QUESTIONS, checklistModel.map(Checklist::getQuestions)) { - @Override - protected void populateItem(ListItem item) { - Label label = new Label(QUESTION_LABEL, item.getModel().map(ChecklistQuestion::getQuestion)); - label.add(new AttributeAppender("id", Model.of(item.getModelObject().getId()))); - item.add(label); - item.add(new ChecklistAnswerCommentPanel(QUESTION, item.getModel())); - item.add(new AnswerListView(ANSWERS, getAuthors(), item.getModel())); + ); + wmc.add( + new ListView<>(QUESTIONS, checklistModel.map(Checklist::getQuestions)) { + @Override + protected void populateItem(ListItem item) { + Label label = new Label(QUESTION_LABEL, item.getModel().map(ChecklistQuestion::getQuestion)); + label.add(new AttributeAppender("id", Model.of(item.getModelObject().getId()))); + item.add(label); + item.add(new ChecklistAnswerCommentPanel(QUESTION, item.getModel())); + item.add(new AnswerListView(ANSWERS, getAuthors(), item.getModel())); + } } - }); + ); } private IModel> getAuthors() { @@ -73,6 +77,7 @@ public class ChecklistQuestionPanel extends GenericPanel { } private class AnswerListView extends ListView { + private final IModel question; public AnswerListView(String id, IModel> model, IModel question) { @@ -83,14 +88,21 @@ public class ChecklistQuestionPanel extends GenericPanel { @Override protected void populateItem(final ListItem item) { - item.add(new AnswerPanel("answer", question, item.getModel()) { - @Override - public void hook() { - if (activityPlanFacade.isCompletedByUser(SciProSession.get().getUser(), ChecklistQuestionPanel.this.getModelObject())) { - sendNotifications(); + item.add( + new AnswerPanel("answer", question, item.getModel()) { + @Override + public void hook() { + if ( + activityPlanFacade.isCompletedByUser( + SciProSession.get().getUser(), + ChecklistQuestionPanel.this.getModelObject() + ) + ) { + sendNotifications(); + } } } - }); + ); } private void sendNotifications() { @@ -106,4 +118,4 @@ public class ChecklistQuestionPanel extends GenericPanel { notificationController.notifyProject(checklist.getProject(), ProjectEvent.Event.CHECKLIST_ANSWERED, source); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanel.java index e2dddd2204..2a7e5e1076 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -27,11 +31,6 @@ import se.su.dsv.scipro.datatables.ClickableOrderColumn; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - public class ChecklistTemplateDataPanel extends Panel { @Inject @@ -56,7 +55,10 @@ public class ChecklistTemplateDataPanel extends Panel { } private void addTable() { - FilteredDataProvider dataProvider = new FilteredDataProvider<>(checklistTemplateService, titleString); + FilteredDataProvider dataProvider = new FilteredDataProvider<>( + checklistTemplateService, + titleString + ); dataProvider.setSort("templateNumber", SortOrder.ASCENDING); dataTable = new ExportableDataPanel<>("dt", columns(), dataProvider); add(dataTable); @@ -65,81 +67,103 @@ public class ChecklistTemplateDataPanel extends Panel { private List> columns() { List> columns = new ArrayList<>(); - columns.add(new ClickableOrderColumn<>(Model.of("Order"), ChecklistTemplate::getTemplateNumber, "templateNumber") { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target, boolean up) { - if (up) { - checklistTemplateService.upChecklistTemplate(clicked.getObject()); - } else { - checklistTemplateService.downChecklistTemplate(clicked.getObject()); - } - target.add(dataTable); - } - - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(String.valueOf(rowModel.getObject().getTemplateNumber())); - } - }); - - columns.add(new LambdaColumn<>(Model.of("Title"), ChecklistTemplate::getName) { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, LambdaModel.of(model, ChecklistTemplate::getName, ChecklistTemplate::setName)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ChecklistTemplate.class), model.getObject().getId()); - setResponsePage(AdminEditChecklistTemplatePage.class, pp); + columns.add( + new ClickableOrderColumn<>(Model.of("Order"), ChecklistTemplate::getTemplateNumber, "templateNumber") { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target, boolean up) { + if (up) { + checklistTemplateService.upChecklistTemplate(clicked.getObject()); + } else { + checklistTemplateService.downChecklistTemplate(clicked.getObject()); } - }); - } - }); - columns.add(new AbstractExportableColumn<>(Model.of("Types")) { - @Override - public void populateItem(Item> item, String id, IModel checklistTemplateIModel) { - item.add(new Label(id, formatProjectTypeNames(checklistTemplateIModel.getObject()))); - } + target.add(dataTable); + } - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(formatProjectTypeNames(rowModel.getObject())); + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(String.valueOf(rowModel.getObject().getTemplateNumber())); + } } - }); + ); + + columns.add( + new LambdaColumn<>(Model.of("Title"), ChecklistTemplate::getName) { + @Override + public void populateItem( + Item> components, + String s, + final IModel model + ) { + components.add( + new AjaxLinkPanel<>( + s, + model, + LambdaModel.of(model, ChecklistTemplate::getName, ChecklistTemplate::setName) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(ChecklistTemplate.class), model.getObject().getId()); + setResponsePage(AdminEditChecklistTemplatePage.class, pp); + } + } + ); + } + } + ); + columns.add( + new AbstractExportableColumn<>(Model.of("Types")) { + @Override + public void populateItem( + Item> item, + String id, + IModel checklistTemplateIModel + ) { + item.add(new Label(id, formatProjectTypeNames(checklistTemplateIModel.getObject()))); + } + + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(formatProjectTypeNames(rowModel.getObject())); + } + } + ); columns.add(new LambdaColumn<>(Model.of("Categories"), this::getCategoryNames)); - columns.add(new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - checklistTemplateService.safeDeleteChecklistTemplate(clicked.getObject()); - target.add(dataTable); + columns.add( + new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + checklistTemplateService.safeDeleteChecklistTemplate(clicked.getObject()); + target.add(dataTable); + } } - }); + ); return columns; } public String getCategoryNames(ChecklistTemplate checklistTemplate) { - return checklistTemplate.getCategories() - .stream() - .map(ChecklistCategory::getCategoryName) - .collect(Collectors.joining(", ")); + return checklistTemplate + .getCategories() + .stream() + .map(ChecklistCategory::getCategoryName) + .collect(Collectors.joining(", ")); } private void addTitleFilter() { TextField titleField = new TextField<>("titleFilter", titleString); - titleField.add(new OnChangeAjaxBehavior() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(dataTable); + titleField.add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); add(titleField); } private String formatProjectTypeNames(ChecklistTemplate checklistTemplate) { - return checklistTemplate.getProjectTypes() - .stream() - .map(ProjectType::getName) - .collect(Collectors.joining(", ")); + return checklistTemplate.getProjectTypes().stream().map(ProjectType::getName).collect(Collectors.joining(", ")); } } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/EditAnswerPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/EditAnswerPanel.java index 3d2e2174f2..51db95c318 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/EditAnswerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/EditAnswerPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.form.Form; @@ -10,14 +11,13 @@ import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.Model; import se.su.dsv.scipro.checklist.*; -import jakarta.inject.Inject; - public abstract class EditAnswerPanel extends Panel { public abstract void submitHook(); @Inject private ChecklistQuestionRepo checklistQuestionRepo; + @Inject private ChecklistAnswerService checklistAnswerService; @@ -34,8 +34,18 @@ public abstract class EditAnswerPanel extends Panel { public EditAnswerForm(String id, IModel model) { super(id, model); add(new MultiLineLabel("question", question.getObject().getQuestion())); - add(new TrafficLightPanel("answer", LambdaModel.of(model, ChecklistAnswer::getAnswer, ChecklistAnswer::setAnswer))); - add(new TextArea<>("comment", LambdaModel.of(model, ChecklistAnswer::getComment, ChecklistAnswer::setComment))); + add( + new TrafficLightPanel( + "answer", + LambdaModel.of(model, ChecklistAnswer::getAnswer, ChecklistAnswer::setAnswer) + ) + ); + add( + new TextArea<>( + "comment", + LambdaModel.of(model, ChecklistAnswer::getComment, ChecklistAnswer::setComment) + ) + ); add(new AttributeAppender("action", Model.of("#" + question.getObject().getId()), "")); } @@ -43,7 +53,10 @@ public abstract class EditAnswerPanel extends Panel { protected void onSubmit() { super.onSubmit(); - ChecklistAnswer copy = new ChecklistAnswer(EditAnswerForm.this.getModelObject().getUser(), EditAnswerForm.this.getModelObject().getAnswer()); + ChecklistAnswer copy = new ChecklistAnswer( + EditAnswerForm.this.getModelObject().getUser(), + EditAnswerForm.this.getModelObject().getAnswer() + ); copy.setComment(EditAnswerForm.this.getModelObject().getComment()); copy = checklistAnswerService.save(copy); @@ -52,7 +65,6 @@ public abstract class EditAnswerPanel extends Panel { checklistQuestionRepo.save(object); submitHook(); - } } } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPage.java b/view/src/main/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPage.java index 278a217742..9c36c83f80 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPage.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.checklists; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -13,9 +14,7 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) public class ProjectViewChecklistPage extends AbstractProjectDetailsPage implements MenuHighlightActivityPlan { @Inject @@ -23,7 +22,6 @@ public class ProjectViewChecklistPage extends AbstractProjectDetailsPage impleme public ProjectViewChecklistPage(PageParameters pp) { super(pp); - final Long checklistId = pp.get(PageParameterKeys.MAP.get(Checklist.class)).toOptionalLong(); if (checklistId == null) { noSuchChecklist(); diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPage.java b/view/src/main/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPage.java index 4d6c427937..9beb9c70e3 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPage.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.checklists; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + +import jakarta.inject.Inject; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.checklist.Checklist; @@ -11,13 +14,10 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) -public class SupervisorViewChecklistPage extends AbstractSupervisorProjectDetailsPage - implements MenuHighlightSupervisorMyProjects, MenuHighlightSupervisorActivityPlan { +@Authorization(authorizedRoles = { SUPERVISOR }) +public class SupervisorViewChecklistPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects, MenuHighlightSupervisorActivityPlan { @Inject private ChecklistService checklistService; diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/TrafficLightPanel.java b/view/src/main/java/se/su/dsv/scipro/checklists/TrafficLightPanel.java index 60482c38a8..623b87390c 100644 --- a/view/src/main/java/se/su/dsv/scipro/checklists/TrafficLightPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/TrafficLightPanel.java @@ -39,10 +39,19 @@ public class TrafficLightPanel extends FormComponentPanel { redImage = new ContextImage("redImage", new Model<>("images/icons/bullet_ball_glass_red.png")); noAnswerImage = new ContextImage("noAnswerImage", new Model<>("images/icons/bullet_ball_glass_grey.png")); - selectedGreen = new ContextImage("greenImage", new Model<>("images/icons/bullet_ball_glass_green_with_border.png")); - selectedYellow = new ContextImage("yellowImage", new Model<>("images/icons/bullet_ball_glass_yellow_with_border.png")); + selectedGreen = new ContextImage( + "greenImage", + new Model<>("images/icons/bullet_ball_glass_green_with_border.png") + ); + selectedYellow = new ContextImage( + "yellowImage", + new Model<>("images/icons/bullet_ball_glass_yellow_with_border.png") + ); selectedRed = new ContextImage("redImage", new Model<>("images/icons/bullet_ball_glass_red_with_border.png")); - selectedNotApplicable = new ContextImage("noAnswerImage", new Model<>("images/icons/bullet_ball_glass_grey_with_border.png")); + selectedNotApplicable = new ContextImage( + "noAnswerImage", + new Model<>("images/icons/bullet_ball_glass_grey_with_border.png") + ); greenBackup = greenImage; yellowBackup = yellowImage; @@ -54,7 +63,12 @@ public class TrafficLightPanel extends FormComponentPanel { greenLink = new TrafficLightLink("greenLink", ChecklistAnswerEnum.GREEN, selectedGreen, greenImage); redLink = new TrafficLightLink("redLink", ChecklistAnswerEnum.RED, selectedRed, redImage); yellowLink = new TrafficLightLink("yellowLink", ChecklistAnswerEnum.YELLOW, selectedYellow, yellowImage); - noAnswerLink = new TrafficLightLink("noAnswerLink", ChecklistAnswerEnum.NOT_APPLICABLE, selectedNotApplicable, noAnswerImage); + noAnswerLink = new TrafficLightLink( + "noAnswerLink", + ChecklistAnswerEnum.NOT_APPLICABLE, + selectedNotApplicable, + noAnswerImage + ); add(greenLink); add(yellowLink); add(redLink); @@ -69,7 +83,12 @@ public class TrafficLightPanel extends FormComponentPanel { private final ContextImage selectedImage; - public TrafficLightLink(String id, ChecklistAnswerEnum answer, ContextImage selectedImage, ContextImage defaultImage) { + public TrafficLightLink( + String id, + ChecklistAnswerEnum answer, + ContextImage selectedImage, + ContextImage defaultImage + ) { super(id, Model.of(answer)); this.selectedImage = selectedImage; add(getImage(answer, selectedImage, defaultImage)); @@ -105,7 +124,11 @@ public class TrafficLightPanel extends FormComponentPanel { target.add(noAnswerLink); } - private ContextImage getImage(ChecklistAnswerEnum answer, ContextImage selectedImage, ContextImage defaultImage) { + private ContextImage getImage( + ChecklistAnswerEnum answer, + ContextImage selectedImage, + ContextImage defaultImage + ) { return getSelected() == answer ? selectedImage : defaultImage; } } diff --git a/view/src/main/java/se/su/dsv/scipro/checklists/ViewChecklistTemplatePanelPeer.java b/view/src/main/java/se/su/dsv/scipro/checklists/ViewChecklistTemplatePanelPeer.java index c05f7f05f4..1b4f23c05e 100755 --- a/view/src/main/java/se/su/dsv/scipro/checklists/ViewChecklistTemplatePanelPeer.java +++ b/view/src/main/java/se/su/dsv/scipro/checklists/ViewChecklistTemplatePanelPeer.java @@ -11,14 +11,18 @@ import se.su.dsv.scipro.checklist.ChecklistTemplate; public class ViewChecklistTemplatePanelPeer extends Panel { public ViewChecklistTemplatePanelPeer(String id, final IModel clt) { - super(id); - + super(id); add(new Label("templateName", LambdaModel.of(clt, ChecklistTemplate::getName, ChecklistTemplate::setName))); - add(new ListView<>("questions", LambdaModel.of(clt, ChecklistTemplate::getQuestions, ChecklistTemplate::setQuestions)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("questionLabel", item.getModel())); + add( + new ListView<>( + "questions", + LambdaModel.of(clt, ChecklistTemplate::getQuestions, ChecklistTemplate::setQuestions) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("questionLabel", item.getModel())); + } } - }); - } + ); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AbstractMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/components/AbstractMenuPanel.java index 22d64a41f1..9f0cc89bc9 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/AbstractMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AbstractMenuPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.components; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.wicket.Page; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -14,10 +17,6 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.io.IClusterable; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlight; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * ABC-class for menu's of different types. * Subclasses should implement their own data feed mechanics via getItemList and provide a menu type via getMenuType @@ -30,7 +29,7 @@ public abstract class AbstractMenuPanel extends Panel { private static final Map CSS_CLASS = new HashMap<>() { { - put(MenuType.TAB_MULTIPLE_ROWS, "multi-tab-menu"); /*lägg in klasser här?*/ + put(MenuType.TAB_MULTIPLE_ROWS, "multi-tab-menu");/*lägg in klasser här?*/ put(MenuType.HORIZONTAL, "horizontal-menu"); } }; @@ -50,7 +49,11 @@ public abstract class AbstractMenuPanel extends Panel { * @param menuContainerCommonSuperClass [Needs documentation] * @param containerClass [Needs documentation] */ - public AbstractMenuPanel(final String id, final Class menuContainerCommonSuperClass, final Class containerClass) { + public AbstractMenuPanel( + final String id, + final Class menuContainerCommonSuperClass, + final Class containerClass + ) { super(id); this.menuContainerCommonSuperClass = menuContainerCommonSuperClass; this.containerClass = containerClass; @@ -81,15 +84,21 @@ public abstract class AbstractMenuPanel extends Panel { } } } - if (highLightAsCurrentByInterface || mi.getTargetClass().equals(containerClass) || - (mi.getTargetClass().getSuperclass().isAssignableFrom(containerClass) - && !mi.getTargetClass().getSuperclass().equals(menuContainerCommonSuperClass) - && !mi.isPopUp())) { + if ( + highLightAsCurrentByInterface || + mi.getTargetClass().equals(containerClass) || + (mi.getTargetClass().getSuperclass().isAssignableFrom(containerClass) && + !mi.getTargetClass().getSuperclass().equals(menuContainerCommonSuperClass) && + !mi.isPopUp()) + ) { item.add(new AttributeAppender("class", Model.of("current"), " ")); } - - BookmarkablePageLink link = new BookmarkablePageLink<>("menuItem", mi.getTargetClass(), mi.getPageParameters()); + BookmarkablePageLink link = new BookmarkablePageLink<>( + "menuItem", + mi.getTargetClass(), + mi.getPageParameters() + ); link.add(new Label("linkText", mi.getName())); if (mi.isPopUp()) { link.add(new AttributeAppender("target", Model.of("_blank"))); @@ -130,7 +139,11 @@ public abstract class AbstractMenuPanel extends Panel { this(name, targetClass, null, null, false); } - public MenuItem(final String name, final Class targetClass, final Class menuHilightInterface) { + public MenuItem( + final String name, + final Class targetClass, + final Class menuHilightInterface + ) { this(name, targetClass, menuHilightInterface, null, false); } @@ -138,7 +151,12 @@ public abstract class AbstractMenuPanel extends Panel { this(name, targetClass, null, pp, false); } - public MenuItem(final String name, final Class targetClass, final Class menuHilightInterface, PageParameters pp) { + public MenuItem( + final String name, + final Class targetClass, + final Class menuHilightInterface, + PageParameters pp + ) { this(name, targetClass, menuHilightInterface, pp, false); } @@ -146,7 +164,13 @@ public abstract class AbstractMenuPanel extends Panel { this(name, targetClass, null, null, isPopUp); } - public MenuItem(final String name, final Class targetClass, final Class menuHilightInterface, PageParameters pp, boolean popUp) { + public MenuItem( + final String name, + final Class targetClass, + final Class menuHilightInterface, + PageParameters pp, + boolean popUp + ) { this.name = Model.of(name); this.targetClass = targetClass; this.menuHighlightInterface = menuHilightInterface; @@ -173,5 +197,5 @@ public abstract class AbstractMenuPanel extends Panel { public boolean isPopUp() { return popUp; } - }//MenuItem + } //MenuItem } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AbstractUploadForm.java b/view/src/main/java/se/su/dsv/scipro/components/AbstractUploadForm.java index 8eda8dd100..dfc74e21b7 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/AbstractUploadForm.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AbstractUploadForm.java @@ -56,7 +56,6 @@ public abstract class AbstractUploadForm extends Form { fileUploadField.setRequired(true); add(fileUploadField); Button submitButton = new AjaxButton("submitButton", this) { - @Override public void onSubmit(AjaxRequestTarget target) { try { @@ -68,7 +67,7 @@ public abstract class AbstractUploadForm extends Form { String message = "The upload was rejected. Reason: " + ise.getMessage(); error(message); LOGGER.info(message, ise); - } catch (final Exception ioe) {//Use explicit error handling for uploading causing IOExceptions + } catch (final Exception ioe) { //Use explicit error handling for uploading causing IOExceptions String message = "An error occurred while uploading the resource, please try again"; error(message); LOGGER.info(message, ioe); @@ -94,8 +93,7 @@ public abstract class AbstractUploadForm extends Form { * Note: this method is only called if no Checked Exceptions are thrown by beforeOnNewSelectionChecker or onNewUpload * */ - protected void onFinished(AjaxRequestTarget target) { - } + protected void onFinished(AjaxRequestTarget target) {} /** * Implement to handle a newly uploaded file, default does nothing. @@ -103,6 +101,5 @@ public abstract class AbstractUploadForm extends Form { * are expected to take this into consideration. * Called whenever a file is uploaded and the form is posted. */ - protected void onNewUpload(final FileUpload fileUpload) { - } + protected void onNewUpload(final FileUpload fileUpload) {} } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AddUsersPanel.java b/view/src/main/java/se/su/dsv/scipro/components/AddUsersPanel.java index 78f18bdad9..d5f0d3bf59 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AddUsersPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AddUsersPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.components; +import jakarta.inject.Inject; +import java.util.HashSet; +import java.util.Set; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.feedback.ComponentFeedbackMessageFilter; @@ -16,10 +19,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.util.HashSet; -import java.util.Set; - public class AddUsersPanel extends GenericPanel> { @Inject @@ -29,8 +28,7 @@ public class AddUsersPanel extends GenericPanel> { public AddUsersPanel(String id, IModel> model, LookFor lookFor) { super(id, model); - - if (model.getObject()==null){ + if (model.getObject() == null) { model.setObject(new HashSet<>()); } @@ -38,64 +36,76 @@ public class AddUsersPanel extends GenericPanel> { wmc.setOutputMarkupId(true); add(wmc); - FencedFeedbackPanel feedbackPanel = new FencedFeedbackPanel("feedback", new ComponentFeedbackMessageFilter(AddUsersPanel.this)); + FencedFeedbackPanel feedbackPanel = new FencedFeedbackPanel( + "feedback", + new ComponentFeedbackMessageFilter(AddUsersPanel.this) + ); feedbackPanel.setOutputMarkupId(true); wmc.add(feedbackPanel); - if (lookFor == LookFor.AUTHORS){ - wmc.add(new AuthorAutoComplete("add") { - @Override - protected void action(AjaxRequestTarget target, User object) { - if (object != null) { - AddUsersPanel.this.getModelObject().add(object); + if (lookFor == LookFor.AUTHORS) { + wmc.add( + new AuthorAutoComplete("add") { + @Override + protected void action(AjaxRequestTarget target, User object) { + if (object != null) { + AddUsersPanel.this.getModelObject().add(object); + } + refresh(); + target.add(wmc); } - refresh(); - target.add(wmc); } - }); + ); } else { - wmc.add(new EmployeeAutoComplete("add", new DetachableServiceModel<>(userService)) { - @Override - protected void action(AjaxRequestTarget target, User object) { - if (object != null) { - AddUsersPanel.this.getModelObject().add(object); + wmc.add( + new EmployeeAutoComplete("add", new DetachableServiceModel<>(userService)) { + @Override + protected void action(AjaxRequestTarget target, User object) { + if (object != null) { + AddUsersPanel.this.getModelObject().add(object); + } + refresh(); + target.add(wmc); } - refresh(); - target.add(wmc); } - }); + ); } users = new ListView<>("users", new ListAdapterModel<>(model)) { @Override protected void populateItem(final ListItem item) { item.add(new UserLinkPanel("user", new DetachableServiceModel<>(userService, item.getModelObject()))); - item.add(new AjaxLink<>("remove", item.getModel()) { - @Override - public void onClick(AjaxRequestTarget target) { - AddUsersPanel.this.getModelObject().remove(item.getModelObject()); - refresh(); - target.add(wmc); + item.add( + new AjaxLink<>("remove", item.getModel()) { + @Override + public void onClick(AjaxRequestTarget target) { + AddUsersPanel.this.getModelObject().remove(item.getModelObject()); + refresh(); + target.add(wmc); + } } - }); + ); } }; wmc.add(users); - wmc.add(new Label("empty", Model.of("No users")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject()==null || getModelObject().isEmpty()); + wmc.add( + new Label("empty", Model.of("No users")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject() == null || getModelObject().isEmpty()); + } } - }); + ); } - private void refresh(){ + private void refresh() { users.detach(); } public enum LookFor { - AUTHORS, EMPLOYEES + AUTHORS, + EMPLOYEES, } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxAutoCompleteChoice.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxAutoCompleteChoice.java index edbe5bb107..f8b320a0d7 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxAutoCompleteChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxAutoCompleteChoice.java @@ -6,7 +6,6 @@ import org.apache.wicket.model.IModel; public abstract class AjaxAutoCompleteChoice extends AutoCompleteChoice { - public AjaxAutoCompleteChoice(String id) { super(id); } @@ -18,14 +17,15 @@ public abstract class AjaxAutoCompleteChoice extends AutoCompleteChoice { @Override protected void onInitialize() { super.onInitialize(); - add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - action(target, getModelObject()); + add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + action(target, getModelObject()); + } } - }); + ); } protected abstract void action(AjaxRequestTarget target, T object); - } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxCheckBoxMultipleChoice.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxCheckBoxMultipleChoice.java index 6fa36cec57..78f685da00 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxCheckBoxMultipleChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxCheckBoxMultipleChoice.java @@ -1,39 +1,54 @@ package se.su.dsv.scipro.components; +import java.util.Collection; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import org.apache.wicket.model.util.ListModel; -import java.util.Collection; -import java.util.List; - public abstract class AjaxCheckBoxMultipleChoice extends BootstrapCheckBoxMultipleChoice { - public AjaxCheckBoxMultipleChoice(String id, List defaultSelection, List choices, IChoiceRenderer renderer) { + public AjaxCheckBoxMultipleChoice( + String id, + List defaultSelection, + List choices, + IChoiceRenderer renderer + ) { super(id, new ListModel<>(defaultSelection), choices, renderer); } - public AjaxCheckBoxMultipleChoice(String id, IModel> defaultModel, List choices, IChoiceRenderer renderer) { + public AjaxCheckBoxMultipleChoice( + String id, + IModel> defaultModel, + List choices, + IChoiceRenderer renderer + ) { super(id, defaultModel, choices, renderer); } - public AjaxCheckBoxMultipleChoice(final String id, final IModel> model, final IModel> choices, final IChoiceRenderer renderer) { + public AjaxCheckBoxMultipleChoice( + final String id, + final IModel> model, + final IModel> choices, + final IChoiceRenderer renderer + ) { super(id, model, choices, renderer); } @Override protected void onInitialize() { super.onInitialize(); - add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - AjaxCheckBoxMultipleChoice.this.onUpdate(target); + add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + AjaxCheckBoxMultipleChoice.this.onUpdate(target); + } } - }); + ); } public abstract void onUpdate(AjaxRequestTarget target); - } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxConfirmingLinkPanel.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxConfirmingLinkPanel.java index 269efd56f8..2bcdf280fe 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxConfirmingLinkPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxConfirmingLinkPanel.java @@ -6,6 +6,7 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.util.AjaxConfirmationLink; public abstract class AjaxConfirmingLinkPanel extends AjaxLinkPanel { + public AjaxConfirmingLinkPanel(String id, IModel model, IModel label) { super(id, model, label); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxDropDownChoice.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxDropDownChoice.java index a9a442c38c..4556beefbb 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxDropDownChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxDropDownChoice.java @@ -1,14 +1,12 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; -import java.util.List; - - public abstract class AjaxDropDownChoice extends DropDownChoice { public AjaxDropDownChoice(String id, IModel model, IModel> choices) { @@ -23,19 +21,26 @@ public abstract class AjaxDropDownChoice extends DropDownChoice { super(id, model, choices); } - public AjaxDropDownChoice(final String id, final IModel model, final List choices, final IChoiceRenderer choiceRenderer) { + public AjaxDropDownChoice( + final String id, + final IModel model, + final List choices, + final IChoiceRenderer choiceRenderer + ) { super(id, model, choices, choiceRenderer); } @Override protected void onInitialize() { super.onInitialize(); - add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - onNewSelection(target, getModelObject()); + add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + onNewSelection(target, getModelObject()); + } } - }); + ); } public abstract void onNewSelection(AjaxRequestTarget target, T objectSelected); diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxEnumLinkPanel.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxEnumLinkPanel.java index 96bbf12874..8538df7e55 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxEnumLinkPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxEnumLinkPanel.java @@ -5,6 +5,7 @@ import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.model.IModel; public abstract class AjaxEnumLinkPanel> extends AjaxLinkPanel { + public AjaxEnumLinkPanel(String id, IModel model, IModel enumLabel) { super(id, model, enumLabel); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxFeedbackPanelUpdater.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxFeedbackPanelUpdater.java index 18099e388e..6000c966b4 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxFeedbackPanelUpdater.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxFeedbackPanelUpdater.java @@ -1,24 +1,29 @@ package se.su.dsv.scipro.components; +import java.util.Map; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.util.visit.IVisitor; -import java.util.Map; - /** * This class add to AjaxRequesttarget.add() all feddback panels that should be repaint *

* Based on Apache Wicket Cookbook */ public class AjaxFeedbackPanelUpdater implements AjaxRequestTarget.IListener { + @Override public void onBeforeRespond(Map map, final AjaxRequestTarget target) { - target.getPage().visitChildren(FeedbackPanel.class, (IVisitor) (feedback, visit) -> { - if (feedback.getOutputMarkupId() && (feedback.anyMessage() || feedback.isVisibleInHierarchy())) { - target.add(feedback); - } - }); + target + .getPage() + .visitChildren( + FeedbackPanel.class, + (IVisitor) (feedback, visit) -> { + if (feedback.getOutputMarkupId() && (feedback.anyMessage() || feedback.isVisibleInHierarchy())) { + target.add(feedback); + } + } + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/AjaxRadioChoice.java b/view/src/main/java/se/su/dsv/scipro/components/AjaxRadioChoice.java index 854a85fdc3..36935b6ccc 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AjaxRadioChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AjaxRadioChoice.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -7,8 +8,6 @@ import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; -import java.util.List; - public abstract class AjaxRadioChoice extends BootstrapRadioChoice { private String confirmationMessage; @@ -17,7 +16,13 @@ public abstract class AjaxRadioChoice extends BootstrapRadioChoice { super(id, model, choices, renderer); } - public AjaxRadioChoice(String id, IModel model, List choices, IChoiceRenderer renderer, String confirmationMessage) { + public AjaxRadioChoice( + String id, + IModel model, + List choices, + IChoiceRenderer renderer, + String confirmationMessage + ) { super(id, model, choices, renderer); this.confirmationMessage = confirmationMessage; } @@ -25,28 +30,33 @@ public abstract class AjaxRadioChoice extends BootstrapRadioChoice { @Override protected void onInitialize() { super.onInitialize(); - add(new AjaxFormChoiceComponentUpdatingBehavior() { + add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + update(target); + } - @Override - protected void onUpdate(AjaxRequestTarget target) { - update(target); - } - - @Override - protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { - super.updateAjaxAttributes(attributes); - if (confirmationMessage != null) { - addConfirmation(attributes); + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { + super.updateAjaxAttributes(attributes); + if (confirmationMessage != null) { + addConfirmation(attributes); + } } } - }); + ); } protected abstract void update(AjaxRequestTarget target); protected void addConfirmation(AjaxRequestAttributes attributes) { - AjaxCallListener ajaxCallListener = new AjaxCallListener(); - ajaxCallListener.onPrecondition("if (!confirm('" + confirmationMessage.replaceAll("'", "\\\\'") + "')) {window.location.reload(); return false;}"); - attributes.getAjaxCallListeners().add(ajaxCallListener); + AjaxCallListener ajaxCallListener = new AjaxCallListener(); + ajaxCallListener.onPrecondition( + "if (!confirm('" + + confirmationMessage.replaceAll("'", "\\\\'") + + "')) {window.location.reload(); return false;}" + ); + attributes.getAjaxCallListeners().add(ajaxCallListener); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AuthorAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/AuthorAutoComplete.java index f81758e229..a7a2a8c17c 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AuthorAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AuthorAutoComplete.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.components; +import java.util.EnumSet; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; -import java.util.EnumSet; - public abstract class AuthorAutoComplete extends UserAutoComplete { public AuthorAutoComplete(String id) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteChoice.java b/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteChoice.java index e6d25a2d16..89556c7091 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteChoice.java @@ -38,7 +38,7 @@ public abstract class AutoCompleteChoice extends Select2Choice { protected abstract ChoiceProvider getChoiceProvider(); - public boolean getAllowClear(){ + public boolean getAllowClear() { return true; } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteRoleProvider.java b/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteRoleProvider.java index cd545ba711..364e40e146 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteRoleProvider.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AutoCompleteRoleProvider.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.components; -import org.wicketstuff.select2.ChoiceProvider; -import org.wicketstuff.select2.Response; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.system.UserSearchService; - import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; +import org.wicketstuff.select2.ChoiceProvider; +import org.wicketstuff.select2.Response; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.system.UserSearchService; public class AutoCompleteRoleProvider extends ChoiceProvider { @@ -41,10 +40,9 @@ public class AutoCompleteRoleProvider extends ChoiceProvider { @Override public Collection toChoices(Collection ids) { List list = new ArrayList<>(ids.size()); - for(String id : ids) { + for (String id : ids) { list.add(service.findOne(Long.valueOf(id))); } return list; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AutoHidingListView.java b/view/src/main/java/se/su/dsv/scipro/components/AutoHidingListView.java index 0f00cb28e7..4950576d3d 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AutoHidingListView.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AutoHidingListView.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.IModel; -import java.util.List; - public abstract class AutoHidingListView extends ListView { + public AutoHidingListView(String id, IModel> model) { super(id, model); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/AutoSavingBehaviour.java b/view/src/main/java/se/su/dsv/scipro/components/AutoSavingBehaviour.java index aa20bf2906..18047dfac8 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/AutoSavingBehaviour.java +++ b/view/src/main/java/se/su/dsv/scipro/components/AutoSavingBehaviour.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.components; +import java.time.Duration; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.attributes.ThrottlingSettings; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; -import java.time.Duration; - public abstract class AutoSavingBehaviour extends AjaxFormComponentUpdatingBehavior { public static final String EVENT = "keydown"; @@ -21,15 +20,22 @@ public abstract class AutoSavingBehaviour extends AjaxFormComponentUpdatingBehav protected abstract void onUpdate(AjaxRequestTarget target); @Override - protected void onError(final AjaxRequestTarget target, final RuntimeException e) { - } + protected void onError(final AjaxRequestTarget target, final RuntimeException e) {} @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); - attributes.setThrottlingSettings(new ThrottlingSettings(getComponent().getPath(), Duration.ofSeconds(AUTO_SAVE_INTERVAL_IN_SECONDS))); - attributes.getAjaxCallListeners().add(new AjaxCallListener() - .onFailure("alert('Auto-saving just failed, you should take precautions to not lose any text and refresh the page afterwards.');")); + attributes.setThrottlingSettings( + new ThrottlingSettings(getComponent().getPath(), Duration.ofSeconds(AUTO_SAVE_INTERVAL_IN_SECONDS)) + ); + attributes + .getAjaxCallListeners() + .add( + new AjaxCallListener() + .onFailure( + "alert('Auto-saving just failed, you should take precautions to not lose any text and refresh the page afterwards.');" + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapCardTabbedPanel.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapCardTabbedPanel.java index 113aea0c02..59a96b263e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapCardTabbedPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapCardTabbedPanel.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.extensions.ajax.markup.html.tabs.AjaxTabbedPanel; import org.apache.wicket.extensions.markup.html.tabs.ITab; import org.apache.wicket.markup.html.WebMarkupContainer; -import java.util.List; - public class BootstrapCardTabbedPanel extends AjaxTabbedPanel { + public BootstrapCardTabbedPanel(String id, List tabs) { super(id, tabs); } @@ -15,8 +15,7 @@ public class BootstrapCardTabbedPanel extends AjaxTabbedPanel @Override protected WebMarkupContainer newLink(String linkId, int index) { WebMarkupContainer components = super.newLink(linkId, index); - components.add(AttributeModifier.append("class", - () -> getSelectedTab() == index ? "active" : "")); + components.add(AttributeModifier.append("class", () -> getSelectedTab() == index ? "active" : "")); return components; } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapCheckBoxMultipleChoice.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapCheckBoxMultipleChoice.java index 017a9559d0..e75f66000d 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapCheckBoxMultipleChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapCheckBoxMultipleChoice.java @@ -1,21 +1,31 @@ package se.su.dsv.scipro.components; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import org.apache.wicket.markup.html.form.CheckBoxMultipleChoice; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import org.apache.wicket.util.value.AttributeMap; import org.apache.wicket.util.value.IValueMap; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - public class BootstrapCheckBoxMultipleChoice extends CheckBoxMultipleChoice { - public BootstrapCheckBoxMultipleChoice(final String id, final IModel> model, final List choices, final IChoiceRenderer renderer) { + + public BootstrapCheckBoxMultipleChoice( + final String id, + final IModel> model, + final List choices, + final IChoiceRenderer renderer + ) { super(id, model, choices, renderer); } - public BootstrapCheckBoxMultipleChoice(final String id, final IModel> model, final IModel> choices, final IChoiceRenderer renderer) { + public BootstrapCheckBoxMultipleChoice( + final String id, + final IModel> model, + final IModel> choices, + final IChoiceRenderer renderer + ) { super(id, model, choices, renderer); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateField.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateField.java index ed9f57a816..faba36e3b2 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateField.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateField.java @@ -1,11 +1,11 @@ package se.su.dsv.scipro.components; +import java.util.*; import org.apache.wicket.extensions.markup.html.form.DateTextField; import org.apache.wicket.model.IModel; -import java.util.*; - public class BootstrapDateField extends DateTextField { + private static final String DATE_PATTERN = "yyyy-MM-dd"; public BootstrapDateField(final String id, final IModel model) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDatePicker.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDatePicker.java index 7f7f76dd4a..a83d2b72f2 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDatePicker.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDatePicker.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.time.LocalDate; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.*; @@ -7,8 +8,6 @@ import org.apache.wicket.request.Response; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.resource.JQueryPluginResourceReference; -import java.time.LocalDate; - public class BootstrapDatePicker extends Behavior { private final LocalDate startDate; @@ -32,8 +31,16 @@ public class BootstrapDatePicker extends Behavior { @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); - response.render(JavaScriptReferenceHeaderItem.forReference(new JQueryPluginResourceReference(BootstrapDatePicker.class, "bootstrap-datetimepicker.js"))); - response.render(CssReferenceHeaderItem.forReference(new PackageResourceReference(BootstrapDatePicker.class, "bootstrap-datetimepicker.css"))); + response.render( + JavaScriptReferenceHeaderItem.forReference( + new JQueryPluginResourceReference(BootstrapDatePicker.class, "bootstrap-datetimepicker.js") + ) + ); + response.render( + CssReferenceHeaderItem.forReference( + new PackageResourceReference(BootstrapDatePicker.class, "bootstrap-datetimepicker.css") + ) + ); String javascript = String.format("$('#%s').focus();", component.getMarkupId()); response.render(OnEventHeaderItem.forMarkupId(getIconId(component), "click", javascript)); response.render(OnDomReadyHeaderItem.forScript(initializeDatePickerJavascript(component))); @@ -73,7 +80,10 @@ public class BootstrapDatePicker extends Behavior { response.append("startDate: ").append(maybeQuote(startDate)); } response.append("})"); - response.append(".on('changeDate', function() { $('#").append(component.getMarkupId()).append("').trigger('inputchange'); });"); + response + .append(".on('changeDate', function() { $('#") + .append(component.getMarkupId()) + .append("').trigger('inputchange'); });"); } response.append("});"); return response.toString(); diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateTimeComponent.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateTimeComponent.java index ca0513f473..0dfd377975 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateTimeComponent.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapDateTimeComponent.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.components; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.FormComponent; -import org.apache.wicket.markup.html.form.FormComponentPanel; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.*; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.markup.html.form.FormComponentPanel; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; public class BootstrapDateTimeComponent extends FormComponentPanel { @@ -41,13 +40,15 @@ public class BootstrapDateTimeComponent extends FormComponentPanel { dateField.add(new BootstrapDatePicker()); add(dateField); - add(new Label("dateHelp", dateHelpText()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isEmpty()); + add( + new Label("dateHelp", dateHelpText()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isEmpty()); + } } - }); + ); timeField = new TextField<>("time", new Model<>(), LocalTime.class) { @Override @@ -81,11 +82,8 @@ public class BootstrapDateTimeComponent extends FormComponentPanel { LocalTime time = timeField.getConvertedInput(); if (date == null || time == null) { setConvertedInput(null); - } - else { - Instant instant = LocalDateTime.of(date, time) - .atZone(ZoneId.systemDefault()) - .toInstant(); + } else { + Instant instant = LocalDateTime.of(date, time).atZone(ZoneId.systemDefault()).toInstant(); setConvertedInput(Date.from(instant)); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapRadioChoice.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapRadioChoice.java index e637c41152..de8984900a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapRadioChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapRadioChoice.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.components; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.markup.html.form.RadioChoice; import org.apache.wicket.model.IModel; import org.apache.wicket.util.value.AttributeMap; import org.apache.wicket.util.value.IValueMap; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - public class BootstrapRadioChoice extends RadioChoice { + public BootstrapRadioChoice(final String id) { super(id); } @@ -19,11 +19,21 @@ public class BootstrapRadioChoice extends RadioChoice { super(id, model, choices); } - public BootstrapRadioChoice(final String id, final IModel model, final List choices, final IChoiceRenderer renderer) { + public BootstrapRadioChoice( + final String id, + final IModel model, + final List choices, + final IChoiceRenderer renderer + ) { super(id, model, choices, renderer); } - public BootstrapRadioChoice(final String id, final IModel model, final IModel> choices, final IChoiceRenderer renderer) { + public BootstrapRadioChoice( + final String id, + final IModel model, + final IModel> choices, + final IChoiceRenderer renderer + ) { super(id, model, choices, renderer); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapTabs.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapTabs.java index 3258517dc6..b3c234b14e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapTabs.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapTabs.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -10,46 +11,47 @@ import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import java.util.List; - public abstract class BootstrapTabs extends GenericPanel> { private static final AttributeAppender ACTIVE = AttributeAppender.append("class", "active"); protected BootstrapTabs(final String id, final IModel> ts) { super(id, ts); - - add(new ListView<>("tabs", ts) { - @Override - protected void populateItem(final ListItem item) { - final IModel labelModel = getLabelModel(item.getModel()); - final String href = "#" + BootstrapTabs.this.getHref(labelModel); - final ExternalLink tab = new ExternalLink("tabLink", Model.of(href), labelModel); - if (item.getIndex() == 0) { - item.add(ACTIVE); - tab.add(ACTIVE); + add( + new ListView<>("tabs", ts) { + @Override + protected void populateItem(final ListItem item) { + final IModel labelModel = getLabelModel(item.getModel()); + final String href = "#" + BootstrapTabs.this.getHref(labelModel); + final ExternalLink tab = new ExternalLink("tabLink", Model.of(href), labelModel); + if (item.getIndex() == 0) { + item.add(ACTIVE); + tab.add(ACTIVE); + } + item.add(tab); } - item.add(tab); } - }); + ); - add(new ListView<>("content", ts) { - { - setReuseItems(true); - } - - @Override - protected void populateItem(final ListItem item) { - final WebMarkupContainer wmc = getContent("id", item.getModel()); - final IModel labelModel = getLabelModel(item.getModel()); - final String href = BootstrapTabs.this.getHref(labelModel); - if (item.getIndex() == 0) { - item.add(ACTIVE); + add( + new ListView<>("content", ts) { + { + setReuseItems(true); + } + + @Override + protected void populateItem(final ListItem item) { + final WebMarkupContainer wmc = getContent("id", item.getModel()); + final IModel labelModel = getLabelModel(item.getModel()); + final String href = BootstrapTabs.this.getHref(labelModel); + if (item.getIndex() == 0) { + item.add(ACTIVE); + } + item.add(AttributeModifier.replace("id", href)); + item.add(wmc); } - item.add(AttributeModifier.replace("id", href)); - item.add(wmc); } - }); + ); } private String getHref(final IModel labelModel) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/BootstrapTimePicker.java b/view/src/main/java/se/su/dsv/scipro/components/BootstrapTimePicker.java index b8634ab2a7..94c5930bf8 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/BootstrapTimePicker.java +++ b/view/src/main/java/se/su/dsv/scipro/components/BootstrapTimePicker.java @@ -11,6 +11,7 @@ import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.resource.JQueryPluginResourceReference; public class BootstrapTimePicker extends Behavior { + @Override public void bind(final Component component) { super.bind(component); @@ -20,8 +21,16 @@ public class BootstrapTimePicker extends Behavior { @Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); - response.render(CssHeaderItem.forReference(new PackageResourceReference(BootstrapTimePicker.class, "bootstrap-clockpicker.css"))); - response.render(JavaScriptHeaderItem.forReference(new JQueryPluginResourceReference(BootstrapTimePicker.class, "bootstrap-clockpicker.js"))); + response.render( + CssHeaderItem.forReference( + new PackageResourceReference(BootstrapTimePicker.class, "bootstrap-clockpicker.css") + ) + ); + response.render( + JavaScriptHeaderItem.forReference( + new JQueryPluginResourceReference(BootstrapTimePicker.class, "bootstrap-clockpicker.js") + ) + ); response.render(OnDomReadyHeaderItem.forScript(initializeClockpickerJavascript(component.getMarkupId()))); } @@ -44,16 +53,16 @@ public class BootstrapTimePicker extends Behavior { private String initializeClockpickerJavascript(String markupId) { return """ - $(function() { - var $input = $('#%s'); - $input.parent().clockpicker({ - "donetext":"", - "autoclose":true, - "afterHide":function() { - $input.trigger('inputchange'); - } - }); - }); - """.formatted(markupId); + $(function() { + var $input = $('#%s'); + $input.parent().clockpicker({ + "donetext":"", + "autoclose":true, + "afterHide":function() { + $input.trigger('inputchange'); + } + }); + }); + """.formatted(markupId); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/CSPPalette.java b/view/src/main/java/se/su/dsv/scipro/components/CSPPalette.java index 0d117b1767..e262ac457f 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/CSPPalette.java +++ b/view/src/main/java/se/su/dsv/scipro/components/CSPPalette.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.util.Collection; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.extensions.markup.html.form.palette.Palette; @@ -11,19 +12,33 @@ import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import org.danekja.java.util.function.serializable.SerializableSupplier; -import java.util.Collection; - /** * Makes the {@link Palette} CSP-compliant by replacing the {@code onfocus} * and {@code ondblclick} attributes with event handlers. */ public class CSPPalette extends Palette { - public CSPPalette(final String id, final IModel> model, final IModel> choicesModel, final IChoiceRenderer choiceRenderer, final int rows, final boolean allowOrder) { + + public CSPPalette( + final String id, + final IModel> model, + final IModel> choicesModel, + final IChoiceRenderer choiceRenderer, + final int rows, + final boolean allowOrder + ) { super(id, model, choicesModel, choiceRenderer, rows, allowOrder); add(new DefaultTheme()); } - public CSPPalette(final String id, final IModel> model, final IModel> choicesModel, final IChoiceRenderer choiceRenderer, final int rows, final boolean allowOrder, final boolean allowMoveAll) { + public CSPPalette( + final String id, + final IModel> model, + final IModel> choicesModel, + final IChoiceRenderer choiceRenderer, + final int rows, + final boolean allowOrder, + final boolean allowMoveAll + ) { super(id, model, choicesModel, choiceRenderer, rows, allowOrder, allowMoveAll); add(new DefaultTheme()); } @@ -43,9 +58,9 @@ public class CSPPalette extends Palette { } private Behavior replaceAttributeWithEventHandler( - final SerializableSupplier ondblclick, - final SerializableSupplier onfocus) - { + final SerializableSupplier ondblclick, + final SerializableSupplier onfocus + ) { return new Behavior() { @Override public void renderHead(final Component component, final IHeaderResponse response) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/CheckBoxRequiredValidator.java b/view/src/main/java/se/su/dsv/scipro/components/CheckBoxRequiredValidator.java index bb948105ac..903ca2120c 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/CheckBoxRequiredValidator.java +++ b/view/src/main/java/se/su/dsv/scipro/components/CheckBoxRequiredValidator.java @@ -1,14 +1,15 @@ -package se.su.dsv.scipro.components; - -import org.apache.wicket.validation.IValidatable; -import org.apache.wicket.validation.IValidator; -import org.apache.wicket.validation.ValidationError; - -public class CheckBoxRequiredValidator implements IValidator { - @Override - public void validate(IValidatable checked) { - if (!checked.getValue()) { - checked.error(new ValidationError(this)); - } - } -} +package se.su.dsv.scipro.components; + +import org.apache.wicket.validation.IValidatable; +import org.apache.wicket.validation.IValidator; +import org.apache.wicket.validation.ValidationError; + +public class CheckBoxRequiredValidator implements IValidator { + + @Override + public void validate(IValidatable checked) { + if (!checked.getValue()) { + checked.error(new ValidationError(this)); + } + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/ClientValidatingSubmitLink.java b/view/src/main/java/se/su/dsv/scipro/components/ClientValidatingSubmitLink.java index b8b2eb2978..aaad7965ed 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ClientValidatingSubmitLink.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ClientValidatingSubmitLink.java @@ -11,6 +11,7 @@ import org.apache.wicket.markup.html.form.SubmitLink; * which when received back down to the form will submit it if it has not been prevented using {@code preventDefault()}. */ public class ClientValidatingSubmitLink extends SubmitLink { + public ClientValidatingSubmitLink(String id) { super(id); } @@ -26,8 +27,6 @@ public class ClientValidatingSubmitLink extends SubmitLink { */ @Override protected final CharSequence getTriggerJavaScript() { - return super.getTriggerJavaScript() - .toString() - .replace("f.submit()", "f.requestSubmit()"); + return super.getTriggerJavaScript().toString().replace("f.submit()", "f.requestSubmit()"); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/CoAuthorChoice.java b/view/src/main/java/se/su/dsv/scipro/components/CoAuthorChoice.java index d0c9d8ad37..d90994b801 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/CoAuthorChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/CoAuthorChoice.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.components; +import jakarta.inject.Inject; +import java.util.Collection; +import java.util.EnumSet; import org.apache.wicket.model.IModel; import org.wicketstuff.select2.Select2MultiChoice; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchService; -import jakarta.inject.Inject; -import java.util.Collection; -import java.util.EnumSet; - public class CoAuthorChoice extends Select2MultiChoice { @Inject diff --git a/view/src/main/java/se/su/dsv/scipro/components/ConfirmationLink.java b/view/src/main/java/se/su/dsv/scipro/components/ConfirmationLink.java index 61db9b53d6..d5044c0581 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ConfirmationLink.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ConfirmationLink.java @@ -15,6 +15,7 @@ import org.apache.wicket.model.IModel; * prompt is presented. */ public abstract class ConfirmationLink extends Link { + protected IModel confirmationMsgModel; public ConfirmationLink(String id, IModel confirmationMsgModel) { @@ -32,9 +33,11 @@ public abstract class ConfirmationLink extends Link { if (confirmationMsgModel.getObject() == null) { return null; } - return String.format("event.preventDefault(); if (confirm('%s')) { window.location.href = '%s'; }", - confirmationMsgModel.getObject().replace("'", "\\'"), - url); + return String.format( + "event.preventDefault(); if (confirm('%s')) { window.location.href = '%s'; }", + confirmationMsgModel.getObject().replace("'", "\\'"), + url + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/components/CounterTextArea.java b/view/src/main/java/se/su/dsv/scipro/components/CounterTextArea.java index b2185b9613..864b6f9358 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/CounterTextArea.java +++ b/view/src/main/java/se/su/dsv/scipro/components/CounterTextArea.java @@ -45,17 +45,16 @@ public class CounterTextArea extends FormComponentPanel { private void addCounter() { final Label countLabel = new Label(COUNT_LABEL, () -> { - String text = textArea.getInput(); - return max - (text != null ? text.length() : 0); - } - ); + String text = textArea.getInput(); + return max - (text != null ? text.length() : 0); + }); countLabel.setOutputMarkupId(true); AjaxFormComponentUpdatingBehavior behavior = new AjaxFormComponentUpdatingBehavior("keyup") { - @Override protected void onUpdate(AjaxRequestTarget target) { updateCount(target); } + @Override protected void onError(AjaxRequestTarget target, RuntimeException e) { updateCount(target); diff --git a/view/src/main/java/se/su/dsv/scipro/components/DateColumn.java b/view/src/main/java/se/su/dsv/scipro/components/DateColumn.java index 3da7cccb67..4c6caba018 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/DateColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DateColumn.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.components; +import java.text.SimpleDateFormat; +import java.util.Date; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; import org.apache.wicket.markup.repeater.Item; @@ -7,9 +9,6 @@ import org.apache.wicket.model.IModel; import org.danekja.java.util.function.serializable.SerializableFunction; import se.su.dsv.scipro.data.enums.DateStyle; -import java.text.SimpleDateFormat; -import java.util.Date; - public class DateColumn extends LambdaColumn { private final DateStyle dateStyle; @@ -27,7 +26,12 @@ public class DateColumn extends LambdaColumn { this(displayModel, dateFunction, sort, DateStyle.DATE); } - public DateColumn(IModel displayModel, SerializableFunction dateFunction, S sort, DateStyle dateStyle) { + public DateColumn( + IModel displayModel, + SerializableFunction dateFunction, + S sort, + DateStyle dateStyle + ) { super(displayModel, sort, dateFunction); this.dateStyle = dateStyle; } @@ -35,14 +39,13 @@ public class DateColumn extends LambdaColumn { @Override public IModel getDataModel(final IModel rowModel) { return () -> { - final Date date = (Date) super.getDataModel(rowModel).getObject(); - if (date == null) { - return null; - } - else { - final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateStyle.getFormat()); - return simpleDateFormat.format(date); - } + final Date date = (Date) super.getDataModel(rowModel).getObject(); + if (date == null) { + return null; + } else { + final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateStyle.getFormat()); + return simpleDateFormat.format(date); + } }; } @@ -51,4 +54,4 @@ public class DateColumn extends LambdaColumn { public void populateItem(Item> cellItem, String componentId, IModel rowModel) { cellItem.add(new DateLabel(componentId, (IModel) super.getDataModel(rowModel), dateStyle)); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/DateLabel.java b/view/src/main/java/se/su/dsv/scipro/components/DateLabel.java index 76ddee7304..6707b60507 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DateLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DateLabel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.components; +import jakarta.inject.Inject; +import java.util.Date; +import java.util.Locale; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.html.basic.Label; @@ -8,13 +11,11 @@ import org.apache.wicket.util.convert.IConverter; import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.date.DateService; -import jakarta.inject.Inject; -import java.util.Date; -import java.util.Locale; - public class DateLabel extends Label { + @Inject private DateService dateService; + private final DateStyle dateStyle; public DateLabel(String id, IModel model) { @@ -41,6 +42,7 @@ public class DateLabel extends Label { } private class DateConverter implements IConverter { + @Override public Date convertToObject(String value, Locale locale) { throw new UnsupportedOperationException("DateLabel should not be converting back to date"); diff --git a/view/src/main/java/se/su/dsv/scipro/components/DatesValidator.java b/view/src/main/java/se/su/dsv/scipro/components/DatesValidator.java index 4ef0c699b7..4c73749218 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DatesValidator.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DatesValidator.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.components; +import java.time.LocalDate; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.validation.AbstractFormValidator; import org.apache.wicket.util.lang.Args; -import java.time.LocalDate; - public class DatesValidator extends AbstractFormValidator { + private final FormComponent firstDateComponent; private final FormComponent secondDateComponent; @@ -18,7 +18,7 @@ public class DatesValidator extends AbstractFormValidator { @Override public FormComponent[] getDependentFormComponents() { - return new FormComponent[]{firstDateComponent, secondDateComponent}; + return new FormComponent[] { firstDateComponent, secondDateComponent }; } @Override @@ -30,4 +30,4 @@ public class DatesValidator extends AbstractFormValidator { error(firstDateComponent); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/DefaultDataPanel.java b/view/src/main/java/se/su/dsv/scipro/components/DefaultDataPanel.java index c33fe89f9a..bb7f677582 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DefaultDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DefaultDataPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.components; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackHeadersToolbar; import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; @@ -7,21 +10,28 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDat import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar; import org.apache.wicket.markup.ComponentTag; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - public class DefaultDataPanel extends DataTable { - private static final long DEFAULT_ROWS_PER_PAGE = 100L; - private static final List ROWS_PER_PAGE_OPTIONS = Collections.unmodifiableList(Arrays.asList(20L, 100L, 500L, 1000L)); - public DefaultDataPanel(final String id, final List> columns, final ISortableDataProvider provider) { + private static final long DEFAULT_ROWS_PER_PAGE = 100L; + private static final List ROWS_PER_PAGE_OPTIONS = Collections.unmodifiableList( + Arrays.asList(20L, 100L, 500L, 1000L) + ); + + public DefaultDataPanel( + final String id, + final List> columns, + final ISortableDataProvider provider + ) { this(id, columns, provider, DEFAULT_ROWS_PER_PAGE); } - public DefaultDataPanel(final String id, final List> columns, final ISortableDataProvider dataProvider, final long rowsPerPage) { + public DefaultDataPanel( + final String id, + final List> columns, + final ISortableDataProvider dataProvider, + final long rowsPerPage + ) { super(id, columns, dataProvider, rowsPerPage); - addTopToolbar(new ResizeableNavigationToolbar(this, ROWS_PER_PAGE_OPTIONS)); addTopToolbar(new AjaxFallbackHeadersToolbar<>(this, dataProvider)); addBottomToolbar(new NoRecordsToolbar(this)); diff --git a/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2Choice.java b/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2Choice.java index b7e23d351e..fb2b8de898 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2Choice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2Choice.java @@ -6,6 +6,7 @@ import org.wicketstuff.select2.Select2Choice; import org.wicketstuff.select2.Settings; public class DefaultSelect2Choice extends Select2Choice { + public DefaultSelect2Choice(String id, IModel model, ChoiceProvider provider) { super(id, model, provider); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2MultiChoice.java b/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2MultiChoice.java index 909ded2d79..af43efad7e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2MultiChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DefaultSelect2MultiChoice.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.components; +import java.util.*; import org.apache.wicket.model.IModel; import org.wicketstuff.select2.ChoiceProvider; import org.wicketstuff.select2.Select2MultiChoice; -import java.util.*; - public class DefaultSelect2MultiChoice extends Select2MultiChoice { + public DefaultSelect2MultiChoice(String id, IModel> model, ChoiceProvider provider) { super(id, model, provider); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/DisableSubmitButtonsOnSubmit.java b/view/src/main/java/se/su/dsv/scipro/components/DisableSubmitButtonsOnSubmit.java index 119359b2f6..77fc7a0ace 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DisableSubmitButtonsOnSubmit.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DisableSubmitButtonsOnSubmit.java @@ -10,6 +10,7 @@ import org.apache.wicket.markup.html.form.Form; * {@link Form} behavior that disables all elements with {@code [type=submit]} when the form is submitted. */ public class DisableSubmitButtonsOnSubmit extends Behavior { + @Override public void bind(Component component) { super.bind(component); @@ -21,12 +22,13 @@ public class DisableSubmitButtonsOnSubmit extends Behavior { @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); - final String javaScript = """ - const submitButtons = event.target.querySelectorAll("[type=submit]"); - for (const button of submitButtons) { - button.classList.add('disabled'); - } - """; + final String javaScript = + """ + const submitButtons = event.target.querySelectorAll("[type=submit]"); + for (const button of submitButtons) { + button.classList.add('disabled'); + } + """; response.render(OnEventHeaderItem.forComponent(component, "submit", javaScript)); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/DisplayMultiplesPanel.java b/view/src/main/java/se/su/dsv/scipro/components/DisplayMultiplesPanel.java index acf5e37128..85ff507a0e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/DisplayMultiplesPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/DisplayMultiplesPanel.java @@ -1,25 +1,28 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; -import java.util.List; - public abstract class DisplayMultiplesPanel extends Panel { + public abstract Component getComponent(String componentId, IModel t); + public DisplayMultiplesPanel(String id, IModel> model) { super(id, model); - add(new ListView<>(LIST, model) { - @Override - protected void populateItem(ListItem item) { - item.add(getComponent(COMPONENT, item.getModel())); + add( + new ListView<>(LIST, model) { + @Override + protected void populateItem(ListItem item) { + item.add(getComponent(COMPONENT, item.getModel())); + } } - }); + ); } public static final String LIST = "list"; public static final String COMPONENT = "component"; -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoComplete.java index 42cb929ae4..69bac125cc 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoComplete.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.components; +import java.util.EnumSet; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; -import java.util.EnumSet; - public abstract class EmployeeAutoComplete extends UserAutoComplete { protected EmployeeAutoComplete(String id, IModel model) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoCompleteDivPanel.java b/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoCompleteDivPanel.java index ae0cd320f0..85d8d04367 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoCompleteDivPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/EmployeeAutoCompleteDivPanel.java @@ -25,8 +25,9 @@ public abstract class EmployeeAutoCompleteDivPanel extends Panel { protected void action(AjaxRequestTarget target, User newSelection) { onNewEmployeeSelection(target, newSelection); } + @Override - public boolean getAllowClear(){ + public boolean getAllowClear() { return allowClear(); } }; diff --git a/view/src/main/java/se/su/dsv/scipro/components/EnumModel.java b/view/src/main/java/se/su/dsv/scipro/components/EnumModel.java index c2df4e3540..f6e391d829 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/EnumModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/EnumModel.java @@ -5,6 +5,7 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.util.lang.Classes; public class EnumModel> implements IModel { + private final Component component; private final IModel model; diff --git a/view/src/main/java/se/su/dsv/scipro/components/ExportableDataPanel.java b/view/src/main/java/se/su/dsv/scipro/components/ExportableDataPanel.java index 8ca6f75c0d..628fc5c644 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ExportableDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ExportableDataPanel.java @@ -1,21 +1,29 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider; import org.apache.wicket.extensions.markup.html.repeater.data.table.export.ExportToolbar; import org.apache.wicket.model.Model; import se.su.dsv.scipro.io.ExcelExporter; -import java.util.List; - public class ExportableDataPanel extends DefaultDataPanel { - public ExportableDataPanel(String id, List> columns, ISortableDataProvider dataProvider) { + + public ExportableDataPanel( + String id, + List> columns, + ISortableDataProvider dataProvider + ) { super(id, columns, dataProvider); } @Override protected void onInitialize() { super.onInitialize(); - addBottomToolbar(new ExportToolbar(this, new Model<>("Download as"), new Model<>("excel")).addDataExporter(new ExcelExporter())); + addBottomToolbar( + new ExportToolbar(this, new Model<>("Download as"), new Model<>("excel")).addDataExporter( + new ExcelExporter() + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/GenericPagingNavigator.java b/view/src/main/java/se/su/dsv/scipro/components/GenericPagingNavigator.java index 41cac2225a..46842a8346 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/GenericPagingNavigator.java +++ b/view/src/main/java/se/su/dsv/scipro/components/GenericPagingNavigator.java @@ -4,6 +4,7 @@ import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable; public class GenericPagingNavigator extends AjaxPagingNavigator { + public GenericPagingNavigator(String navigatorId, DataTable table) { super(navigatorId, table); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/IdeaMailChoice.java b/view/src/main/java/se/su/dsv/scipro/components/IdeaMailChoice.java index edee9b60e3..67911fe07f 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/IdeaMailChoice.java +++ b/view/src/main/java/se/su/dsv/scipro/components/IdeaMailChoice.java @@ -1,26 +1,26 @@ package se.su.dsv.scipro.components; +import java.util.Arrays; import org.apache.wicket.model.Model; import se.su.dsv.scipro.data.enums.MailChoice; -import java.util.Arrays; - public class IdeaMailChoice extends BootstrapRadioChoice { - - public IdeaMailChoice(String id) { - super(id); - initChoices(); - setModel(Model.of(MailChoice.THESIS_SUPPORT)); - } + + public IdeaMailChoice(String id) { + super(id); + initChoices(); + setModel(Model.of(MailChoice.THESIS_SUPPORT)); + } private void initChoices() { - setChoices(Arrays.asList( - MailChoice.THESIS_SUPPORT, - MailChoice.AUTHORS_SUBMITTED_IDEA, - MailChoice.AUTHORS_MATCHED_IDEA, - MailChoice.SUPERVISORS_SUBMITTED_IDEA, - MailChoice.SUPERVISORS_MATCHED_IDEA - )); - } - + setChoices( + Arrays.asList( + MailChoice.THESIS_SUPPORT, + MailChoice.AUTHORS_SUBMITTED_IDEA, + MailChoice.AUTHORS_MATCHED_IDEA, + MailChoice.SUPERVISORS_SUBMITTED_IDEA, + MailChoice.SUPERVISORS_MATCHED_IDEA + ) + ); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/InfoPanel.java b/view/src/main/java/se/su/dsv/scipro/components/InfoPanel.java index 567b84c4e4..e4484b37f9 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/InfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/InfoPanel.java @@ -16,12 +16,11 @@ public class InfoPanel extends GenericPanel { public InfoPanel(String id, IModel model) { super(id, model); - final WebMarkupContainer container = new WebMarkupContainer(CONTAINER); container.setOutputMarkupId(true); add(container); - final SmartLinkMultiLineLabel info = new SmartLinkMultiLineLabel(INFO, model){ + final SmartLinkMultiLineLabel info = new SmartLinkMultiLineLabel(INFO, model) { @Override protected void onConfigure() { super.onConfigure(); @@ -30,12 +29,14 @@ public class InfoPanel extends GenericPanel { }; container.add(info); - container.add(new AjaxLink(SHOW) { - @Override - public void onClick(AjaxRequestTarget target) { - target.add(container); - infoVisible = !infoVisible; + container.add( + new AjaxLink(SHOW) { + @Override + public void onClick(AjaxRequestTarget target) { + target.add(container); + infoVisible = !infoVisible; + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/KeywordAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/KeywordAutoComplete.java index 9d4530efbd..c1944c42e6 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/KeywordAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/KeywordAutoComplete.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.components; -import org.apache.wicket.model.Model; -import org.wicketstuff.select2.ChoiceProvider; -import org.wicketstuff.select2.Response; -import se.su.dsv.scipro.match.Keyword; -import se.su.dsv.scipro.match.KeywordService; - import jakarta.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.apache.wicket.model.Model; +import org.wicketstuff.select2.ChoiceProvider; +import org.wicketstuff.select2.Response; +import se.su.dsv.scipro.match.Keyword; +import se.su.dsv.scipro.match.KeywordService; public abstract class KeywordAutoComplete extends AjaxAutoCompleteChoice { @@ -51,7 +50,7 @@ public abstract class KeywordAutoComplete extends AjaxAutoCompleteChoice toChoices(Collection ids) { List keywords = new ArrayList<>(); - for(String id : ids) { + for (String id : ids) { keywords.add(keywordService.findOne(Long.valueOf(id))); } return keywords; diff --git a/view/src/main/java/se/su/dsv/scipro/components/LargeModalWindow.java b/view/src/main/java/se/su/dsv/scipro/components/LargeModalWindow.java index 52d76c5b45..ebafc0b53a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/LargeModalWindow.java +++ b/view/src/main/java/se/su/dsv/scipro/components/LargeModalWindow.java @@ -1,7 +1,8 @@ package se.su.dsv.scipro.components; public class LargeModalWindow extends ModalWindowPlus { + public LargeModalWindow(final String id) { super(id); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/LinkWrapper.java b/view/src/main/java/se/su/dsv/scipro/components/LinkWrapper.java index 9167452e7b..5da3ca1d67 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/LinkWrapper.java +++ b/view/src/main/java/se/su/dsv/scipro/components/LinkWrapper.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.components; +import java.util.function.Function; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.panel.Panel; -import java.util.function.Function; - public final class LinkWrapper extends Panel { + private LinkWrapper(final String id) { super(id); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/ListAdapterModel.java b/view/src/main/java/se/su/dsv/scipro/components/ListAdapterModel.java index 4a00f47af6..e9e44b353d 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ListAdapterModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ListAdapterModel.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.components; -import org.apache.wicket.model.IModel; - import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.apache.wicket.model.IModel; public class ListAdapterModel implements IModel> { + private final IModel> collectionModel; public ListAdapterModel(IModel> collectionModel) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/ListField.java b/view/src/main/java/se/su/dsv/scipro/components/ListField.java index 2bda4d962d..64cbd7c17a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ListField.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ListField.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.components; -import org.apache.wicket.markup.html.form.TextField; -import org.apache.wicket.model.IModel; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; +import org.apache.wicket.markup.html.form.TextField; +import org.apache.wicket.model.IModel; public class ListField extends TextField> { @@ -16,7 +15,6 @@ public class ListField extends TextField> { public ListField(String id, IModel> model, Class type) { super(id, model); - this.type = type; } @@ -31,7 +29,7 @@ public class ListField extends TextField> { @Override protected String getModelValue() { StringBuilder value = new StringBuilder(); - for (Iterator iterator = getModelObject().iterator(); iterator.hasNext(); ) { + for (Iterator iterator = getModelObject().iterator(); iterator.hasNext();) { value.append(convertToString(iterator.next(), getLocale())); if (iterator.hasNext()) { value.append(SEPARATOR); diff --git a/view/src/main/java/se/su/dsv/scipro/components/MaxLengthLabel.java b/view/src/main/java/se/su/dsv/scipro/components/MaxLengthLabel.java index edfdd48ab9..e61ea8fbaf 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/MaxLengthLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/MaxLengthLabel.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.components; +import java.util.Locale; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.util.convert.IConverter; -import java.util.Locale; - public class MaxLengthLabel extends Label { + private final IModel maxLengthModel; public MaxLengthLabel(String id, IModel dataModel, IModel maxLength) { @@ -20,6 +20,7 @@ public class MaxLengthLabel extends Label { } private class MaxLengthConverter implements IConverter { + @Override public String convertToObject(String s, Locale locale) { return s; diff --git a/view/src/main/java/se/su/dsv/scipro/components/ModalWindowPlus.java b/view/src/main/java/se/su/dsv/scipro/components/ModalWindowPlus.java index 0eca546462..83f4b7869b 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ModalWindowPlus.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ModalWindowPlus.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.util.function.Function; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -12,13 +13,10 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.danekja.java.util.function.serializable.SerializableConsumer; -import java.util.function.Function; - public class ModalWindowPlus extends Panel { public ModalWindowPlus(String id) { super(id); - add(AttributeAppender.append("class", "modal")); setOutputMarkupId(true); @@ -87,11 +85,13 @@ public class ModalWindowPlus extends Panel { } public void onClose(SerializableConsumer onClose) { - add(new AjaxEventBehavior("hidden.bs.modal") { - @Override - protected void onEvent(AjaxRequestTarget target) { - onClose.accept(target); + add( + new AjaxEventBehavior("hidden.bs.modal") { + @Override + protected void onEvent(AjaxRequestTarget target) { + onClose.accept(target); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/NoBreakLabel.java b/view/src/main/java/se/su/dsv/scipro/components/NoBreakLabel.java index 309a78ffde..f45188dac0 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/NoBreakLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/NoBreakLabel.java @@ -6,6 +6,7 @@ import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; public class NoBreakLabel extends Label { + public NoBreakLabel(String id, IModel model) { super(id, model); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/NonEmptyLabel.java b/view/src/main/java/se/su/dsv/scipro/components/NonEmptyLabel.java index 27218979e7..eafdf7d01b 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/NonEmptyLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/NonEmptyLabel.java @@ -7,6 +7,7 @@ import org.apache.wicket.model.IModel; * A basic {@link Label} that hides itself if the rendered model object {@link String#isBlank() is blank} */ public class NonEmptyLabel extends Label { + public NonEmptyLabel(String id, IModel model) { super(id, model); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/NullReplacementModel.java b/view/src/main/java/se/su/dsv/scipro/components/NullReplacementModel.java index f028fe4868..08a2f5432f 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/NullReplacementModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/NullReplacementModel.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.components; import org.apache.wicket.model.IModel; public final class NullReplacementModel implements IModel { + private final IModel inner; private final String nullReplacement; diff --git a/view/src/main/java/se/su/dsv/scipro/components/OppositeVisibility.java b/view/src/main/java/se/su/dsv/scipro/components/OppositeVisibility.java index 1b4f15f361..3bb830195e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/OppositeVisibility.java +++ b/view/src/main/java/se/su/dsv/scipro/components/OppositeVisibility.java @@ -4,6 +4,7 @@ import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; public class OppositeVisibility extends Behavior { + private final Component opposite; public OppositeVisibility(Component opposite) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/OrNullModel.java b/view/src/main/java/se/su/dsv/scipro/components/OrNullModel.java index bef23e296a..dea7a79848 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/OrNullModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/OrNullModel.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.components; +import java.util.Optional; import org.apache.wicket.model.IModel; -import java.util.Optional; - public class OrNullModel implements IModel { + private final IModel> nested; public OrNullModel(final IModel> nested) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/ProgramAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/ProgramAutoComplete.java index 595dc85b19..49d3af0ea6 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ProgramAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ProgramAutoComplete.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.components; -import org.apache.wicket.model.IModel; -import org.wicketstuff.select2.ChoiceProvider; -import org.wicketstuff.select2.Response; -import se.su.dsv.scipro.match.ProgramService; -import se.su.dsv.scipro.system.Program; - import jakarta.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.apache.wicket.model.IModel; +import org.wicketstuff.select2.ChoiceProvider; +import org.wicketstuff.select2.Response; +import se.su.dsv.scipro.match.ProgramService; +import se.su.dsv.scipro.system.Program; public abstract class ProgramAutoComplete extends AjaxAutoCompleteChoice { @@ -45,7 +44,7 @@ public abstract class ProgramAutoComplete extends AjaxAutoCompleteChoice toChoices(Collection ids) { List programs = new ArrayList<>(); - for(String id : ids) { + for (String id : ids) { programs.add(programService.findOne(Long.valueOf(id))); } return programs; diff --git a/view/src/main/java/se/su/dsv/scipro/components/ProjectMailChoiceNew.java b/view/src/main/java/se/su/dsv/scipro/components/ProjectMailChoiceNew.java index 3f050a57de..d84cd182f8 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ProjectMailChoiceNew.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ProjectMailChoiceNew.java @@ -1,27 +1,27 @@ package se.su.dsv.scipro.components; +import java.util.Arrays; import org.apache.wicket.model.Model; import se.su.dsv.scipro.data.enums.MailChoice; -import java.util.Arrays; - public class ProjectMailChoiceNew extends BootstrapRadioChoice { - - public ProjectMailChoiceNew(String id) { - super(id); - initChoices(); - setModel(Model.of(MailChoice.THESIS_SUPPORT)); - } + + public ProjectMailChoiceNew(String id) { + super(id); + initChoices(); + setModel(Model.of(MailChoice.THESIS_SUPPORT)); + } private void initChoices() { - setChoices(Arrays.asList( - MailChoice.THESIS_SUPPORT, - MailChoice.AUTHORS_ACTIVE_PROJECT, - MailChoice.ACTIVE_SUPERVISORS, - MailChoice.ACTIVE_CO_SUPERVISORS, - MailChoice.ACTIVE_REVIEWERS, - MailChoice.ALL_FOLLOWERS - )); - } - + setChoices( + Arrays.asList( + MailChoice.THESIS_SUPPORT, + MailChoice.AUTHORS_ACTIVE_PROJECT, + MailChoice.ACTIVE_SUPERVISORS, + MailChoice.ACTIVE_CO_SUPERVISORS, + MailChoice.ACTIVE_REVIEWERS, + MailChoice.ALL_FOLLOWERS + ) + ); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/RedGreenLabel.java b/view/src/main/java/se/su/dsv/scipro/components/RedGreenLabel.java index ce8d35f88f..374a479a83 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/RedGreenLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/RedGreenLabel.java @@ -5,22 +5,31 @@ import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; public class RedGreenLabel extends Panel { - public RedGreenLabel(final String id, final IModel isGreen, final IModel redText, final IModel greenText) { - super(id); - add(new Label("red", redText) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isGreen.getObject()); + public RedGreenLabel( + final String id, + final IModel isGreen, + final IModel redText, + final IModel greenText + ) { + super(id); + add( + new Label("red", redText) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!isGreen.getObject()); + } } - }); - add(new Label("green", greenText) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isGreen.getObject()); + ); + add( + new Label("green", greenText) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isGreen.getObject()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/ResearchAreaChoiceRenderer.java b/view/src/main/java/se/su/dsv/scipro/components/ResearchAreaChoiceRenderer.java index 398706f7ca..a998561775 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ResearchAreaChoiceRenderer.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ResearchAreaChoiceRenderer.java @@ -5,6 +5,7 @@ import org.apache.wicket.markup.html.form.ChoiceRenderer; import se.su.dsv.scipro.system.ResearchArea; public class ResearchAreaChoiceRenderer extends ChoiceRenderer { + private final Component component; /** @@ -18,8 +19,7 @@ public class ResearchAreaChoiceRenderer extends ChoiceRenderer { public Object getDisplayValue(ResearchArea researchArea) { if (researchArea.isDeleted()) { return component.getString("research_area_inactive", () -> researchArea); - } - else { + } else { return component.getString("research_area_active", () -> researchArea); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/ResearchAreasModel.java b/view/src/main/java/se/su/dsv/scipro/components/ResearchAreasModel.java index 69244ae6d3..a11366292a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ResearchAreasModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ResearchAreasModel.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.components; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.model.LoadableDetachableModel; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.ResearchAreaService; -import java.util.Comparator; -import java.util.List; - public class ResearchAreasModel extends LoadableDetachableModel> { + private final ResearchAreaService researchAreaService; public ResearchAreasModel(ResearchAreaService researchAreaService) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/ResizeableNavigationToolbar.java b/view/src/main/java/se/su/dsv/scipro/components/ResizeableNavigationToolbar.java index 628ac58710..52340f451e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ResizeableNavigationToolbar.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ResizeableNavigationToolbar.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.components; +import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractToolbar; @@ -8,30 +9,32 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigatorLab import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.LambdaModel; -import java.util.List; - public class ResizeableNavigationToolbar extends AbstractToolbar { public ResizeableNavigationToolbar(DataTable table, List itemsPerPageChoices) { super(table); - table.setOutputMarkupId(true); WebMarkupContainer cell = new WebMarkupContainer("span"); cell.add(AttributeModifier.replace("colspan", () -> getTable().getColumns().size())); - cell.add(new NavigatorLabel("navigatorLabel", table)); cell.add(new GenericPagingNavigator("navigator", table)); - cell.add(new AjaxDropDownChoice<>("rows", LambdaModel.of(table::getItemsPerPage, table::setItemsPerPage), itemsPerPageChoices) { - @Override - public void onNewSelection(AjaxRequestTarget target, Long objectSelected) { - target.add(getTable()); + cell.add( + new AjaxDropDownChoice<>( + "rows", + LambdaModel.of(table::getItemsPerPage, table::setItemsPerPage), + itemsPerPageChoices + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, Long objectSelected) { + target.add(getTable()); + } } - }); + ); add(cell); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/ScrollIntoView.java b/view/src/main/java/se/su/dsv/scipro/components/ScrollIntoView.java index ca9a4b0afb..2de6197f63 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ScrollIntoView.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ScrollIntoView.java @@ -6,6 +6,7 @@ import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; public class ScrollIntoView extends Behavior { + private Component component; public ScrollIntoView(Component component) { @@ -20,8 +21,12 @@ public class ScrollIntoView extends Behavior { @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); - response.render(OnDomReadyHeaderItem.forScript( + response.render( + OnDomReadyHeaderItem.forScript( "document.getElementById('%s').scrollIntoView({behavior:\"instant\"})".formatted( - this.component.getMarkupId(true)))); + this.component.getMarkupId(true) + ) + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/ScrollSneakBehavior.java b/view/src/main/java/se/su/dsv/scipro/components/ScrollSneakBehavior.java index 92b7ddd04a..5d7dcaf4c6 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/ScrollSneakBehavior.java +++ b/view/src/main/java/se/su/dsv/scipro/components/ScrollSneakBehavior.java @@ -6,10 +6,13 @@ import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; public class ScrollSneakBehavior extends Behavior { + @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); - response.render(OnDomReadyHeaderItem.forScript(""" + response.render( + OnDomReadyHeaderItem.forScript( + """ (function() { var sneaky = new ScrollSneak(location.hostname); document.getElementById('%s').addEventListener('click', function() { @@ -17,6 +20,7 @@ public class ScrollSneakBehavior extends Behavior { }); })(); """.formatted(component.getMarkupId()) - )); + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/components/SmarterLinkMultiLineLabel.java b/view/src/main/java/se/su/dsv/scipro/components/SmarterLinkMultiLineLabel.java index 8ef4192614..17d770f541 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/SmarterLinkMultiLineLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/SmarterLinkMultiLineLabel.java @@ -7,6 +7,7 @@ import org.apache.wicket.extensions.markup.html.basic.SmartLinkMultiLineLabel; import org.apache.wicket.model.IModel; public class SmarterLinkMultiLineLabel extends SmartLinkMultiLineLabel { + public SmarterLinkMultiLineLabel(String id, IModel model) { super(id, model); } @@ -17,6 +18,7 @@ public class SmarterLinkMultiLineLabel extends SmartLinkMultiLineLabel { } private static class EscapedLinkParser extends LinkParser { + /** * Copied from {@link org.apache.wicket.extensions.markup.html.basic.DefaultLinkParser} */ diff --git a/view/src/main/java/se/su/dsv/scipro/components/SortOrderPanel.java b/view/src/main/java/se/su/dsv/scipro/components/SortOrderPanel.java index 3c4db83ae1..6b859d2ce9 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/SortOrderPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/SortOrderPanel.java @@ -13,24 +13,27 @@ public class SortOrderPanel extends Panel { public SortOrderPanel(String id, IModel model, SortOrderService service) { super(id); - this.orderService = service; this.objectModel = model; - add(new AjaxLink(MOVE_UP) { - @Override - public void onClick(AjaxRequestTarget target) { - orderService.moveUp(objectModel.getObject()); - setResponsePage(getPage()); + add( + new AjaxLink(MOVE_UP) { + @Override + public void onClick(AjaxRequestTarget target) { + orderService.moveUp(objectModel.getObject()); + setResponsePage(getPage()); + } } - }); - add(new AjaxLink(MOVE_DOWN) { - @Override - public void onClick(AjaxRequestTarget target) { - orderService.moveDown(objectModel.getObject()); - setResponsePage(getPage()); + ); + add( + new AjaxLink(MOVE_DOWN) { + @Override + public void onClick(AjaxRequestTarget target) { + orderService.moveDown(objectModel.getObject()); + setResponsePage(getPage()); + } } - }); + ); } static final String MOVE_UP = "moveUp"; diff --git a/view/src/main/java/se/su/dsv/scipro/components/StatelessModel.java b/view/src/main/java/se/su/dsv/scipro/components/StatelessModel.java index 6a1ddd3e34..3312a15751 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/StatelessModel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/StatelessModel.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.components; import org.apache.wicket.model.LoadableDetachableModel; public final class StatelessModel extends LoadableDetachableModel { + @Override protected T load() { return null; diff --git a/view/src/main/java/se/su/dsv/scipro/components/SupervisorAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/SupervisorAutoComplete.java index 6900d1dcec..06adb97353 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/SupervisorAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/SupervisorAutoComplete.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.components; +import jakarta.inject.Inject; +import java.util.EnumSet; import org.apache.wicket.model.IModel; import org.wicketstuff.select2.ChoiceProvider; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchService; -import jakarta.inject.Inject; -import java.util.EnumSet; - public class SupervisorAutoComplete extends AutoCompleteChoice { @Inject diff --git a/view/src/main/java/se/su/dsv/scipro/components/TemporalColumn.java b/view/src/main/java/se/su/dsv/scipro/components/TemporalColumn.java index 59cd728412..56bbebf42a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/TemporalColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/components/TemporalColumn.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.components; +import java.time.temporal.Temporal; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.danekja.java.util.function.serializable.SerializableFunction; -import java.time.temporal.Temporal; - public class TemporalColumn extends LambdaColumn { + public TemporalColumn(IModel displayModel, SerializableFunction function) { super(displayModel, function); } diff --git a/view/src/main/java/se/su/dsv/scipro/components/UploadFormPanel.java b/view/src/main/java/se/su/dsv/scipro/components/UploadFormPanel.java index f8145ce2b3..da6c9334a0 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/UploadFormPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/components/UploadFormPanel.java @@ -8,8 +8,9 @@ import org.apache.wicket.markup.html.panel.Panel; * Like: add(new UploadFormPanel(new AbstractUploadForm(){...implementation....})); */ public class UploadFormPanel extends Panel { - public UploadFormPanel(final String id, final AbstractUploadForm form){ - super(id); - add(form); - } -} \ No newline at end of file + + public UploadFormPanel(final String id, final AbstractUploadForm form) { + super(id); + add(form); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/components/UserAutoComplete.java b/view/src/main/java/se/su/dsv/scipro/components/UserAutoComplete.java index 52dff9974d..4e3c268676 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/UserAutoComplete.java +++ b/view/src/main/java/se/su/dsv/scipro/components/UserAutoComplete.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.components; +import jakarta.inject.Inject; +import java.util.EnumSet; import org.apache.wicket.model.IModel; import org.wicketstuff.select2.ChoiceProvider; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchService; -import jakarta.inject.Inject; -import java.util.EnumSet; - public abstract class UserAutoComplete extends AjaxAutoCompleteChoice { @Inject diff --git a/view/src/main/java/se/su/dsv/scipro/components/datatables/MultipleUsersColumn.java b/view/src/main/java/se/su/dsv/scipro/components/datatables/MultipleUsersColumn.java index db2e48fa66..7cd59335c8 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/datatables/MultipleUsersColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/components/datatables/MultipleUsersColumn.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.components.datatables; +import java.util.List; +import java.util.stream.Collectors; import org.apache.wicket.Component; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; @@ -9,32 +11,31 @@ import se.su.dsv.scipro.components.DisplayMultiplesPanel; import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; -import java.util.List; -import java.util.stream.Collectors; - public abstract class MultipleUsersColumn extends AbstractExportableColumn { + public MultipleUsersColumn(final IModel displayModel) { super(displayModel); } @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, getUsers(rowModel)) { - @Override - public Component getComponent(final String componentId, final IModel t) { - return new UserLinkPanel(componentId, t); + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>(componentId, getUsers(rowModel)) { + @Override + public Component getComponent(final String componentId, final IModel t) { + return new UserLinkPanel(componentId, t); + } } - }); + ); } @Override public IModel getDataModel(final IModel rowModel) { - return () -> - getUsers(rowModel) - .getObject() - .stream() - .map(User::getFullName) - .collect(Collectors.joining(", ")); + return () -> getUsers(rowModel).getObject().stream().map(User::getFullName).collect(Collectors.joining(", ")); } protected abstract IModel> getUsers(final IModel rowModel); diff --git a/view/src/main/java/se/su/dsv/scipro/components/datatables/UserColumn.java b/view/src/main/java/se/su/dsv/scipro/components/datatables/UserColumn.java index bc3c46f4a8..9f2a557510 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/datatables/UserColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/components/datatables/UserColumn.java @@ -9,6 +9,7 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; public class UserColumn extends AbstractExportableColumn { + private final SerializableFunction toUser; public UserColumn(final IModel displayModel, final SerializableFunction toUser) { diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlight.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlight.java index 2c96855f11..6e041c9ec4 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlight.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlight.java @@ -4,8 +4,6 @@ package se.su.dsv.scipro.components.menuhighlighting; * Base interface only signaling intent (mixin pattern), that is if a menu item needs to be highlighted. * Should preferably not be used directly, subclass it instead so intent is clear. * Should probably be refactored into an annotation-based implementation instead. - * + * */ -public interface MenuHighlight { - -} +public interface MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightActivityPlan.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightActivityPlan.java index 86badc6020..413c2a6ac4 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightActivityPlan.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightActivityPlan.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightActivityPlan extends MenuHighlight { -} +public interface MenuHighlightActivityPlan extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminActivityPlanTemplates.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminActivityPlanTemplates.java index bb168aeb40..764e2aca51 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminActivityPlanTemplates.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminActivityPlanTemplates.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAdminActivityPlanTemplates extends MenuHighlight { -} +public interface MenuHighlightAdminActivityPlanTemplates extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminApplicationPeriod.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminApplicationPeriod.java index 88f8f3db08..7c8f467756 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminApplicationPeriod.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminApplicationPeriod.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAdminApplicationPeriod extends MenuHighlight { -} +public interface MenuHighlightAdminApplicationPeriod extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminAuthorStatistics.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminAuthorStatistics.java index 8002521191..78c0e9b43d 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminAuthorStatistics.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminAuthorStatistics.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightAdminAuthorStatistics extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightAdminAuthorStatistics extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminChecklist.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminChecklist.java index fca3b8d865..7519b7a8a9 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminChecklist.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminChecklist.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAdminChecklist extends MenuHighlight { -} +public interface MenuHighlightAdminChecklist extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminFinalSeminars.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminFinalSeminars.java index 9640343d28..f3b4f94811 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminFinalSeminars.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminFinalSeminars.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAdminFinalSeminars extends MenuHighlight { -} +public interface MenuHighlightAdminFinalSeminars extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminMileStoneStatistics.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminMileStoneStatistics.java index d3892c20fb..0480b11bfa 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminMileStoneStatistics.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminMileStoneStatistics.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightAdminMileStoneStatistics extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightAdminMileStoneStatistics extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminPeer.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminPeer.java index 973d8aa426..11e63bbbaf 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminPeer.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminPeer.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAdminPeer extends MenuHighlight { -} +public interface MenuHighlightAdminPeer extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminProjectManagement.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminProjectManagement.java index 0ede800aca..89c400ed0e 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminProjectManagement.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAdminProjectManagement.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightAdminProjectManagement extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightAdminProjectManagement extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorFinalSeminars.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorFinalSeminars.java index 156d15ba48..27e2411fc6 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorFinalSeminars.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorFinalSeminars.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightAuthorFinalSeminars extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightAuthorFinalSeminars extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyGroups.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyGroups.java index 96b43de440..6dfe097f60 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyGroups.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyGroups.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightAuthorMyGroups extends MenuHighlight { -} +public interface MenuHighlightAuthorMyGroups extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyProjects.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyProjects.java index f41e1685d4..bb7a1a98f4 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyProjects.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorMyProjects.java @@ -4,6 +4,4 @@ package se.su.dsv.scipro.components.menuhighlighting; * Used to highlight hierarchy for My Projects in the author view. * */ -public interface MenuHighlightAuthorMyProjects extends MenuHighlight { - -} +public interface MenuHighlightAuthorMyProjects extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorOpposition.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorOpposition.java index 8e7cd1eb33..bb10768a29 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorOpposition.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightAuthorOpposition.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightAuthorOpposition extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightAuthorOpposition extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightFinalSeminar.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightFinalSeminar.java index 4f71f59980..408521567b 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightFinalSeminar.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightFinalSeminar.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightFinalSeminar extends MenuHighlight { -} +public interface MenuHighlightFinalSeminar extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightForum.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightForum.java index 0f7fd385f4..dc76e3bd3a 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightForum.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightForum.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightForum extends MenuHighlight { -} +public interface MenuHighlightForum extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectIdeas.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectIdeas.java index a0f6c501cb..15a8112136 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectIdeas.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectIdeas.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightProjectIdeas extends MenuHighlight { -} +public interface MenuHighlightProjectIdeas extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectMyIdeas.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectMyIdeas.java index bf0be5645a..71bbcba8f7 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectMyIdeas.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightProjectMyIdeas.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightProjectMyIdeas extends MenuHighlight { -} +public interface MenuHighlightProjectMyIdeas extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityPlan.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityPlan.java index 338cd8bd4d..c4d5638896 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityPlan.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityPlan.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightSupervisorActivityPlan extends MenuHighlight { -} +public interface MenuHighlightSupervisorActivityPlan extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityTemplates.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityTemplates.java index bbe378ae60..d86f77ffee 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityTemplates.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorActivityTemplates.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightSupervisorActivityTemplates extends MenuHighlight { -} +public interface MenuHighlightSupervisorActivityTemplates extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllPeers.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllPeers.java index b8c275cb2e..4d2661e10f 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllPeers.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllPeers.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightSupervisorAllPeers extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightSupervisorAllPeers extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllProjects.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllProjects.java index 2c5a4dd120..1d0b0200b8 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllProjects.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorAllProjects.java @@ -4,6 +4,4 @@ package se.su.dsv.scipro.components.menuhighlighting; * Used to highlight hierarchy for My Projects in Supervisor view. * */ -public interface MenuHighlightSupervisorAllProjects extends MenuHighlight { - -} +public interface MenuHighlightSupervisorAllProjects extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorFinalSeminars.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorFinalSeminars.java index f0cb7e655d..c5459a17b1 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorFinalSeminars.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorFinalSeminars.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightSupervisorFinalSeminars extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightSupervisorFinalSeminars extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorGradingReport.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorGradingReport.java index 46804f604b..7bf3857a81 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorGradingReport.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorGradingReport.java @@ -1,4 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightSupervisorGradingReport extends MenuHighlight { -} +public interface MenuHighlightSupervisorGradingReport extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMilestoneStatistics.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMilestoneStatistics.java index c81790b30f..e99fc52781 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMilestoneStatistics.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMilestoneStatistics.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightSupervisorMilestoneStatistics extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightSupervisorMilestoneStatistics extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyGroups.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyGroups.java index a5b58140d0..5c9609a1d6 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyGroups.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyGroups.java @@ -4,5 +4,4 @@ package se.su.dsv.scipro.components.menuhighlighting; * Used to highlight hierarchy for My groups in Supervisor view. * */ -public interface MenuHighlightSupervisorMyGroups extends MenuHighlight { -} +public interface MenuHighlightSupervisorMyGroups extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyIdeas.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyIdeas.java index 87627721b7..f074a93a65 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyIdeas.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyIdeas.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.components.menuhighlighting; - -public interface MenuHighlightSupervisorMyIdeas extends MenuHighlight { -} +package se.su.dsv.scipro.components.menuhighlighting; + +public interface MenuHighlightSupervisorMyIdeas extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyProjects.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyProjects.java index dd4a40cf43..46a000f717 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyProjects.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorMyProjects.java @@ -4,6 +4,4 @@ package se.su.dsv.scipro.components.menuhighlighting; * Used to highlight hierarchy for My Projects in Supervisor view. * */ -public interface MenuHighlightSupervisorMyProjects extends MenuHighlight { - -} +public interface MenuHighlightSupervisorMyProjects extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorOverview.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorOverview.java index 7b53af4fcc..df54068fc8 100644 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorOverview.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorOverview.java @@ -4,5 +4,4 @@ package se.su.dsv.scipro.components.menuhighlighting; * Created with IntelliJ IDEA. User: fred-fri Date: 5/30/13 Time: 2:42 PM To change this template use File | Settings | * File Templates. */ -public interface MenuHighlightSupervisorOverview extends MenuHighlight { -} +public interface MenuHighlightSupervisorOverview extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorProjectIdea.java b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorProjectIdea.java index 0623ca542b..170b3d3581 100755 --- a/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorProjectIdea.java +++ b/view/src/main/java/se/su/dsv/scipro/components/menuhighlighting/MenuHighlightSupervisorProjectIdea.java @@ -1,5 +1,3 @@ package se.su.dsv.scipro.components.menuhighlighting; -public interface MenuHighlightSupervisorProjectIdea extends MenuHighlight { - -} +public interface MenuHighlightSupervisorProjectIdea extends MenuHighlight {} diff --git a/view/src/main/java/se/su/dsv/scipro/crosscutting/ForwardPhase2Feedback.java b/view/src/main/java/se/su/dsv/scipro/crosscutting/ForwardPhase2Feedback.java index e77e8864c4..87db35401c 100644 --- a/view/src/main/java/se/su/dsv/scipro/crosscutting/ForwardPhase2Feedback.java +++ b/view/src/main/java/se/su/dsv/scipro/crosscutting/ForwardPhase2Feedback.java @@ -2,6 +2,9 @@ package se.su.dsv.scipro.crosscutting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import java.util.HashSet; +import java.util.Set; import org.apache.wicket.Application; import org.apache.wicket.Localizer; import org.apache.wicket.model.Model; @@ -13,28 +16,22 @@ import se.su.dsv.scipro.reviewing.ReviewerApproval; import se.su.dsv.scipro.reviewing.RoughDraftApprovalApprovedEvent; import se.su.dsv.scipro.reviewing.RoughDraftApprovalRejectedEvent; -import jakarta.inject.Inject; -import java.util.HashSet; -import java.util.Set; - public class ForwardPhase2Feedback { + private final Application application; private final ProjectForumService projectForumService; - public ForwardPhase2Feedback( - Application application, - ProjectForumService projectForumService) - { + public ForwardPhase2Feedback(Application application, ProjectForumService projectForumService) { this.application = application; this.projectForumService = projectForumService; } @Inject public ForwardPhase2Feedback( - WebApplication application, - ProjectForumService projectForumService, - EventBus eventBus) - { + WebApplication application, + ProjectForumService projectForumService, + EventBus eventBus + ) { this(application, projectForumService); eventBus.register(this); } @@ -60,10 +57,11 @@ public class ForwardPhase2Feedback { } private static Set getAttachments(ReviewerApproval reviewerApproval) { - return reviewerApproval.getCurrentAttachment() - .map(FileReference::getFileDescription) - .map(Attachment::existing) - .map(Set::of) - .orElseGet(Set::of); + return reviewerApproval + .getCurrentAttachment() + .map(FileReference::getFileDescription) + .map(Attachment::existing) + .map(Set::of) + .orElseGet(Set::of); } } diff --git a/view/src/main/java/se/su/dsv/scipro/crosscutting/NotifyFailedReflection.java b/view/src/main/java/se/su/dsv/scipro/crosscutting/NotifyFailedReflection.java index 867703dde2..8ccd579fd9 100644 --- a/view/src/main/java/se/su/dsv/scipro/crosscutting/NotifyFailedReflection.java +++ b/view/src/main/java/se/su/dsv/scipro/crosscutting/NotifyFailedReflection.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro.crosscutting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import jakarta.inject.Inject; +import java.util.Set; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.NotificationController; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; @@ -10,9 +11,8 @@ import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; import se.su.dsv.scipro.reflection.ReflectionImprovementsRequestedEvent; import se.su.dsv.scipro.reflection.ReflectionImprovementsSubmittedEvent; -import java.util.Set; - public class NotifyFailedReflection { + private final NotificationController notificationController; @Inject @@ -26,10 +26,11 @@ public class NotifyFailedReflection { NotificationSource source = new NotificationSource(); source.setMessage(event.supervisorComment()); notificationController.notifyCustomProject( - event.project(), - ProjectEvent.Event.REFLECTION_IMPROVEMENTS_REQUESTED, - source, - Set.of(new Member(event.author(), Member.Type.AUTHOR))); + event.project(), + ProjectEvent.Event.REFLECTION_IMPROVEMENTS_REQUESTED, + source, + Set.of(new Member(event.author(), Member.Type.AUTHOR)) + ); } @Subscribe @@ -38,9 +39,10 @@ public class NotifyFailedReflection { source.setMessage(event.reflection()); source.setAdditionalMessage(event.author().getFullName()); notificationController.notifyCustomProject( - event.project(), - ProjectEvent.Event.REFLECTION_IMPROVEMENTS_SUBMITTED, - source, - Set.of(new Member(event.project().getHeadSupervisor(), Member.Type.SUPERVISOR))); + event.project(), + ProjectEvent.Event.REFLECTION_IMPROVEMENTS_SUBMITTED, + source, + Set.of(new Member(event.project().getHeadSupervisor(), Member.Type.SUPERVISOR)) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotifications.java b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotifications.java index c0111caf10..349cdd6ad9 100644 --- a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotifications.java +++ b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotifications.java @@ -2,6 +2,9 @@ package se.su.dsv.scipro.crosscutting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.function.Consumer; import se.su.dsv.scipro.notifications.NotificationController; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; @@ -10,20 +13,18 @@ import se.su.dsv.scipro.reviewing.FinalSeminarApprovalService; import se.su.dsv.scipro.reviewing.ReviewerApproval; import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import java.util.function.Consumer; - @Singleton public class ReviewerAssignedNotifications { + private final RoughDraftApprovalService roughDraftApprovalService; private final FinalSeminarApprovalService finalSeminarApprovalService; private final NotificationController notificationController; ReviewerAssignedNotifications( - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService, - NotificationController notificationController) { + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService, + NotificationController notificationController + ) { this.roughDraftApprovalService = roughDraftApprovalService; this.finalSeminarApprovalService = finalSeminarApprovalService; this.notificationController = notificationController; @@ -31,26 +32,29 @@ public class ReviewerAssignedNotifications { @Inject public ReviewerAssignedNotifications( - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService, - NotificationController notificationController, - EventBus eventBus) { + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService, + NotificationController notificationController, + EventBus eventBus + ) { this(roughDraftApprovalService, finalSeminarApprovalService, notificationController); eventBus.register(this); } @Subscribe public void reviewerAssigned(ReviewerAssignedEvent event) { - roughDraftApprovalService.findBy(event.getProject()) - .filter(rda -> !rda.isDecided()) - .ifPresent(sendNotification(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED)); + roughDraftApprovalService + .findBy(event.getProject()) + .filter(rda -> !rda.isDecided()) + .ifPresent(sendNotification(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED)); - finalSeminarApprovalService.findBy(event.getProject()) - .filter(fsa -> !fsa.isDecided()) - .ifPresent(sendNotification(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED)); + finalSeminarApprovalService + .findBy(event.getProject()) + .filter(fsa -> !fsa.isDecided()) + .ifPresent(sendNotification(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED)); } private Consumer sendNotification(ProjectEvent.Event event) { return approval -> notificationController.notifyProject(approval.getProject(), event, new NotificationSource()); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailer.java b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailer.java index 2fd86978ca..d13bf829c2 100644 --- a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailer.java +++ b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailer.java @@ -2,6 +2,11 @@ package se.su.dsv.scipro.crosscutting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.mail.MailEvent; @@ -12,19 +17,18 @@ import se.su.dsv.scipro.reviewing.FinalSeminarApprovalRequestEvent; import se.su.dsv.scipro.reviewing.RoughDraftApprovalRequestedEvent; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - @Singleton public class ReviewerSupportMailer { + private final MailEventService mailEventService; private final GeneralSystemSettingsService systemSettingsService; @Inject - public ReviewerSupportMailer(final EventBus eventBus, MailEventService mailEventService, GeneralSystemSettingsService systemSettingsService) { + public ReviewerSupportMailer( + final EventBus eventBus, + MailEventService mailEventService, + GeneralSystemSettingsService systemSettingsService + ) { this.mailEventService = mailEventService; this.systemSettingsService = systemSettingsService; eventBus.register(this); @@ -34,7 +38,10 @@ public class ReviewerSupportMailer { public void onFinalSeminarApprovalRequest(final FinalSeminarApprovalRequestEvent finalSeminarApprovalRequestEvent) { final Project project = finalSeminarApprovalRequestEvent.getProject(); if (project.getReviewer() == null) { - final String comment = finalSeminarApprovalRequestEvent.getFinalSeminarApproval().getCurrentDecision().getComment(); + final String comment = finalSeminarApprovalRequestEvent + .getFinalSeminarApproval() + .getCurrentDecision() + .getComment(); sendMailToReviewerSupport(project, comment, ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED); } } @@ -43,7 +50,10 @@ public class ReviewerSupportMailer { public void onRoughDraftApprovalRequest(final RoughDraftApprovalRequestedEvent roughDraftApprovalRequestedEvent) { final Project project = roughDraftApprovalRequestedEvent.getProject(); if (project.getReviewer() == null) { - final String comment = roughDraftApprovalRequestedEvent.getRoughDraftApproval().getCurrentDecision().getComment(); + final String comment = roughDraftApprovalRequestedEvent + .getRoughDraftApproval() + .getCurrentDecision() + .getComment(); sendMailToReviewerSupport(project, comment, ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED); } } @@ -56,15 +66,32 @@ public class ReviewerSupportMailer { mail.setFromName(systemSettings.getMailFromName()); mail.setNonUserRecipients(getReviewerSupport(systemSettings)); mail.setSubject("Important: Reviewer needed!"); - mail.setMessageBody(event.name() + "\n" - + " Project: " + project.getTitle() + "\n" - + " Level: " + project.getProjectType().getName() + "\n" - + " Supervisor: " + project.getHeadSupervisor().getFullName() + "\n" - + " Research area: " + ((project.getResearchArea() == null) ? "N/A" : project.getResearchArea().getTitle()) + "\n" - + " Language: " + (project.getLanguage() != null ? project.getLanguage() : "Unknown") + "\n" - + " Authors: " + project.getProjectParticipants().stream().map(User::getFullName).collect(Collectors.joining(" ,")) + "\n" - + " Comment: " + comment + "\n\n" - + " Assign a reviewer to this project asap!"); + mail.setMessageBody( + event.name() + + "\n" + + " Project: " + + project.getTitle() + + "\n" + + " Level: " + + project.getProjectType().getName() + + "\n" + + " Supervisor: " + + project.getHeadSupervisor().getFullName() + + "\n" + + " Research area: " + + ((project.getResearchArea() == null) ? "N/A" : project.getResearchArea().getTitle()) + + "\n" + + " Language: " + + (project.getLanguage() != null ? project.getLanguage() : "Unknown") + + "\n" + + " Authors: " + + project.getProjectParticipants().stream().map(User::getFullName).collect(Collectors.joining(" ,")) + + "\n" + + " Comment: " + + comment + + "\n\n" + + " Assign a reviewer to this project asap!" + ); mailEventService.save(mail); } diff --git a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewingNotifications.java b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewingNotifications.java index 17b4746f9f..907166612c 100644 --- a/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewingNotifications.java +++ b/view/src/main/java/se/su/dsv/scipro/crosscutting/ReviewingNotifications.java @@ -2,6 +2,8 @@ package se.su.dsv.scipro.crosscutting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; import org.apache.wicket.core.request.handler.BookmarkablePageRequestHandler; import org.apache.wicket.core.request.handler.PageProvider; import org.apache.wicket.protocol.http.WebApplication; @@ -19,17 +21,20 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalApprovedEvent; import se.su.dsv.scipro.reviewing.RoughDraftApprovalRejectedEvent; import se.su.dsv.scipro.reviewing.RoughDraftApprovalRequestedEvent; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; - @Singleton public class ReviewingNotifications { + private final NotificationController notificationController; private final GeneralSystemSettingsService generalSystemSettingsService; private final WebApplication application; @Inject - public ReviewingNotifications(final EventBus eventBus, final NotificationController notificationController, GeneralSystemSettingsService generalSystemSettingsService, WebApplication application) { + public ReviewingNotifications( + final EventBus eventBus, + final NotificationController notificationController, + GeneralSystemSettingsService generalSystemSettingsService, + WebApplication application + ) { this.notificationController = notificationController; this.generalSystemSettingsService = generalSystemSettingsService; this.application = application; @@ -38,38 +43,70 @@ public class ReviewingNotifications { @Subscribe public void onFinalSeminarApprovalRequest(final FinalSeminarApprovalRequestEvent finalSeminarApprovalRequestEvent) { - notificationController.notifyProject(finalSeminarApprovalRequestEvent.getProject(), ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED, new NotificationSource()); + notificationController.notifyProject( + finalSeminarApprovalRequestEvent.getProject(), + ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED, + new NotificationSource() + ); } @Subscribe - public void onFinalSeminarApprovalRejected(final FinalSeminarApprovalRejectedEvent finalSeminarApprovalRejectedEvent) { - notificationController.notifyProject(finalSeminarApprovalRejectedEvent.getProject(), ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REJECTED, new NotificationSource()); + public void onFinalSeminarApprovalRejected( + final FinalSeminarApprovalRejectedEvent finalSeminarApprovalRejectedEvent + ) { + notificationController.notifyProject( + finalSeminarApprovalRejectedEvent.getProject(), + ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REJECTED, + new NotificationSource() + ); } @Subscribe - public void onFinalSeminarApprovalApproved(final FinalSeminarApprovalApprovedEvent finalSeminarApprovalApprovedEvent) { - notificationController.notifyProject(finalSeminarApprovalApprovedEvent.getProject(), ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_APPROVED, new NotificationSource()); + public void onFinalSeminarApprovalApproved( + final FinalSeminarApprovalApprovedEvent finalSeminarApprovalApprovedEvent + ) { + notificationController.notifyProject( + finalSeminarApprovalApprovedEvent.getProject(), + ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_APPROVED, + new NotificationSource() + ); } @Subscribe public void onRoughDraftApprovalRequest(final RoughDraftApprovalRequestedEvent roughDraftApprovalRequestedEvent) { - notificationController.notifyProject(roughDraftApprovalRequestedEvent.getProject(), ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED, new NotificationSource()); + notificationController.notifyProject( + roughDraftApprovalRequestedEvent.getProject(), + ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED, + new NotificationSource() + ); } @Subscribe public void onRoughDraftApprovalRejected(final RoughDraftApprovalRejectedEvent roughDraftApprovalRejectedEvent) { - notificationController.notifyProject(roughDraftApprovalRejectedEvent.getProject(), ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REJECTED, new NotificationSource()); + notificationController.notifyProject( + roughDraftApprovalRejectedEvent.getProject(), + ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REJECTED, + new NotificationSource() + ); } @Subscribe public void onRoughDraftApprovalApproved(final RoughDraftApprovalApprovedEvent roughDraftApprovalApprovedEvent) { - final PageParameters pageParameters = SupervisorGradingPage.getPageParameters(roughDraftApprovalApprovedEvent.getProject()); + final PageParameters pageParameters = SupervisorGradingPage.getPageParameters( + roughDraftApprovalApprovedEvent.getProject() + ); final PageProvider pageProvider = new PageProvider(SupervisorGradingPage.class, pageParameters); - final Url relativeUrl = application.getRootRequestMapper().mapHandler(new BookmarkablePageRequestHandler(pageProvider)); + final Url relativeUrl = application + .getRootRequestMapper() + .mapHandler(new BookmarkablePageRequestHandler(pageProvider)); final String absoluteUrl = makeAbsolute(relativeUrl); final NotificationSource source = new NotificationSource(); source.setMessage(absoluteUrl); - notificationController.notifyProject(roughDraftApprovalApprovedEvent.getProject(), ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_APPROVED, source); + notificationController.notifyProject( + roughDraftApprovalApprovedEvent.getProject(), + ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_APPROVED, + source + ); } private String makeAbsolute(Url relativeUrl) { diff --git a/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModel.java b/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModel.java index 450873c036..b0dbc990e5 100755 --- a/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModel.java +++ b/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModel.java @@ -19,13 +19,11 @@ public final class DetachableServiceModel implements IM public DetachableServiceModel(GenericService service, DO object) { this(service); - setObject(object); } public DetachableServiceModel(GenericService service, Long id) { this(service); - this.id = id; } diff --git a/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModelCollection.java b/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModelCollection.java index dc316e420c..19b4f17be1 100755 --- a/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModelCollection.java +++ b/view/src/main/java/se/su/dsv/scipro/data/DetachableServiceModelCollection.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.data; -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.GenericService; - import java.util.Collection; import java.util.Collections; import java.util.stream.Collectors; +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.GenericService; public final class DetachableServiceModelCollection implements IModel> { @@ -33,9 +32,7 @@ public final class DetachableServiceModelCollection imp @Override public void setObject(Collection object) { attached = true; - ids = object.stream() - .map(DomainObject::getId) - .collect(Collectors.toSet()); + ids = object.stream().map(DomainObject::getId).collect(Collectors.toSet()); this.object = object; } @@ -45,18 +42,14 @@ public final class DetachableServiceModelCollection imp // equal but since Hibernate injects id into the same reference // they are always equal so setObject will never get called. if (attached) { - ids = object.stream() - .map(DomainObject::getId) - .collect(Collectors.toSet()); + ids = object.stream().map(DomainObject::getId).collect(Collectors.toSet()); } attached = false; object = null; } private void reload() { - final Collection objects = ids.stream() - .map(service::findOne) - .collect(Collectors.toSet()); + final Collection objects = ids.stream().map(service::findOne).collect(Collectors.toSet()); setObject(objects); } } diff --git a/view/src/main/java/se/su/dsv/scipro/data/FilteredListModel.java b/view/src/main/java/se/su/dsv/scipro/data/FilteredListModel.java index d13cea9b78..89afcada42 100644 --- a/view/src/main/java/se/su/dsv/scipro/data/FilteredListModel.java +++ b/view/src/main/java/se/su/dsv/scipro/data/FilteredListModel.java @@ -1,33 +1,32 @@ package se.su.dsv.scipro.data; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.LoadableDetachableModel; - import java.util.ArrayList; import java.util.List; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.LoadableDetachableModel; /** * Model to use in a ListView (or another repeater component) when you want to hide some list items conditionally. */ -public abstract class FilteredListModel extends LoadableDetachableModel>{ +public abstract class FilteredListModel extends LoadableDetachableModel> { - private IModel> inner; + private IModel> inner; @Override - protected void onDetach(){ + protected void onDetach() { inner.detach(); } - - public FilteredListModel(IModel> inner){ + + public FilteredListModel(IModel> inner) { this.inner = inner; } @Override - protected final List load(){ + protected final List load() { List input = inner.getObject(); List result = new ArrayList<>(input.size()); - for(T t : input){ - if(accept(t)) { + for (T t : input) { + if (accept(t)) { result.add(t); } } @@ -35,5 +34,4 @@ public abstract class FilteredListModel extends LoadableDetachableModel extends GenericDataProvider { + private final FilteredService filteredService; private final IModel filter; @@ -17,7 +17,12 @@ public class FilteredDataProvider extends GenericData this.filter = filter; } - public FilteredDataProvider(FilteredService filteredService, IModel filter, String sortParam, SortOrder sortOrder) { + public FilteredDataProvider( + FilteredService filteredService, + IModel filter, + String sortParam, + SortOrder sortOrder + ) { super(filteredService); this.filteredService = filteredService; this.filter = filter; diff --git a/view/src/main/java/se/su/dsv/scipro/dataproviders/GenericDataProvider.java b/view/src/main/java/se/su/dsv/scipro/dataproviders/GenericDataProvider.java index 409e694529..f8790ccd36 100644 --- a/view/src/main/java/se/su/dsv/scipro/dataproviders/GenericDataProvider.java +++ b/view/src/main/java/se/su/dsv/scipro/dataproviders/GenericDataProvider.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.dataproviders; +import java.util.Iterator; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.GenericService; -import java.util.Iterator; - public class GenericDataProvider extends SortableDataProvider { + private final GenericService genericService; public GenericDataProvider(GenericService genericService) { diff --git a/view/src/main/java/se/su/dsv/scipro/dataproviders/PageAdapter.java b/view/src/main/java/se/su/dsv/scipro/dataproviders/PageAdapter.java index 61b7977786..ee815feedd 100644 --- a/view/src/main/java/se/su/dsv/scipro/dataproviders/PageAdapter.java +++ b/view/src/main/java/se/su/dsv/scipro/dataproviders/PageAdapter.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.dataproviders; +import java.util.Objects; import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.Sort; -import java.util.Objects; - public class PageAdapter extends PageRequest { private final SortParam sort; @@ -21,9 +20,7 @@ public class PageAdapter extends PageRequest { return null; } - return new Sort( - sort.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC, - sort.getProperty()); + return new Sort(sort.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC, sort.getProperty()); } @Override @@ -31,9 +28,7 @@ public class PageAdapter extends PageRequest { if (o == this) return true; if (!(o instanceof PageAdapter)) return false; final PageAdapter other = (PageAdapter) o; - return other.canEqual(this) - && super.equals(o) - && Objects.equals(this.getSort(), other.getSort()); + return (other.canEqual(this) && super.equals(o) && Objects.equals(this.getSort(), other.getSort())); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/dataproviders/WicketPage.java b/view/src/main/java/se/su/dsv/scipro/dataproviders/WicketPage.java index 53352bd78f..07adfdca47 100644 --- a/view/src/main/java/se/su/dsv/scipro/dataproviders/WicketPage.java +++ b/view/src/main/java/se/su/dsv/scipro/dataproviders/WicketPage.java @@ -7,7 +7,8 @@ public record WicketPage(long offset, long limit, SortParam sortParam) imp @Override public Sort sort() { return new Sort<>( - sortParam().getProperty(), - sortParam().isAscending() ? Direction.ASCENDING : Direction.DESCENDING); + sortParam().getProperty(), + sortParam().isAscending() ? Direction.ASCENDING : Direction.DESCENDING + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapper.java b/view/src/main/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapper.java index 3d505d504d..345b599a12 100644 --- a/view/src/main/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapper.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapper.java @@ -13,21 +13,25 @@ public abstract class AjaxCheckboxWrapper extends Panel { public AjaxCheckboxWrapper(String id, IModel model) { super(id); - add(new AjaxCheckBox(CHECKBOX, model) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - onChange(target, getModelObject()); - } + add( + new AjaxCheckBox(CHECKBOX, model) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + onChange(target, getModelObject()); + } - @Override - protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { - super.updateAjaxAttributes(attributes); - AjaxCallListener ajaxCallListener = new AjaxCallListener(); - ajaxCallListener.onPrecondition("if (!confirm('Are you sure?')) {window.location.reload(); return false;}"); - attributes.getAjaxCallListeners().add(ajaxCallListener); + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { + super.updateAjaxAttributes(attributes); + AjaxCallListener ajaxCallListener = new AjaxCallListener(); + ajaxCallListener.onPrecondition( + "if (!confirm('Are you sure?')) {window.location.reload(); return false;}" + ); + attributes.getAjaxCallListeners().add(ajaxCallListener); + } } - }); + ); } public static final String CHECKBOX = "checkbox"; -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/ClickableIconColumn.java b/view/src/main/java/se/su/dsv/scipro/datatables/ClickableIconColumn.java index 3872ab31e8..adc3f460ac 100755 --- a/view/src/main/java/se/su/dsv/scipro/datatables/ClickableIconColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/ClickableIconColumn.java @@ -13,6 +13,7 @@ import org.apache.wicket.model.Model; import se.su.dsv.scipro.util.AjaxConfirmationLink; public abstract class ClickableIconColumn extends AbstractColumn { + public static final String DELETE = "fa fa-times"; public static final String EDIT = "fa fa-edit"; @@ -20,54 +21,49 @@ public abstract class ClickableIconColumn extends AbstractColumn { private final String confirmMessage; public ClickableIconColumn(IModel displayModel, String sort, String iconString) { - this(displayModel, sort, iconString, null); + this(displayModel, sort, iconString, null); } - + public ClickableIconColumn(IModel displayModel, String sort, String iconString, String confirmMessage) { - super(displayModel, sort); + super(displayModel, sort); this.iconString = iconString; - this.confirmMessage = confirmMessage; + this.confirmMessage = confirmMessage; } @Override - public void populateItem(Item> cellItem, - String componentId, IModel rowModel) { - cellItem.add(new LinkPanel(componentId, rowModel, - getIconString())); + public void populateItem(Item> cellItem, String componentId, IModel rowModel) { + cellItem.add(new LinkPanel(componentId, rowModel, getIconString())); } protected abstract void onClick(IModel clicked, AjaxRequestTarget target); /** - * Override this if you want to customize the visibility of the icon. + * Override this if you want to customize the visibility of the icon. * e.g. the case where you want some specific rows editable based on certain conditions. */ protected boolean shouldBeVisible(IModel rowModel) { - return true; + return true; } protected String getIconString() { return iconString; } - + private class LinkPanel extends Panel { public LinkPanel(String id, IModel rowModel, String iconString) { super(id); - AjaxLink link; - - if(confirmMessage!=null) { - link = new AjaxConfirmationLink<>("link", rowModel, confirmMessage) { + if (confirmMessage != null) { + link = new AjaxConfirmationLink<>("link", rowModel, confirmMessage) { @Override public void onClick(AjaxRequestTarget target) { ClickableIconColumn.this.onClick(getModel(), target); } }; } else { - link = new AjaxLink<>("link", rowModel) { - + link = new AjaxLink<>("link", rowModel) { @Override public void onClick(AjaxRequestTarget target) { ClickableIconColumn.this.onClick(getModel(), target); @@ -81,4 +77,4 @@ public abstract class ClickableIconColumn extends AbstractColumn { link.setVisible(shouldBeVisible(rowModel)); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/ClickableOrderColumn.java b/view/src/main/java/se/su/dsv/scipro/datatables/ClickableOrderColumn.java index f9c92ca8fd..980ffebd83 100755 --- a/view/src/main/java/se/su/dsv/scipro/datatables/ClickableOrderColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/ClickableOrderColumn.java @@ -15,30 +15,28 @@ import org.danekja.java.util.function.serializable.SerializableFunction; * Author: fred-fri * Date: 5/4/12 */ -public abstract class ClickableOrderColumn extends AbstractColumn implements IExportableColumn { +public abstract class ClickableOrderColumn + extends AbstractColumn + implements IExportableColumn { private final SerializableFunction function; - public ClickableOrderColumn(IModel displayModel, - SerializableFunction function, String sort) { + public ClickableOrderColumn(IModel displayModel, SerializableFunction function, String sort) { super(displayModel, sort); this.function = function; } @Override - public void populateItem(Item> cellItem, - String componentId, IModel rowModel) { - cellItem.add(new LinkPanel(componentId, rowModel, - rowModel.map(function))); + public void populateItem(Item> cellItem, String componentId, IModel rowModel) { + cellItem.add(new LinkPanel(componentId, rowModel, rowModel.map(function))); } protected abstract void onClick(IModel clicked, AjaxRequestTarget target, boolean up); private class LinkPanel extends Panel { - public LinkPanel(String id, IModel rowModel, IModel - labelModel) { - super(id); + public LinkPanel(String id, IModel rowModel, IModel labelModel) { + super(id); add(new Label("label", labelModel)); AjaxLink uplink = new AjaxLink<>("uplink", rowModel) { @@ -58,4 +56,4 @@ public abstract class ClickableOrderColumn extends AbstractColumn add(downlink); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/LabelAndLinkColumn.java b/view/src/main/java/se/su/dsv/scipro/datatables/LabelAndLinkColumn.java index b76be3760e..cb206a952d 100755 --- a/view/src/main/java/se/su/dsv/scipro/datatables/LabelAndLinkColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/LabelAndLinkColumn.java @@ -8,56 +8,60 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.util.AjaxConfirmationLink; public abstract class LabelAndLinkColumn extends Panel { - private LabelAndLinkColumn ajaxLinkColumn; + + private LabelAndLinkColumn ajaxLinkColumn; public abstract void onClick(AjaxRequestTarget target, IModel clickedModel); + public abstract String labelString(); - + /** - * Datatable column with a label and a link next to it. If a confirmationMessage string is available, + * Datatable column with a label and a link next to it. If a confirmationMessage string is available, * a confirmation dialog pops up before confirming link click - * + * */ public LabelAndLinkColumn(String id, final IModel model, String linkString) { - this(id, model, linkString, null, true); + this(id, model, linkString, null, true); } - public LabelAndLinkColumn(String id, final IModel model, String linkString, String confirmationMessage, boolean showLinks) { - super(id, model); - ajaxLinkColumn = this; + public LabelAndLinkColumn( + String id, + final IModel model, + String linkString, + String confirmationMessage, + boolean showLinks + ) { + super(id, model); + ajaxLinkColumn = this; - AjaxLink link; - if(confirmationMessage!=null){ - link = new AjaxConfirmationLink<>("link", model, confirmationMessage) { - - @Override - public void onClick(AjaxRequestTarget target) { - ajaxLinkColumn.onClick(target, model); - } - }; - } else { - link = new AjaxLink<>("link") { - - @Override - public void onClick(AjaxRequestTarget target) { - ajaxLinkColumn.onClick(target, model); - } - }; - } - - - link.add(new Label("linkLabel", linkString)); - link.setVisible(showLinks); - add(new Label("label", labelString())); - add(link); + AjaxLink link; + if (confirmationMessage != null) { + link = new AjaxConfirmationLink<>("link", model, confirmationMessage) { + @Override + public void onClick(AjaxRequestTarget target) { + ajaxLinkColumn.onClick(target, model); + } + }; + } else { + link = new AjaxLink<>("link") { + @Override + public void onClick(AjaxRequestTarget target) { + ajaxLinkColumn.onClick(target, model); + } + }; + } + link.add(new Label("linkLabel", linkString)); + link.setVisible(showLinks); + add(new Label("label", labelString())); + add(link); } - + /** * Use this constructor if you don't want the link to have a confirmation dialog when clicking - * + * */ public LabelAndLinkColumn(String id, final IModel model, String linkString, boolean showLinks) { - this(id, model, linkString, null, showLinks); + this(id, model, linkString, null, showLinks); } } diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectDataPanel.java b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectDataPanel.java index b1ebdf8cb2..04b5d7b3f8 100644 --- a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectDataPanel.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.datatables.project; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -46,13 +48,11 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.*; - public class ProjectDataPanel extends Panel { @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; @@ -64,16 +64,19 @@ public class ProjectDataPanel extends Panel { super(id); filter = new ProjectService.Filter(); filter.setFilterExternal(false); - final List defaultProjectTypes - = projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)); + final List defaultProjectTypes = projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ); filter.setProjectTypes(defaultProjectTypes); filter.setStatuses(new ArrayList<>(Collections.singletonList(ProjectStatus.ACTIVE))); - add(new ProjectFilterPanel("filterForm", Model.of(filter)) { - @Override - protected void filterUpdated(final AjaxRequestTarget target) { - target.add(exportableDataPanel); + add( + new ProjectFilterPanel("filterForm", Model.of(filter)) { + @Override + protected void filterUpdated(final AjaxRequestTarget target) { + target.add(exportableDataPanel); + } } - }); + ); addCreateNewProjectLink(); addFeedbackPanel(); addDataTable(); @@ -92,8 +95,7 @@ public class ProjectDataPanel extends Panel { columns.add(new TemporalColumn<>(Model.of("Started"), "startDate", Project::getStartDate)); if (SciProSession.get().authorizedForRole(Roles.SYSADMIN)) { columns.add(titleColumn()); - } - else { + } else { columns.add(new LambdaColumn<>(Model.of("Title"), "title", Project::getTitle)); } columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", Project::getProjectTypeName)); @@ -102,11 +104,12 @@ public class ProjectDataPanel extends Panel { columns.add(supervisorColumn()); if (isAdmin) { columns.add(reviewerColumn()); - } - else { + } else { columns.add(new UserColumn<>(Model.of("Reviewer"), "reviewer.fullName", Project::getReviewer)); } - columns.add(new LambdaColumn<>(Model.of("Research area"), project -> getGetResearchAreaName(project.getResearchArea()))); + columns.add( + new LambdaColumn<>(Model.of("Research area"), project -> getGetResearchAreaName(project.getResearchArea())) + ); if (isAdmin) { columns.add(inactivateCheckbox()); } @@ -116,8 +119,7 @@ public class ProjectDataPanel extends Panel { private String getGetResearchAreaName(ResearchArea researchArea) { if (researchArea != null) { return researchArea.getTitle(); - } - else { + } else { return null; } } @@ -130,7 +132,9 @@ public class ProjectDataPanel extends Panel { return new MultipleUsersColumn<>(Model.of("Authors")) { @Override public IModel> getUsers(final IModel rowModel) { - return new ListAdapterModel<>(LambdaModel.of(rowModel, Project::getProjectParticipants, Project::setProjectParticipants)); + return new ListAdapterModel<>( + LambdaModel.of(rowModel, Project::getProjectParticipants, Project::setProjectParticipants) + ); } }; } @@ -139,13 +143,19 @@ public class ProjectDataPanel extends Panel { return new LambdaColumn<>(Model.of("Title"), "title", Project::getTitle) { @Override public void populateItem(Item> components, String s, final IModel model) { - components.add(LinkWrapper.apply(s, id -> { - final PageParameters pp = new PageParameters(); - pp.set(PageParameterKeys.MAP.get(Project.class), model.getObject().getId()); - final BookmarkablePageLink link = new BookmarkablePageLink<>(id, AdminEditProjectPage.class, pp); - link.setBody(Model.of(model.getObject().getTitle())); - return link; - })); + components.add( + LinkWrapper.apply(s, id -> { + final PageParameters pp = new PageParameters(); + pp.set(PageParameterKeys.MAP.get(Project.class), model.getObject().getId()); + final BookmarkablePageLink link = new BookmarkablePageLink<>( + id, + AdminEditProjectPage.class, + pp + ); + link.setBody(Model.of(model.getObject().getTitle())); + return link; + }) + ); } }; } @@ -153,7 +163,11 @@ public class ProjectDataPanel extends Panel { private AbstractColumn reviewerColumn() { return new LambdaColumn<>(Model.of("Reviewer"), Project::getReviewer) { @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { cellItem.add(new ReviewerColumnCell(componentId, rowModel)); } }; @@ -162,17 +176,23 @@ public class ProjectDataPanel extends Panel { private AbstractColumn inactivateCheckbox() { return new AbstractExportableColumn<>(Model.of("Active")) { @Override - public void populateItem(Item> cellItem, String componentId, final IModel model) { + public void populateItem( + Item> cellItem, + String componentId, + final IModel model + ) { final Project project = model.getObject(); final boolean currentState = project.getProjectStatus() != ProjectStatus.INACTIVE; - cellItem.add(new AjaxCheckboxWrapper(componentId, Model.of(currentState)) { - @Override - public void onChange(AjaxRequestTarget target, boolean selected) { - projectService.toggleActiveStatus(model.getObject(), selected); - success(getString("inactive", model)); - target.add(feedback); + cellItem.add( + new AjaxCheckboxWrapper(componentId, Model.of(currentState)) { + @Override + public void onChange(AjaxRequestTarget target, boolean selected) { + projectService.toggleActiveStatus(model.getObject(), selected); + success(getString("inactive", model)); + target.add(feedback); + } } - }); + ); } @Override @@ -200,15 +220,19 @@ public class ProjectDataPanel extends Panel { } private static class ReviewerColumnCell extends GenericPanel { + public ReviewerColumnCell(String id, IModel project) { super(id, project); - add(new UserLinkPanel("current_reviewer", project.map(Project::getReviewer))); PageParameters pp = AdminAssignReviewerPage.pageParametersFor(project.getObject()); - final BookmarkablePageLink link = new BookmarkablePageLink<>("link", AdminAssignReviewerPage.class, pp); + final BookmarkablePageLink link = new BookmarkablePageLink<>( + "link", + AdminAssignReviewerPage.class, + pp + ); link.setBody(() -> project.getObject().getReviewer() == null ? "(assign reviewer)" : "(change reviewer)"); add(link); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectExternalOrganisationPanel.java b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectExternalOrganisationPanel.java index 7b0d7b7efc..7994440982 100644 --- a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectExternalOrganisationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectExternalOrganisationPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.datatables.project; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -35,17 +39,14 @@ import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.*; - -import static java.util.Arrays.asList; - -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class ProjectExternalOrganisationPanel extends Panel { public static final int MIN_TITLE_LENGTH = 3; + @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; @@ -73,8 +74,11 @@ public class ProjectExternalOrganisationPanel extends Panel { columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", Project::getProjectTypeName)); columns.add(new EnumLambdaColumn<>(Model.of("Status"), "projectStatus", Project::getProjectStatus)); columns.add(supervisorColumn()); - columns.add(new LambdaColumn<>(Model.of("External organisation"), "externalOrganization.name", - p -> p.getExternalOrganization() != null ? p.getExternalOrganization().getName() : null)); + columns.add( + new LambdaColumn<>(Model.of("External organisation"), "externalOrganization.name", p -> + p.getExternalOrganization() != null ? p.getExternalOrganization().getName() : null + ) + ); return columns; } @@ -86,12 +90,14 @@ public class ProjectExternalOrganisationPanel extends Panel { return new LambdaColumn<>(Model.of("Title"), Project::getTitle) { @Override public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Project::getTitle, Project::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - openCRUDPanel(model); + components.add( + new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Project::getTitle, Project::setTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + openCRUDPanel(model); + } } - }); + ); } }; } @@ -109,6 +115,7 @@ public class ProjectExternalOrganisationPanel extends Panel { } private class FilterForm extends Form { + private String titleString; public FilterForm(String id) { @@ -125,67 +132,93 @@ public class ProjectExternalOrganisationPanel extends Panel { } private void addRedStateFilter() { - TextField redStateField = new TextField<>("redStateFilter", LambdaModel.of(filter::getRedStateTime, filter::setRedStateTime), Integer.class); - redStateField.add(new AjaxFormComponentUpdatingBehavior("keyup") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(exportableDataPanel); + TextField redStateField = new TextField<>( + "redStateFilter", + LambdaModel.of(filter::getRedStateTime, filter::setRedStateTime), + Integer.class + ); + redStateField.add( + new AjaxFormComponentUpdatingBehavior("keyup") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(exportableDataPanel); + } } - }); + ); add(redStateField); } private void addDateFilter() { - add(new DeactivatableDatePickerPanel("dateFilter", + add( + new DeactivatableDatePickerPanel( + "dateFilter", LambdaModel.of(filter::getCreatedAfter, filter::setCreatedAfter), - LambdaModel.of(filter::getCreatedBefore, filter::setCreatedBefore)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(exportableDataPanel); + LambdaModel.of(filter::getCreatedBefore, filter::setCreatedBefore) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(exportableDataPanel); + } } - }); + ); } private void addSupervisorFilter() { - add(new EmployeeAutoComplete("supervisorFilter", LambdaModel.of(filter::getSupervisor, filter::setSupervisor)) { - @Override - protected void action(AjaxRequestTarget pTarget, User newSelection) { - pTarget.add(exportableDataPanel); + add( + new EmployeeAutoComplete( + "supervisorFilter", + LambdaModel.of(filter::getSupervisor, filter::setSupervisor) + ) { + @Override + protected void action(AjaxRequestTarget pTarget, User newSelection) { + pTarget.add(exportableDataPanel); + } } - }); + ); } private void addProjectTitleFilter() { - TextField titleField = new TextField<>("titleFilter", LambdaModel.of(() -> titleString, newTitleFilter -> titleString = newTitleFilter)); - titleField.add(new AjaxFormComponentUpdatingBehavior("keyup") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { - filter.setTitleContains(titleString); - } else { - filter.setTitleContains(null); + TextField titleField = new TextField<>( + "titleFilter", + LambdaModel.of(() -> titleString, newTitleFilter -> titleString = newTitleFilter) + ); + titleField.add( + new AjaxFormComponentUpdatingBehavior("keyup") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { + filter.setTitleContains(titleString); + } else { + filter.setTitleContains(null); + } + target.add(exportableDataPanel); } - target.add(exportableDataPanel); } - }); + ); add(titleField); } private void addAuthorFilter() { - add(new AuthorAutoComplete("authorFilter") { - @Override - protected void action(AjaxRequestTarget pTarget, User newSelection) { - filter.setAuthorUser(newSelection); - pTarget.add(exportableDataPanel); + add( + new AuthorAutoComplete("authorFilter") { + @Override + protected void action(AjaxRequestTarget pTarget, User newSelection) { + filter.setAuthorUser(newSelection); + pTarget.add(exportableDataPanel); + } } - }); + ); } private void addProjectTypeFilter() { - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -200,10 +233,12 @@ public class ProjectExternalOrganisationPanel extends Panel { } private void addProjectStatusFilter() { - AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>("statusFilter", - new ArrayList<>(Collections.singletonList(ProjectStatus.ACTIVE)), - asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this)) { + AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>( + "statusFilter", + new ArrayList<>(Collections.singletonList(ProjectStatus.ACTIVE)), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onUpdate(AjaxRequestTarget target) { filter.setStatuses(new HashSet<>(getModelObject())); @@ -215,4 +250,4 @@ public class ProjectExternalOrganisationPanel extends Panel { filter.setStatuses(new HashSet<>(projectStatus.getModelObject())); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectFilterPanel.java b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectFilterPanel.java index 667962b195..67cecff2e2 100644 --- a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectFilterPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectFilterPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.datatables.project; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -20,10 +23,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - -import static java.util.Arrays.asList; - public abstract class ProjectFilterPanel extends Panel { private static final int MIN_TITLE_LENGTH = 3; @@ -33,13 +32,17 @@ public abstract class ProjectFilterPanel extends Panel { public ProjectFilterPanel(final String id, final IModel model) { super(id, model); - - add(new AjaxCheckBox("noReviewer", LambdaModel.of(model, ProjectService.Filter::isNoReviewer, ProjectService.Filter::setNoReviewer)) { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - filterUpdated(target); + add( + new AjaxCheckBox( + "noReviewer", + LambdaModel.of(model, ProjectService.Filter::isNoReviewer, ProjectService.Filter::setNoReviewer) + ) { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + filterUpdated(target); + } } - }); + ); addDateFilter(model); addRedStateFilter(model); @@ -54,93 +57,128 @@ public abstract class ProjectFilterPanel extends Panel { protected abstract void filterUpdated(AjaxRequestTarget target); private void addDateFilter(final IModel filter) { - add(new DeactivatableDatePickerPanel("dateFilter", + add( + new DeactivatableDatePickerPanel( + "dateFilter", LambdaModel.of(filter, ProjectService.Filter::getCreatedAfter, ProjectService.Filter::setCreatedAfter), - LambdaModel.of(filter, ProjectService.Filter::getCreatedBefore, ProjectService.Filter::setCreatedBefore)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - filterUpdated(target); + LambdaModel.of(filter, ProjectService.Filter::getCreatedBefore, ProjectService.Filter::setCreatedBefore) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + filterUpdated(target); + } } - }); + ); } private void addRedStateFilter(final IModel filter) { - TextField redStateField = new TextField<>("redStateFilter", LambdaModel.of(filter, ProjectService.Filter::getRedStateTime, ProjectService.Filter::setRedStateTime), Integer.class); - redStateField.add(new AjaxFormComponentUpdatingBehavior("keyup") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - filterUpdated(target); + TextField redStateField = new TextField<>( + "redStateFilter", + LambdaModel.of(filter, ProjectService.Filter::getRedStateTime, ProjectService.Filter::setRedStateTime), + Integer.class + ); + redStateField.add( + new AjaxFormComponentUpdatingBehavior("keyup") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + filterUpdated(target); + } } - }); + ); add(redStateField); } private void addSupervisorFilter(final IModel filter) { - add(new EmployeeAutoComplete("supervisorFilter", LambdaModel.of(filter, ProjectService.Filter::getSupervisor, ProjectService.Filter::setSupervisor)) { - @Override - protected void action(AjaxRequestTarget target, User newSelection) { - filterUpdated(target); + add( + new EmployeeAutoComplete( + "supervisorFilter", + LambdaModel.of(filter, ProjectService.Filter::getSupervisor, ProjectService.Filter::setSupervisor) + ) { + @Override + protected void action(AjaxRequestTarget target, User newSelection) { + filterUpdated(target); + } } - }); + ); } private void addReviewerFilter(final IModel filter) { - add(new EmployeeAutoComplete("reviewerFilter", LambdaModel.of(filter, ProjectService.Filter::getReviewer, ProjectService.Filter::setReviewer)) { - @Override - protected void action(AjaxRequestTarget target, User newSelection) { - filterUpdated(target); + add( + new EmployeeAutoComplete( + "reviewerFilter", + LambdaModel.of(filter, ProjectService.Filter::getReviewer, ProjectService.Filter::setReviewer) + ) { + @Override + protected void action(AjaxRequestTarget target, User newSelection) { + filterUpdated(target); + } } - }); + ); } private void addProjectTitleFilter(final IModel model) { TextField titleField = new TextField<>("titleFilter", new Model<>()); - titleField.add(new AjaxFormComponentUpdatingBehavior("keyup") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - final String titleString = titleField.getModelObject(); - final ProjectService.Filter filter = model.getObject(); - if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { - filter.setTitleContains(titleString); - } else { - filter.setTitleContains(null); + titleField.add( + new AjaxFormComponentUpdatingBehavior("keyup") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + final String titleString = titleField.getModelObject(); + final ProjectService.Filter filter = model.getObject(); + if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { + filter.setTitleContains(titleString); + } else { + filter.setTitleContains(null); + } + filterUpdated(target); } - filterUpdated(target); } - }); + ); add(titleField); } private void addAuthorFilter(final IModel filter) { - add(new AuthorAutoComplete("authorFilter", LambdaModel.of(filter, ProjectService.Filter::getAuthorUser, ProjectService.Filter::setAuthorUser)) { - @Override - protected void action(AjaxRequestTarget target, User newSelection) { - filterUpdated(target); + add( + new AuthorAutoComplete( + "authorFilter", + LambdaModel.of(filter, ProjectService.Filter::getAuthorUser, ProjectService.Filter::setAuthorUser) + ) { + @Override + protected void action(AjaxRequestTarget target, User newSelection) { + filterUpdated(target); + } } - }); + ); } private void addProjectTypeFilter(final IModel filter) { - add(new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", + add( + new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", LambdaModel.of(filter, ProjectService.Filter::getProjectTypes, ProjectService.Filter::setProjectTypes), projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - filterUpdated(target); + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + filterUpdated(target); + } } - }); + ); } private void addProjectStatusFilter(final IModel filter) { - add(new AjaxCheckBoxMultipleChoice<>("statusFilter", + add( + new AjaxCheckBoxMultipleChoice<>( + "statusFilter", LambdaModel.of(filter, ProjectService.Filter::getStatuses, ProjectService.Filter::setStatuses), asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(ProjectFilterPanel.this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - filterUpdated(target); + new EnumChoiceRenderer<>(ProjectFilterPanel.this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + filterUpdated(target); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectStateColumn.java b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectStateColumn.java index 8f38f05eb9..4f089ff44c 100755 --- a/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectStateColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/project/ProjectStateColumn.java @@ -14,7 +14,8 @@ import se.su.dsv.scipro.project.StateOfMind; public class ProjectStateColumn extends AbstractExportableColumn { - static final String STATE_INFO = "Authors indicate if feedback is needed or not and how urgent it is. This alert function is solely controlled by the authors"; + static final String STATE_INFO = + "Authors indicate if feedback is needed or not and how urgent it is. This alert function is solely controlled by the authors"; public static final String TITLE = "title"; public static final String IMG = "img"; @@ -38,9 +39,9 @@ public class ProjectStateColumn extends AbstractExportableColumn rowModel) { super(id); - Project p = rowModel.getObject(); switch (p.getStateOfMind()) { @@ -62,4 +63,4 @@ public class ProjectStateColumn extends AbstractExportableColumn rowModel) { super(id); - Project project = rowModel.getObject(); PageParameters pp = new PageParameters(); pp.add(PageParameterKeys.MAP.get(Project.class), project.getId()); - BookmarkablePageLink projectLink = new BookmarkablePageLink<>("link", SupervisorProjectDetailsPage.class, pp); + BookmarkablePageLink projectLink = new BookmarkablePageLink<>( + "link", + SupervisorProjectDetailsPage.class, + pp + ); Label title = new Label("label", rowModel.map(Project::getTitle)); title.add(new AttributeAppender("title", Model.of(project.getTitle()))); @@ -46,4 +50,4 @@ public class ProjectTitleColumn extends AbstractExportableColumn model) { super(id, model); - - add(new ListView<>("list", new ListAdapterModel<>(LambdaModel.of(model, ApplicationPeriod::getProjectTypes, ApplicationPeriod::setProjectTypes))) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("pc", item.getModelObject().getName())); - item.add(new Label("total", String.valueOf(applicationPeriodFacade.totalTargets(model.getObject(), item.getModelObject())))); - item.add(new Label("remaining", String.valueOf(applicationPeriodFacade.remainingTargets(model.getObject(), item.getModelObject())))); + add( + new ListView<>( + "list", + new ListAdapterModel<>( + LambdaModel.of(model, ApplicationPeriod::getProjectTypes, ApplicationPeriod::setProjectTypes) + ) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("pc", item.getModelObject().getName())); + item.add( + new Label( + "total", + String.valueOf( + applicationPeriodFacade.totalTargets(model.getObject(), item.getModelObject()) + ) + ) + ); + item.add( + new Label( + "remaining", + String.valueOf( + applicationPeriodFacade.remainingTargets(model.getObject(), item.getModelObject()) + ) + ) + ); + } } - }); - add(new Link("editTarget"){ - @Override - public void onClick() { - setResponsePage(new AdminEditTargetsPage(model)); + ); + add( + new Link("editTarget") { + @Override + public void onClick() { + setResponsePage(new AdminEditTargetsPage(model)); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/datatables/target/EditTargetPanel.java b/view/src/main/java/se/su/dsv/scipro/datatables/target/EditTargetPanel.java index 31dcedd59c..e820a85f9f 100644 --- a/view/src/main/java/se/su/dsv/scipro/datatables/target/EditTargetPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/datatables/target/EditTargetPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.datatables.target; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.TextField; @@ -13,8 +14,6 @@ import se.su.dsv.scipro.match.TargetService; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public abstract class EditTargetPanel extends Panel { private final IModel apModel; @@ -26,27 +25,39 @@ public abstract class EditTargetPanel extends Panel { public abstract void update(AjaxRequestTarget ajaxTarget, User e); - public EditTargetPanel(String id, final IModel apModel, final IModel eModel, final IModel pcModel, final boolean isEditable) { + public EditTargetPanel( + String id, + final IModel apModel, + final IModel eModel, + final IModel pcModel, + final boolean isEditable + ) { super(id); this.apModel = apModel; this.eModel = eModel; this.pcModel = pcModel; final IModel target = findTarget(apModel, eModel, pcModel); - final TextField inputField = new TextField<>("input", LambdaModel.of(target, Target::getTarget, Target::setTarget), Integer.class) { + final TextField inputField = new TextField<>( + "input", + LambdaModel.of(target, Target::getTarget, Target::setTarget), + Integer.class + ) { @Override protected void onConfigure() { super.onConfigure(); setEnabled(isEditable); } }; - inputField.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget ajaxTarget) { - targetService.save(target.getObject()); - update(ajaxTarget, eModel.getObject()); + inputField.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget ajaxTarget) { + targetService.save(target.getObject()); + update(ajaxTarget, eModel.getObject()); + } } - }); + ); add(inputField); } @@ -58,11 +69,19 @@ public abstract class EditTargetPanel extends Panel { pcModel.detach(); } - private LoadableDetachableModel findTarget(final IModel apModelObject, final IModel eModelObject, final IModel projectType) { + private LoadableDetachableModel findTarget( + final IModel apModelObject, + final IModel eModelObject, + final IModel projectType + ) { return new LoadableDetachableModel<>() { @Override protected Target load() { - return targetService.findOne(apModelObject.getObject(), eModelObject.getObject(), projectType.getObject()); + return targetService.findOne( + apModelObject.getObject(), + eModelObject.getObject(), + projectType.getObject() + ); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/date/DatePickerModel.java b/view/src/main/java/se/su/dsv/scipro/date/DatePickerModel.java index 7fdf949b3a..0ec847cd3a 100755 --- a/view/src/main/java/se/su/dsv/scipro/date/DatePickerModel.java +++ b/view/src/main/java/se/su/dsv/scipro/date/DatePickerModel.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.date; -import org.apache.wicket.util.io.IClusterable; - import java.time.Instant; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.*; +import org.apache.wicket.util.io.IClusterable; public final class DatePickerModel implements IClusterable { @@ -30,8 +29,8 @@ public final class DatePickerModel implements IClusterable { public void setStartDate(Date startDate) { if (startDate != null) { Instant tmp = ZonedDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault()) - .with(LocalTime.MIDNIGHT) - .toInstant(); + .with(LocalTime.MIDNIGHT) + .toInstant(); this.startDate = Date.from(tmp); } else { this.startDate = null; @@ -45,8 +44,8 @@ public final class DatePickerModel implements IClusterable { public void setEndDate(Date endDate) { if (endDate != null) { final Instant tmp = ZonedDateTime.ofInstant(endDate.toInstant(), ZoneId.systemDefault()) - .with(LocalTime.MAX) - .toInstant(); + .with(LocalTime.MAX) + .toInstant(); this.endDate = Date.from(tmp); } else { this.endDate = null; @@ -56,5 +55,4 @@ public final class DatePickerModel implements IClusterable { public Date getEndDate() { return endDate; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/date/DatePickerPanel.java b/view/src/main/java/se/su/dsv/scipro/date/DatePickerPanel.java index 06863a02f0..54657ca7fc 100755 --- a/view/src/main/java/se/su/dsv/scipro/date/DatePickerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/date/DatePickerPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.date; +import java.util.Date; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.markup.html.form.Form; @@ -9,8 +10,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import se.su.dsv.scipro.components.BootstrapDateField; -import java.util.Date; - public class DatePickerPanel extends Panel { public static final String DATE_FORM = "dateForm"; @@ -50,27 +49,20 @@ public class DatePickerPanel extends Panel { public DatePickerPanel(String id, IModel startDate, IModel endDate) { super(id); - - dpm = new DatePickerModel(startDate.getObject(), endDate.getObject()); - Form dateForm = new Form<>(DATE_FORM) { - @Override protected void onSubmit() { dpm.setStartDate(startDtf.getModelObject()); dpm.setEndDate(endDtf.getModelObject()); - } }; startDtf = new BootstrapDateField(START_DATE, startDate); endDtf = new BootstrapDateField(END_DATE, endDate); - OnChangeAjaxBehavior startDtfOnChange = new OnChangeAjaxBehavior() { - @Override protected void onUpdate(AjaxRequestTarget target) { setStartDate(startDtf.getModelObject()); @@ -79,8 +71,6 @@ public class DatePickerPanel extends Panel { }; OnChangeAjaxBehavior endDtfOnChangeAjaxBehavior = new OnChangeAjaxBehavior() { - - @Override protected void onUpdate(AjaxRequestTarget target) { setEndDate(endDtf.getModelObject()); @@ -96,7 +86,6 @@ public class DatePickerPanel extends Panel { dateForm.add(endDtf); add(dateForm); - } public void setStartDate(Date startDate) { @@ -105,7 +94,6 @@ public class DatePickerPanel extends Panel { } public void setEndDate(Date endDate) { - dpm.setEndDate(endDate); endDtf.setModelObject(dpm.getEndDate()); } diff --git a/view/src/main/java/se/su/dsv/scipro/date/DeactivatableDatePickerPanel.java b/view/src/main/java/se/su/dsv/scipro/date/DeactivatableDatePickerPanel.java index 1cea509b10..27a0922a2f 100644 --- a/view/src/main/java/se/su/dsv/scipro/date/DeactivatableDatePickerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/date/DeactivatableDatePickerPanel.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.date; +import java.util.Date; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.markup.html.border.Border; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import java.util.Date; - public class DeactivatableDatePickerPanel extends Border { + public static final String TOGGLE = "toggle"; public static final String DATE_PICKER = "datePicker"; @@ -21,7 +21,12 @@ public class DeactivatableDatePickerPanel extends Border { this(id, startDate, endDate, Model.of(Boolean.FALSE)); } - public DeactivatableDatePickerPanel(String id, IModel startDate, IModel endDate, IModel activated) { + public DeactivatableDatePickerPanel( + String id, + IModel startDate, + IModel endDate, + IModel activated + ) { super(id); this.startDate = startDate; this.endDate = endDate; @@ -33,8 +38,7 @@ public class DeactivatableDatePickerPanel extends Border { if (getModelObject()) { DeactivatableDatePickerPanel.this.startDate.setObject(datePicker.getStartDate()); DeactivatableDatePickerPanel.this.endDate.setObject(datePicker.getEndDate()); - } - else { + } else { DeactivatableDatePickerPanel.this.startDate.setObject(null); DeactivatableDatePickerPanel.this.endDate.setObject(null); } diff --git a/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerPage.java b/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerPage.java index 6e69516476..9ec6ba4bc0 100644 --- a/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.examiner.pages; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; @@ -8,9 +9,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.springdata.services.UserProfileService; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.EXAMINER}) +@Authorization(authorizedRoles = { Roles.EXAMINER }) public abstract class ExaminerPage extends MenuPage { @Inject @@ -22,10 +21,11 @@ public abstract class ExaminerPage extends MenuPage { public ExaminerPage(PageParameters pp) { super(pp); saveSelectedRole(); - SciProSession.get().setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); + SciProSession.get() + .setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); } private void saveSelectedRole() { userProfileService.setSelectedRole(SciProSession.get().getUser(), Roles.EXAMINER); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerStartPage.java b/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerStartPage.java index 9069ef6ac3..801f45cfef 100755 --- a/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/examiner/pages/ExaminerStartPage.java @@ -4,11 +4,12 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.EXAMINER}) +@Authorization(authorizedRoles = { Roles.EXAMINER }) public class ExaminerStartPage extends ExaminerPage { + public static final String MAIN_MENU_LABEL = "Examiner"; public ExaminerStartPage(PageParameters pp) { super(pp); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/exceptions/PageNotFoundException.java b/view/src/main/java/se/su/dsv/scipro/exceptions/PageNotFoundException.java index 0e463fc168..962088deeb 100755 --- a/view/src/main/java/se/su/dsv/scipro/exceptions/PageNotFoundException.java +++ b/view/src/main/java/se/su/dsv/scipro/exceptions/PageNotFoundException.java @@ -4,7 +4,8 @@ import org.apache.wicket.RestartResponseAtInterceptPageException; import se.su.dsv.scipro.basepages.errorpages.NotFoundPage; public class PageNotFoundException extends RestartResponseAtInterceptPageException { - public PageNotFoundException(){ - super(NotFoundPage.class); - } + + public PageNotFoundException() { + super(NotFoundPage.class); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/files/FileDescriptionPanel.java b/view/src/main/java/se/su/dsv/scipro/files/FileDescriptionPanel.java index a870d7e332..668a9c69d9 100644 --- a/view/src/main/java/se/su/dsv/scipro/files/FileDescriptionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/files/FileDescriptionPanel.java @@ -12,33 +12,37 @@ import se.su.dsv.scipro.util.AjaxConfirmationLink; public class FileDescriptionPanel extends GenericPanel { - - - public boolean deleteAllowed(){ + public boolean deleteAllowed() { return false; } - public void onDelete(AjaxRequestTarget target){ - } + public void onDelete(AjaxRequestTarget target) {} public FileDescriptionPanel(String id, final IModel model) { super(id, model); - add(new ViewAttachmentPanel(FILE, model, DateStyle.DATETIME)); - add(new UserLinkPanel(UPLOADER, LambdaModel.of(model, FileDescription::getUploader, FileDescription::setUploader))); + add( + new UserLinkPanel( + UPLOADER, + LambdaModel.of(model, FileDescription::getUploader, FileDescription::setUploader) + ) + ); - add(new AjaxConfirmationLink(DELETE, "Are you sure you want to delete the file?") { - @Override - public void onClick(AjaxRequestTarget target) { - onDelete(target); + add( + new AjaxConfirmationLink(DELETE, "Are you sure you want to delete the file?") { + @Override + public void onClick(AjaxRequestTarget target) { + onDelete(target); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(deleteAllowed()); + } } - @Override - protected void onConfigure(){ - super.onConfigure(); - setVisibilityAllowed(deleteAllowed()); - } - }); + ); } @Override @@ -50,4 +54,4 @@ public class FileDescriptionPanel extends GenericPanel { public static final String FILE = "file"; public static final String UPLOADER = "uploader"; public static final String DELETE = "delete"; -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/files/WicketFileUpload.java b/view/src/main/java/se/su/dsv/scipro/files/WicketFileUpload.java index a99eacec8e..3fb54afc95 100644 --- a/view/src/main/java/se/su/dsv/scipro/files/WicketFileUpload.java +++ b/view/src/main/java/se/su/dsv/scipro/files/WicketFileUpload.java @@ -1,17 +1,17 @@ package se.su.dsv.scipro.files; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.system.User; - import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Objects; import java.util.Optional; import java.util.function.Function; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.User; public class WicketFileUpload implements FileUpload { + private final org.apache.wicket.markup.html.form.upload.FileUpload fileUpload; private final User user; diff --git a/view/src/main/java/se/su/dsv/scipro/files/WicketProjectFileUpload.java b/view/src/main/java/se/su/dsv/scipro/files/WicketProjectFileUpload.java index 3d2bec1b40..d719d2ddf7 100644 --- a/view/src/main/java/se/su/dsv/scipro/files/WicketProjectFileUpload.java +++ b/view/src/main/java/se/su/dsv/scipro/files/WicketProjectFileUpload.java @@ -17,5 +17,4 @@ public class WicketProjectFileUpload extends WicketFileUpload implements Project public Project getProject() { return project; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanel.java index 9557edcb83..16717fe50c 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -24,11 +28,6 @@ import se.su.dsv.scipro.reusable.SciProUtilities; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - public class AdminFinalSeminarDataPanel extends Panel { public static final String DATE_PICKER_PANEL = "datePickerPanel"; @@ -63,6 +62,7 @@ public class AdminFinalSeminarDataPanel extends Panel { filter.setFromDate(getStartDate()); target.add(dataTable); } + @Override public void updateEndDate(AjaxRequestTarget target) { filter.setToDate(getEndDate()); @@ -73,7 +73,12 @@ public class AdminFinalSeminarDataPanel extends Panel { } private void addDataTable() { - SortableDataProvider provider = new FilteredDataProvider<>(finalSeminarService, Model.of(filter), "startDate", SortOrder.ASCENDING); + SortableDataProvider provider = new FilteredDataProvider<>( + finalSeminarService, + Model.of(filter), + "startDate", + SortOrder.ASCENDING + ); dataTable = new ExportableDataPanel<>(DATA_TABEL, createColumns(), provider); add(dataTable); } @@ -81,42 +86,68 @@ public class AdminFinalSeminarDataPanel extends Panel { private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of("Date"), FinalSeminar::getStartDate, "startDate", DateStyle.DATETIME)); - columns.add(new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName())); + columns.add( + new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName()) + ); - columns.add(new LambdaColumn<>(Model.of("Title"), FinalSeminar::getProjectTitle) { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, model.map(FinalSeminar::getProject).map(Project::getTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - setResponsePage(new AdminFinalSeminarDetailsPage(getModel())); - } - }); + columns.add( + new LambdaColumn<>(Model.of("Title"), FinalSeminar::getProjectTitle) { + @Override + public void populateItem( + Item> components, + String s, + final IModel model + ) { + components.add( + new AjaxLinkPanel<>(s, model, model.map(FinalSeminar::getProject).map(Project::getTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + setResponsePage(new AdminFinalSeminarDetailsPage(getModel())); + } + } + ); + } } - }); + ); final boolean isAdmin = SciProSession.get().authorizedForRole(Roles.ADMIN); if (isAdmin) { - columns.add(new AbstractColumn<>(Model.of("Cancel")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), "Are you sure you want to cancel final seminar?") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - setModelObject(finalSeminarService.cancel(getModelObject())); - success("Cancelled final seminar"); - target.add(feedback); - target.add(dataTable); - } + columns.add( + new AbstractColumn<>(Model.of("Cancel")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + "Are you sure you want to cancel final seminar?" + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + setModelObject(finalSeminarService.cancel(getModelObject())); + success("Cancelled final seminar"); + target.add(feedback); + target.add(dataTable); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(rowModel.getObject().getStartDate().after(new Date()) && !rowModel.getObject().isCancelled()); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + rowModel.getObject().getStartDate().after(new Date()) && + !rowModel.getObject().isCancelled() + ); + } + } + ); + } } - }); + ); } return columns; diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDetailsPage.java index 72cd3d666a..58b9033691 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDetailsPage.java @@ -6,8 +6,9 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminFinalSemin import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM }) public class AdminFinalSeminarDetailsPage extends AbstractAdminProjectPage implements MenuHighlightAdminFinalSeminars { + public AdminFinalSeminarDetailsPage(IModel model) { setDefaultModel(model); diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPage.java index 135943bd0f..e4436cdbe3 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPage.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.finalseminar; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -35,16 +42,11 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; +@Authorization(authorizedRoles = { Roles.ADMIN }) +public class AdminFinalSeminarExemptionPage + extends AbstractAdminProjectPage + implements MenuHighlightAdminFinalSeminars { -import static java.util.Arrays.asList; - -@Authorization(authorizedRoles = {Roles.ADMIN}) -public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage implements MenuHighlightAdminFinalSeminars { public static final String DP = "dp"; public static final String FORM = "form"; public static final String FEEDBACK = "feedback"; @@ -52,8 +54,10 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; + @Inject private FinalSeminarService finalSeminarService; @@ -62,14 +66,12 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp private FencedFeedbackPanel feedbackPanel; public AdminFinalSeminarExemptionPage() { - feedbackPanel = new FencedFeedbackPanel(FEEDBACK, this); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); add(new FilterForm(FORM)); addDP(); - } private void addDP() { @@ -82,60 +84,89 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new LambdaColumn<>(Model.of("Title"), "title", Project::getTitle)); - columns.add(new AbstractExportableColumn<>(Model.of(FinalSeminar.U_SINGULAR)) { - @Override - public void populateItem(Item> item, String s, IModel iModel) { - if (finalSeminarService.findByProject(iModel.getObject()) != null) { - item.add(new DateLabel(s, new Model<>(finalSeminarService.findByProject(iModel.getObject()).getStartDate()), DateStyle.DATETIME)); - } else { - item.add(new Label(s, new ResourceModel("noSeminar"))); + columns.add( + new AbstractExportableColumn<>(Model.of(FinalSeminar.U_SINGULAR)) { + @Override + public void populateItem(Item> item, String s, IModel iModel) { + if (finalSeminarService.findByProject(iModel.getObject()) != null) { + item.add( + new DateLabel( + s, + new Model<>(finalSeminarService.findByProject(iModel.getObject()).getStartDate()), + DateStyle.DATETIME + ) + ); + } else { + item.add(new Label(s, new ResourceModel("noSeminar"))); + } + } + + @Override + public IModel getDataModel(IModel rowModel) { + if (finalSeminarService.findByProject(rowModel.getObject()) != null) { + return Model.of( + finalSeminarService.findByProject(rowModel.getObject()).getStartDate().toString() + ); + } else { + return Model.of("noSeminar"); + } } } + ); - @Override - public IModel getDataModel(IModel rowModel) { - if (finalSeminarService.findByProject(rowModel.getObject()) != null) { - return Model.of(finalSeminarService.findByProject(rowModel.getObject()).getStartDate().toString()); - } else { - return Model.of("noSeminar"); - } - } - }); + columns.add( + new AbstractExportableColumn<>(Model.of("Exempted from final seminar rules")) { + @Override + public void populateItem( + Item> item, + String componentId, + final IModel iModel + ) { + item.add( + new AjaxCheckboxWrapper( + componentId, + LambdaModel.of( + iModel, + Project::isFinalSeminarRuleExempted, + Project::setFinalSeminarRuleExempted + ) + ) { + @Override + public void onChange(AjaxRequestTarget target, boolean selected) { + iModel.getObject().setFinalSeminarRuleExempted(selected); + iModel.setObject(projectService.save(iModel.getObject())); + if (selected) { + feedbackPanel.info(getString("exemptionGranted")); + } else { + feedbackPanel.info(getString("exemptionRevoked")); + } + target.add(exportableDataPanel); + target.add(feedbackPanel); + } - columns.add(new AbstractExportableColumn<>(Model.of("Exempted from final seminar rules")) { - @Override - public void populateItem(Item> item, String componentId, final IModel iModel) { - item.add(new AjaxCheckboxWrapper(componentId, LambdaModel.of(iModel, Project::isFinalSeminarRuleExempted, Project::setFinalSeminarRuleExempted)) { - @Override - public void onChange(AjaxRequestTarget target, boolean selected) { - iModel.getObject().setFinalSeminarRuleExempted(selected); - iModel.setObject(projectService.save(iModel.getObject())); - if (selected) { - feedbackPanel.info(getString("exemptionGranted")); - } else { - feedbackPanel.info(getString("exemptionRevoked")); + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled( + !(iModel.getObject().isFinalSeminarRuleExempted() && + finalSeminarService.findByProject(iModel.getObject()) != null) + ); + } } - target.add(exportableDataPanel); - target.add(feedbackPanel); - } + ); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(!(iModel.getObject().isFinalSeminarRuleExempted() && finalSeminarService.findByProject(iModel.getObject()) != null)); - } - }); + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(rowModel.getObject().isFinalSeminarRuleExempted()); + } } - - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(rowModel.getObject().isFinalSeminarRuleExempted()); - } - }); + ); return columns; } public class FilterForm extends Form { + private String titleString; public FilterForm(String id) { @@ -150,48 +181,60 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp } private void addSupervisorFilter() { - add(new EmployeeAutoComplete("supervisorFilter", LambdaModel.of(filter::getSupervisor, filter::setSupervisor)) { - @Override - protected void action(AjaxRequestTarget pTarget, User newSelection) { - pTarget.add(exportableDataPanel); + add( + new EmployeeAutoComplete( + "supervisorFilter", + LambdaModel.of(filter::getSupervisor, filter::setSupervisor) + ) { + @Override + protected void action(AjaxRequestTarget pTarget, User newSelection) { + pTarget.add(exportableDataPanel); + } } - }); + ); } private void addProjectTitleFilter() { - TextField titleField = new TextField<>("titleFilter", LambdaModel.of(() -> titleString, newTitleString -> titleString = newTitleString)); - titleField.add(new OnChangeAjaxBehavior() { - - @Override - protected void onUpdate(AjaxRequestTarget target) { - if (titleString != null && titleString.length() >= MIN_CHARS) { - filter.setTitleContains(titleString); - target.add(exportableDataPanel); - } else { - filter.setTitleContains(null); - target.add(exportableDataPanel); + TextField titleField = new TextField<>( + "titleFilter", + LambdaModel.of(() -> titleString, newTitleString -> titleString = newTitleString) + ); + titleField.add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + if (titleString != null && titleString.length() >= MIN_CHARS) { + filter.setTitleContains(titleString); + target.add(exportableDataPanel); + } else { + filter.setTitleContains(null); + target.add(exportableDataPanel); + } } - } - }); + ); add(titleField); } private void addAuthorFilter() { - add(new AuthorAutoComplete("authorFilter") { - @Override - protected void action(AjaxRequestTarget pTarget, User newSelection) { - filter.setAuthorUser(newSelection); - pTarget.add(exportableDataPanel); + add( + new AuthorAutoComplete("authorFilter") { + @Override + protected void action(AjaxRequestTarget pTarget, User newSelection) { + filter.setAuthorUser(newSelection); + pTarget.add(exportableDataPanel); + } } - }); + ); } private void addProjectStatusFilter() { - AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>("statusFilter", - new ArrayList<>(Collections.singletonList(ProjectStatus.ACTIVE)), - asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this)) { + AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>( + "statusFilter", + new ArrayList<>(Collections.singletonList(ProjectStatus.ACTIVE)), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onUpdate(AjaxRequestTarget target) { filter.setStatuses(new HashSet<>(getModelObject())); @@ -204,9 +247,12 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp } private void addProjectTypeFilter() { - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - projectTypeService.findWithModule(ProjectModule.FINAL_SEMINAR), projectTypeService.findWithModule(ProjectModule.FINAL_SEMINAR), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + projectTypeService.findWithModule(ProjectModule.FINAL_SEMINAR), + projectTypeService.findWithModule(ProjectModule.FINAL_SEMINAR), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -219,4 +265,4 @@ public class AdminFinalSeminarExemptionPage extends AbstractAdminProjectPage imp add(projectType); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPage.java index 43f99605d0..8b0c9be656 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPage.java @@ -6,10 +6,11 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminFinalSemin import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM }) public class AdminFinalSeminarPage extends AbstractAdminProjectPage implements MenuHighlightAdminFinalSeminars { - public AdminFinalSeminarPage() { + + public AdminFinalSeminarPage() { add(new AdminFinalSeminarDataPanel("dp")); add(new BookmarkablePageLink("exemptions", AdminFinalSeminarExemptionPage.class)); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPage.java index 6cfecd9f06..59dad683ab 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.Form; @@ -14,10 +16,8 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.ProjectTypeSettings; -import jakarta.inject.Inject; -import java.util.List; - public class AdminFinalSeminarSettingsPage extends AbstractAdminSystemPage { + static final String SETTINGS_FORM = "seminarSettingsForm"; static final String SEMINAR_CREATE_DAYS_AHEAD = "daysAheadToCreate"; static final String SEMINAR_MIN_DAYS_REGISTER_ACTIVE = "daysAheadToRegisterParticipation"; @@ -42,13 +42,20 @@ public class AdminFinalSeminarSettingsPage extends AbstractAdminSystemPage { public AdminFinalSeminarSettingsPage() { FinalSeminarSettingsForm form = new FinalSeminarSettingsForm(SETTINGS_FORM, getFinalSeminarSettings()); - form.add(new ListView<>(PROJECT_TYPE_LIST, getProjectTypes()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(PROJECT_TYPE, item.getModelObject().getName())); - item.add(new SeminarLevelSettingsForm(PROJECT_TYPE_FORM, item.getModel().map(ProjectType::getProjectTypeSettings))); + form.add( + new ListView<>(PROJECT_TYPE_LIST, getProjectTypes()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(PROJECT_TYPE, item.getModelObject().getName())); + item.add( + new SeminarLevelSettingsForm( + PROJECT_TYPE_FORM, + item.getModel().map(ProjectType::getProjectTypeSettings) + ) + ); + } } - }); + ); add(form); } @@ -74,26 +81,82 @@ public class AdminFinalSeminarSettingsPage extends AbstractAdminSystemPage { public FinalSeminarSettingsForm(String id, IModel model) { super(id, model); - add(new RequiredTextField<>(SEMINAR_MIN_DAYS_REGISTER_OPPONENT, - LambdaModel.of(model, FinalSeminarSettings::getDaysAheadToRegisterOpposition, FinalSeminarSettings::setDaysAheadToRegisterOpposition), - Integer.class)); - add(new RequiredTextField<>(SEMINAR_MIN_DAYS_REGISTER_ACTIVE, - LambdaModel.of(model, FinalSeminarSettings::getDaysAheadToRegisterParticipation, FinalSeminarSettings::setDaysAheadToRegisterParticipation), - Integer.class)); - add(new RequiredTextField<>(SEMINAR_CREATE_DAYS_AHEAD, - LambdaModel.of(model, FinalSeminarSettings::getDaysAheadToCreate, FinalSeminarSettings::setDaysAheadToCreate), - Integer.class)); - add(new Label(SEMINAR_THESIS_DAYS_AHEAD_LABEL, new StringResourceModel(SEMINAR_THESIS_DAYS_AHEAD_LABEL, this, null))); - add(new RequiredTextField<>(SEMINAR_THESIS_DAYS_AHEAD, - LambdaModel.of(model, FinalSeminarSettings::getDaysAheadToUploadThesis, FinalSeminarSettings::setDaysAheadToUploadThesis), - Integer.class)); - add(new CheckBox(SEMINAR_PDF, - LambdaModel.of(model, FinalSeminarSettings::isThesisMustBePDF, FinalSeminarSettings::setThesisMustBePDF)) - .setOutputMarkupId(true)); - add(new RequiredTextField<>("oppositionPriorityDays", LambdaModel.of(model, FinalSeminarSettings::getOppositionPriorityDays, FinalSeminarSettings::setOppositionPriorityDays), Integer.class)); - TextField evaluationURL = new TextField<>(EVALUATION_URL, - LambdaModel.of(model, FinalSeminarSettings::getEvaluationURL, FinalSeminarSettings::setEvaluationURL)); - evaluationURL.add(new UrlValidator(new String[]{"http", "https"})); + add( + new RequiredTextField<>( + SEMINAR_MIN_DAYS_REGISTER_OPPONENT, + LambdaModel.of( + model, + FinalSeminarSettings::getDaysAheadToRegisterOpposition, + FinalSeminarSettings::setDaysAheadToRegisterOpposition + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + SEMINAR_MIN_DAYS_REGISTER_ACTIVE, + LambdaModel.of( + model, + FinalSeminarSettings::getDaysAheadToRegisterParticipation, + FinalSeminarSettings::setDaysAheadToRegisterParticipation + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + SEMINAR_CREATE_DAYS_AHEAD, + LambdaModel.of( + model, + FinalSeminarSettings::getDaysAheadToCreate, + FinalSeminarSettings::setDaysAheadToCreate + ), + Integer.class + ) + ); + add( + new Label( + SEMINAR_THESIS_DAYS_AHEAD_LABEL, + new StringResourceModel(SEMINAR_THESIS_DAYS_AHEAD_LABEL, this, null) + ) + ); + add( + new RequiredTextField<>( + SEMINAR_THESIS_DAYS_AHEAD, + LambdaModel.of( + model, + FinalSeminarSettings::getDaysAheadToUploadThesis, + FinalSeminarSettings::setDaysAheadToUploadThesis + ), + Integer.class + ) + ); + add( + new CheckBox( + SEMINAR_PDF, + LambdaModel.of( + model, + FinalSeminarSettings::isThesisMustBePDF, + FinalSeminarSettings::setThesisMustBePDF + ) + ).setOutputMarkupId(true) + ); + add( + new RequiredTextField<>( + "oppositionPriorityDays", + LambdaModel.of( + model, + FinalSeminarSettings::getOppositionPriorityDays, + FinalSeminarSettings::setOppositionPriorityDays + ), + Integer.class + ) + ); + TextField evaluationURL = new TextField<>( + EVALUATION_URL, + LambdaModel.of(model, FinalSeminarSettings::getEvaluationURL, FinalSeminarSettings::setEvaluationURL) + ); + evaluationURL.add(new UrlValidator(new String[] { "http", "https" })); add(evaluationURL); } @@ -102,31 +165,61 @@ public class AdminFinalSeminarSettingsPage extends AbstractAdminSystemPage { finalSeminarSettingsService.save(getModelObject()); info("Settings saved"); } - } private class SeminarLevelSettingsForm extends Form { public SeminarLevelSettingsForm(String id, IModel model) { super(id, model); - add(new RequiredTextField<>(SEMINAR_MAX_OPPONENTS, - LambdaModel.of(model, ProjectTypeSettings::getMaxOpponentsOnFinalSeminar, ProjectTypeSettings::setMaxOpponentsOnFinalSeminar), - Integer.class)); - add(new RequiredTextField<>(SEMINAR_MAX_PARTICIPANTS, - LambdaModel.of(model, ProjectTypeSettings::getMaxFinalSeminarActiveParticipation, ProjectTypeSettings::setMaxFinalSeminarActiveParticipation), - Integer.class)); - add(new RequiredTextField<>(SEMINAR_MIN_OPPONENTS, - LambdaModel.of(model, ProjectTypeSettings::getMinOpponentsOnFinalSeminar, ProjectTypeSettings::setMinOpponentsOnFinalSeminar), - Integer.class)); - add(new RequiredTextField<>(SEMINAR_MIN_PARTICIPANTS, - LambdaModel.of(model, ProjectTypeSettings::getMinFinalSeminarActiveParticipation, ProjectTypeSettings::setMinFinalSeminarActiveParticipation), - Integer.class)); + add( + new RequiredTextField<>( + SEMINAR_MAX_OPPONENTS, + LambdaModel.of( + model, + ProjectTypeSettings::getMaxOpponentsOnFinalSeminar, + ProjectTypeSettings::setMaxOpponentsOnFinalSeminar + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + SEMINAR_MAX_PARTICIPANTS, + LambdaModel.of( + model, + ProjectTypeSettings::getMaxFinalSeminarActiveParticipation, + ProjectTypeSettings::setMaxFinalSeminarActiveParticipation + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + SEMINAR_MIN_OPPONENTS, + LambdaModel.of( + model, + ProjectTypeSettings::getMinOpponentsOnFinalSeminar, + ProjectTypeSettings::setMinOpponentsOnFinalSeminar + ), + Integer.class + ) + ); + add( + new RequiredTextField<>( + SEMINAR_MIN_PARTICIPANTS, + LambdaModel.of( + model, + ProjectTypeSettings::getMinFinalSeminarActiveParticipation, + ProjectTypeSettings::setMinFinalSeminarActiveParticipation + ), + Integer.class + ) + ); } @Override protected void onSubmit() { projectTypeService.save(getModelObject().getProjectType()); } - } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/AttendingPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/AttendingPanel.java index 5983aeb34d..66f701a982 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/AttendingPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/AttendingPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -20,9 +22,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class AttendingPanel extends GenericPanel { private ListView participations; @@ -35,32 +34,54 @@ public class AttendingPanel extends GenericPanel { public AttendingPanel(String id, final IModel model) { super(id, model); - add(new AutoHidingListView<>("oppositions", getOppositions()) { - @Override - protected void populateItem(ListItem item) { - IModel finalSeminarModel = item.getModel().map(FinalSeminarOpposition::getFinalSeminar); - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), String.valueOf(finalSeminarModel.getObject().getProject().getId())); - BookmarkablePageLink link = new BookmarkablePageLink<>("seminarLink", ProjectFinalSeminarDetailsPage.class, pp); - item.add(link); - link.add(new Label("seminarLabel", finalSeminarModel.map(FinalSeminar::getProject).map(Project::getTitle))); - item.add(new DateLabel("date", finalSeminarModel.map(FinalSeminar::getStartDate), DateStyle.DATETIME)); - item.add(new EnumLabel<>("grade", item.getModel().map(FinalSeminarParticipation::getGrade)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject() != null); - } - }); + add( + new AutoHidingListView<>("oppositions", getOppositions()) { + @Override + protected void populateItem(ListItem item) { + IModel finalSeminarModel = item + .getModel() + .map(FinalSeminarOpposition::getFinalSeminar); + PageParameters pp = new PageParameters(); + pp.add( + PageParameterKeys.MAP.get(Project.class), + String.valueOf(finalSeminarModel.getObject().getProject().getId()) + ); + BookmarkablePageLink link = new BookmarkablePageLink<>( + "seminarLink", + ProjectFinalSeminarDetailsPage.class, + pp + ); + item.add(link); + link.add( + new Label( + "seminarLabel", + finalSeminarModel.map(FinalSeminar::getProject).map(Project::getTitle) + ) + ); + item.add( + new DateLabel("date", finalSeminarModel.map(FinalSeminar::getStartDate), DateStyle.DATETIME) + ); + item.add( + new EnumLabel<>("grade", item.getModel().map(FinalSeminarParticipation::getGrade)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject() != null); + } + } + ); + } } - }); - add(new Label("noOppositions", "No oppositions"){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getOppositions().getObject().isEmpty()); + ); + add( + new Label("noOppositions", "No oppositions") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getOppositions().getObject().isEmpty()); + } } - }); + ); final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); add(wmc); @@ -68,14 +89,27 @@ public class AttendingPanel extends GenericPanel { participations = new AutoHidingListView<>("participations", getParticipations()) { @Override protected void populateItem(final ListItem item) { - IModel seminarModel = item.getModel().map(FinalSeminarActiveParticipation::getFinalSeminar); + IModel seminarModel = item + .getModel() + .map(FinalSeminarActiveParticipation::getFinalSeminar); PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), String.valueOf(seminarModel.getObject().getProject().getId())); - BookmarkablePageLink link = new BookmarkablePageLink<>("seminarLink", ProjectFinalSeminarDetailsPage.class, pp); + pp.add( + PageParameterKeys.MAP.get(Project.class), + String.valueOf(seminarModel.getObject().getProject().getId()) + ); + BookmarkablePageLink link = new BookmarkablePageLink<>( + "seminarLink", + ProjectFinalSeminarDetailsPage.class, + pp + ); item.add(link); link.add(new Label("seminarLabel", seminarModel.map(FinalSeminar::getProject).map(Project::getTitle))); item.add(new DateLabel("date", seminarModel.map(FinalSeminar::getStartDate), DateStyle.DATETIME)); - Component removeParticipation = new AjaxConfirmationLink<>("remove", seminarModel, "Are you sure you want to delete this active participation?") { + Component removeParticipation = new AjaxConfirmationLink<>( + "remove", + seminarModel, + "Are you sure you want to delete this active participation?" + ) { @Override public void onClick(AjaxRequestTarget target) { seminarModel.getObject().removeActiveParticipant(SciProSession.get().getUser()); @@ -84,42 +118,52 @@ public class AttendingPanel extends GenericPanel { target.add(wmc); } }; - removeParticipation.setVisible(!finalSeminarActiveParticipationService.findByFinalSeminarUser( - seminarModel.getObject(), SciProSession.get().getUser()).hasGrade()); + removeParticipation.setVisible( + !finalSeminarActiveParticipationService + .findByFinalSeminarUser(seminarModel.getObject(), SciProSession.get().getUser()) + .hasGrade() + ); item.add(removeParticipation); - item.add(new EnumLabel<>("grade", item.getModel().map(FinalSeminarParticipation::getGrade)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject() != null); + item.add( + new EnumLabel<>("grade", item.getModel().map(FinalSeminarParticipation::getGrade)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject() != null); + } } - }); + ); } }; wmc.add(participations); - add(new Label("noParticipations", "No participations"){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getParticipations().getObject().isEmpty()); + add( + new Label("noParticipations", "No participations") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getParticipations().getObject().isEmpty()); + } } - }); + ); } - private void refresh(){ + private void refresh() { participations.detach(); } - private LoadableDetachableModel> getOppositions(){ + private LoadableDetachableModel> getOppositions() { return new LoadableDetachableModel<>() { @Override protected List load() { - return finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(getModelObject().getProjectType(), SciProSession.get().getUser()); + return finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType( + getModelObject().getProjectType(), + SciProSession.get().getUser() + ); } }; } - private LoadableDetachableModel> getParticipations(){ + private LoadableDetachableModel> getParticipations() { return new LoadableDetachableModel<>() { @Override protected List load() { diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanel.java index b008aeda80..fe82b15be8 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanel.java @@ -1,6 +1,5 @@ package se.su.dsv.scipro.finalseminar; - import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.markup.html.panel.Panel; @@ -12,14 +11,17 @@ import se.su.dsv.scipro.report.Report; public class DownloadPdfReportPanel extends Panel { - public static final String DOWNLOAD_PDF = "downloadPdf"; public static final String PDF_LABEL = "pdfLabel"; public static final String PDF_UPLOAD_DATE = "pdfUploadDate"; - public DownloadPdfReportPanel(String id, IModel finalSeminar, final IModel report, final ReportPdfResource reportPdfResource) { + public DownloadPdfReportPanel( + String id, + IModel finalSeminar, + final IModel report, + final ReportPdfResource reportPdfResource + ) { super(id, finalSeminar); - ResourceLink resourceLink = new ResourceLink<>(DOWNLOAD_PDF, reportPdfResource) { @Override protected void onConfigure() { @@ -29,6 +31,8 @@ public class DownloadPdfReportPanel extends Panel { }; add(resourceLink); resourceLink.add(new Label(PDF_LABEL, reportPdfResource.getFileName())); - resourceLink.add(new DateLabel(PDF_UPLOAD_DATE, LambdaModel.of(report, Report::getLastModified, Report::setLastModified))); + resourceLink.add( + new DateLabel(PDF_UPLOAD_DATE, LambdaModel.of(report, Report::getLastModified, Report::setLastModified)) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDataPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDataPanel.java index 211a0f8c4f..df0b2e05c8 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDataPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.function.Function; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -29,12 +34,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.function.Function; - public class FinalSeminarDataPanel extends Panel { @Inject @@ -43,11 +42,10 @@ public class FinalSeminarDataPanel extends Panel { private FinalSeminarService.Filter filter; private boolean supervisorView; private RadioGroup group; - private ExportableDataPanel dataTable; + private ExportableDataPanel dataTable; public FinalSeminarDataPanel(String id, boolean isSupervisorView) { super(id); - supervisorView = isSupervisorView; addModalWindow(); addFiltering(); @@ -69,44 +67,51 @@ public class FinalSeminarDataPanel extends Panel { group = new RadioGroup<>("dateChoice", new Model<>(Boolean.TRUE)); add(group); - group.add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(dataTable); - if (group.getModelObject()) { - filter.setFromDate(new Date()); - filter.setToDate(null); - } else { - filter.setToDate(new Date()); - filter.setFromDate(null); + group.add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(dataTable); + if (group.getModelObject()) { + filter.setFromDate(new Date()); + filter.setToDate(null); + } else { + filter.setToDate(new Date()); + filter.setFromDate(null); + } } } - }); + ); group.add(new Radio<>("future", Model.of(Boolean.TRUE)).setOutputMarkupId(true)); group.add(new Radio<>("past", Model.of(Boolean.FALSE)).setOutputMarkupId(true)); - add(new AjaxCheckBox("onlyMy", new Model<>()) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - if (getModelObject()) { - filter.setHeadSupervisor(SciProSession.get().getUser()); - } else { - filter.setHeadSupervisor(null); + add( + new AjaxCheckBox("onlyMy", new Model<>()) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + if (getModelObject()) { + filter.setHeadSupervisor(SciProSession.get().getUser()); + } else { + filter.setHeadSupervisor(null); + } + target.add(dataTable); } - target.add(dataTable); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(supervisorView); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(supervisorView); + } } - }); + ); } private void addDataTable() { - SortableDataProvider provider = new FilteredDataProvider<>(finalSeminarService, Model.of(filter)); + SortableDataProvider provider = new FilteredDataProvider<>( + finalSeminarService, + Model.of(filter) + ); provider.setSort("startDate", SortOrder.DESCENDING); dataTable = new ExportableDataPanel<>("dp", createColumns(), provider); add(dataTable); @@ -115,33 +120,53 @@ public class FinalSeminarDataPanel extends Panel { private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of("Date"), FinalSeminar::getStartDate, "startDate", DateStyle.DATETIME)); - columns.add(new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Title"), "project.title") { - @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - cellItem.add(LinkWrapper.apply(componentId, new Function<>() { - @Override - public AbstractLink apply(final String id) { - final Class pageClass = getRedirectPage(); - final PageParameters pp = new PageParameters(); - pp.set(PageParameterKeys.MAP.get(Project.class), rowModel.getObject().getProject().getId()); - final BookmarkablePageLink link = new BookmarkablePageLink<>(id, pageClass, pp); - link.setBody(rowModel.map(FinalSeminar::getProject).map(Project::getTitle)); - return link; - } + columns.add( + new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName()) + ); + columns.add( + new AbstractColumn<>(Model.of("Title"), "project.title") { + @Override + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + cellItem.add( + LinkWrapper.apply( + componentId, + new Function<>() { + @Override + public AbstractLink apply(final String id) { + final Class pageClass = getRedirectPage(); + final PageParameters pp = new PageParameters(); + pp.set( + PageParameterKeys.MAP.get(Project.class), + rowModel.getObject().getProject().getId() + ); + final BookmarkablePageLink link = new BookmarkablePageLink<>( + id, + pageClass, + pp + ); + link.setBody(rowModel.map(FinalSeminar::getProject).map(Project::getTitle)); + return link; + } - private Class getRedirectPage() { - return iSupervisorView() ? - SupervisorFinalSeminarDetailsPage.class : - ProjectFinalSeminarDetailsPage.class; - } - })); + private Class getRedirectPage() { + return iSupervisorView() + ? SupervisorFinalSeminarDetailsPage.class + : ProjectFinalSeminarDetailsPage.class; + } + } + ) + ); + } } - }); + ); return columns; } private boolean iSupervisorView() { return supervisorView; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDateTimeComponent.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDateTimeComponent.java index 52fb0e2401..9b06d5d645 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDateTimeComponent.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDateTimeComponent.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.finalseminar; -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.components.BootstrapDateTimeComponent; - import jakarta.inject.Inject; import java.util.Date; +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.components.BootstrapDateTimeComponent; public class FinalSeminarDateTimeComponent extends BootstrapDateTimeComponent { + @Inject private FinalSeminarSettingsService finalSeminarSettings; @@ -23,8 +23,8 @@ public class FinalSeminarDateTimeComponent extends BootstrapDateTimeComponent { @Override protected IModel dateHelpText() { return () -> { - int daysAhead = finalSeminarSettings.getInstance().getDaysAheadToCreate(); - return "(at least " + daysAhead + " work days away from now)"; + int daysAhead = finalSeminarSettings.getInstance().getDaysAheadToCreate(); + return "(at least " + daysAhead + " work days away from now)"; }; } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParameters.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParameters.java index b63db6bd77..ce3ee4aa15 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParameters.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParameters.java @@ -1,10 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import java.io.Serializable; import se.su.dsv.scipro.system.Language; -import java.io.Serializable; - public class FinalSeminarDetailsParameters implements Serializable { + private String room; private Boolean manualParticipants; private int maxParticipants; @@ -26,7 +26,15 @@ public class FinalSeminarDetailsParameters implements Serializable { } FinalSeminarDetails asDetails() { - return new FinalSeminarDetails(room, manualParticipants, maxParticipants, maxOpponents, presentationLanguage, reportLanguage, extraInfo); + return new FinalSeminarDetails( + room, + manualParticipants, + maxParticipants, + maxOpponents, + presentationLanguage, + reportLanguage, + extraInfo + ); } public String getRoom() { diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParametersPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParametersPanel.java index 245f9eb696..10dac30c17 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParametersPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarDetailsParametersPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.form.*; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -12,83 +14,109 @@ import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.system.Language; -import jakarta.inject.Inject; -import java.util.List; - public class FinalSeminarDetailsParametersPanel extends GenericPanel { @Inject GeneralSystemSettingsService generalSystemSettingsService; public FinalSeminarDetailsParametersPanel( - String id, - IModel model, - int minActiveParticipants, - int minOpponents) - { + String id, + IModel model, + int minActiveParticipants, + int minOpponents + ) { super(id, model); - - RequiredTextField room = new RequiredTextField<>("room", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getRoom, - FinalSeminarDetailsParameters::setRoom)); + RequiredTextField room = new RequiredTextField<>( + "room", + LambdaModel.of(model, FinalSeminarDetailsParameters::getRoom, FinalSeminarDetailsParameters::setRoom) + ); room.add(StringValidator.maximumLength(255)); add(room); - IModel externalRoomBookingURL = LoadableDetachableModel.of(generalSystemSettingsService::getGeneralSystemSettingsInstance) - .map(GeneralSystemSettings::getExternalRoomBookingURL); - add(new ExternalLink("externalRoomBooking", externalRoomBookingURL) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); + IModel externalRoomBookingURL = LoadableDetachableModel.of( + generalSystemSettingsService::getGeneralSystemSettingsInstance + ).map(GeneralSystemSettings::getExternalRoomBookingURL); + add( + new ExternalLink("externalRoomBooking", externalRoomBookingURL) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } } - }); + ); - add(new CheckBox("manualParticipants", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getManualParticipants, - FinalSeminarDetailsParameters::setManualParticipants)).setOutputMarkupId(true)); + add( + new CheckBox( + "manualParticipants", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getManualParticipants, + FinalSeminarDetailsParameters::setManualParticipants + ) + ).setOutputMarkupId(true) + ); - RequiredTextField maxParticipants = new RequiredTextField<>("maxParticipants", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getMaxParticipants, - FinalSeminarDetailsParameters::setMaxParticipants), - Integer.class); + RequiredTextField maxParticipants = new RequiredTextField<>( + "maxParticipants", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getMaxParticipants, + FinalSeminarDetailsParameters::setMaxParticipants + ), + Integer.class + ); maxParticipants.add(RangeValidator.minimum(minActiveParticipants)); add(maxParticipants); - RequiredTextField maxOpponents = new RequiredTextField<>("maxOpponents", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getMaxOpponents, - FinalSeminarDetailsParameters::setMaxOpponents), - Integer.class); + RequiredTextField maxOpponents = new RequiredTextField<>( + "maxOpponents", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getMaxOpponents, + FinalSeminarDetailsParameters::setMaxOpponents + ), + Integer.class + ); maxOpponents.add(RangeValidator.minimum(minOpponents)); add(maxOpponents); List languages = java.util.Arrays.asList(Language.values()); - DropDownChoice presentationLanguage = new DropDownChoice<>("presentationLanguage", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getPresentationLanguage, - FinalSeminarDetailsParameters::setPresentationLanguage), - languages, - new EnumChoiceRenderer<>(this)); + DropDownChoice presentationLanguage = new DropDownChoice<>( + "presentationLanguage", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getPresentationLanguage, + FinalSeminarDetailsParameters::setPresentationLanguage + ), + languages, + new EnumChoiceRenderer<>(this) + ); presentationLanguage.setRequired(true); add(presentationLanguage); - DropDownChoice reportLanguage = new DropDownChoice<>("reportLanguage", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getReportLanguage, - FinalSeminarDetailsParameters::setReportLanguage), - languages, new EnumChoiceRenderer<>(this)); + DropDownChoice reportLanguage = new DropDownChoice<>( + "reportLanguage", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getReportLanguage, + FinalSeminarDetailsParameters::setReportLanguage + ), + languages, + new EnumChoiceRenderer<>(this) + ); reportLanguage.setRequired(true); add(reportLanguage); - TextArea extraInfo = new TextArea<>("extraInfo", - LambdaModel.of(model, - FinalSeminarDetailsParameters::getExtraInfo, - FinalSeminarDetailsParameters::setExtraInfo)); + TextArea extraInfo = new TextArea<>( + "extraInfo", + LambdaModel.of( + model, + FinalSeminarDetailsParameters::getExtraInfo, + FinalSeminarDetailsParameters::setExtraInfo + ) + ); add(extraInfo); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPage.java index b0401ee8c9..432ae75ffd 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPage.java @@ -4,6 +4,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.project.pages.ProjectPage; public class FinalSeminarProjectListPage extends ProjectPage { + public FinalSeminarProjectListPage(PageParameters pp) { super(pp); add(new FinalSeminarDataPanel("dp", false)); diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanel.java index 87a360cf8c..cf8286641a 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.time.Clock; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.*; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -12,18 +18,14 @@ import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.SeminarEvent; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.Clock; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.*; - public class MoveFinalSeminarPanel extends GenericPanel { + @Inject private FinalSeminarService finalSeminarService; + @Inject private NotificationController notificationController; + @Inject private Clock clock; @@ -39,20 +41,13 @@ public class MoveFinalSeminarPanel extends GenericPanel { public MoveForm(String form, final IModel model) { super(form, model); - - RequiredTextField dateField = new RequiredTextField<>( - "date", - dateModel, - LocalDate.class); + RequiredTextField dateField = new RequiredTextField<>("date", dateModel, LocalDate.class); dateField.setModelObject(toLocalDate(model.getObject().getStartDate())); dateField.add(new BootstrapDatePicker()); dateField.add(new SeminarDateValidator(model.map(FinalSeminar::getProject))); add(dateField); - RequiredTextField timeField = new RequiredTextField<>( - "time", - timeModel, - LocalTime.class); + RequiredTextField timeField = new RequiredTextField<>("time", timeModel, LocalTime.class); timeField.setModelObject(toLocalTime(model.getObject().getStartDate())); timeField.add(new BootstrapTimePicker()); add(timeField); @@ -71,14 +66,16 @@ public class MoveFinalSeminarPanel extends GenericPanel { @Override protected void onSubmit() { LocalDateTime to = dateModel.getObject().atTime(timeModel.getObject()); - Either move = - finalSeminarService.move(getModelObject(), to); + Either move = finalSeminarService.move(getModelObject(), to); if (move.isRight()) { - notificationController.notifySeminar(getModelObject(), SeminarEvent.Event.DATE_CHANGED, new NotificationSource()); + notificationController.notifySeminar( + getModelObject(), + SeminarEvent.Event.DATE_CHANGED, + new NotificationSource() + ); MoveForm.this.success("Final seminar moved to the new date"); - } - else { + } else { error("Could not move the final seminar to that date"); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/OpposeColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/OpposeColumnPanel.java index ed3ae21d06..3fac802f03 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/OpposeColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/OpposeColumnPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.text.SimpleDateFormat; +import java.util.Date; import org.apache.wicket.Component; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.link.StatelessLink; @@ -12,10 +15,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.text.SimpleDateFormat; -import java.util.Date; - public abstract class OpposeColumnPanel extends Panel { public static final String LINK = "link"; @@ -26,14 +25,18 @@ public abstract class OpposeColumnPanel extends Panel { public abstract void onClick(IModel clickedModel); - public OpposeColumnPanel(String id, final IModel finalSeminarModel, final IModel projectModel) { + public OpposeColumnPanel( + String id, + final IModel finalSeminarModel, + final IModel projectModel + ) { super(id, finalSeminarModel); - - final Either canOppose = - finalSeminarService.canOppose(SciProSession.get().getUser(), finalSeminarModel.getObject(), projectModel.getObject()); - final Component opposeLink = canOppose.fold( - this::showError, - allowed -> new OpposeLink(LINK, finalSeminarModel) + final Either canOppose = finalSeminarService.canOppose( + SciProSession.get().getUser(), + finalSeminarModel.getObject(), + projectModel.getObject() + ); + final Component opposeLink = canOppose.fold(this::showError, allowed -> new OpposeLink(LINK, finalSeminarModel) ); add(opposeLink); @@ -41,16 +44,22 @@ public abstract class OpposeColumnPanel extends Panel { private Component showError(OppositionRegistrationErrorStatus notAllowed) { return notAllowed.fold( - ungradedOpposition -> getLabel("You have ungraded oppositions"), - finalSeminarCancelled -> getLabel("This seminar has been cancelled"), - alreadyParticipating -> getLabel("You are already participating on this seminar"), - alreadyHappened -> getLabel("This seminar has already happened"), - tooManyOpponents -> getLabel("This seminar has reached the maximum number of opponents"), - priorityForSeminarAuthors -> getLabel("Authors with their own final seminar have " + - "priority to register for " + priorityForSeminarAuthors.getPriorityDays() + - " day(s). This priority will end at " + asDateTime(Date.from(priorityForSeminarAuthors.getPriorityEnd()))), - alreadyOpposed -> getLabel("You have already completed an opposition and can not perform a second one"), - manualOpponents -> getLabel("Opponents for this seminar are handled by the supervisor")); + ungradedOpposition -> getLabel("You have ungraded oppositions"), + finalSeminarCancelled -> getLabel("This seminar has been cancelled"), + alreadyParticipating -> getLabel("You are already participating on this seminar"), + alreadyHappened -> getLabel("This seminar has already happened"), + tooManyOpponents -> getLabel("This seminar has reached the maximum number of opponents"), + priorityForSeminarAuthors -> + getLabel( + "Authors with their own final seminar have " + + "priority to register for " + + priorityForSeminarAuthors.getPriorityDays() + + " day(s). This priority will end at " + + asDateTime(Date.from(priorityForSeminarAuthors.getPriorityEnd())) + ), + alreadyOpposed -> getLabel("You have already completed an opposition and can not perform a second one"), + manualOpponents -> getLabel("Opponents for this seminar are handled by the supervisor") + ); } public String asDateTime(Date date) { @@ -60,12 +69,12 @@ public abstract class OpposeColumnPanel extends Panel { private Component getLabel(final String label) { // Dumb workaround to get the tag transformed into a - return new StatelessLink(LINK){ + return new StatelessLink(LINK) { @Override public void onClick() {} } - .setBody(Model.of(label)) - .setEnabled(false); + .setBody(Model.of(label)) + .setEnabled(false); } private class OpposeLink extends Link { diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/OppositionReportPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/OppositionReportPage.java index f0fcc13dfa..fc35785ba1 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/OppositionReportPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/OppositionReportPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.TextArea; @@ -17,8 +18,6 @@ import se.su.dsv.scipro.report.OppositionReportService; import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class OppositionReportPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorOpposition { public static final String THESIS_SUMMARY = "thesisSummary"; @@ -26,12 +25,12 @@ public class OppositionReportPage extends AbstractProjectDetailsPage implements @Inject private FinalSeminarOppositionRepo finalSeminarOppositionRepo; + @Inject private OppositionReportService oppositionReportService; public OppositionReportPage(PageParameters pp) { super(pp); - if (pp.get("oid").isNull()) { throw new RestartResponseException(ProjectDetailsPage.class, pp); } @@ -44,26 +43,38 @@ public class OppositionReportPage extends AbstractProjectDetailsPage implements final IModel report = getOppositionReport(opposition); - add(new ViewAttachmentPanel("thesisFile", report.map(or -> or.getFinalSeminarOpposition().getFinalSeminar().getDocument().getFileDescription()))); + add( + new ViewAttachmentPanel( + "thesisFile", + report.map(or -> or.getFinalSeminarOpposition().getFinalSeminar().getDocument().getFileDescription()) + ) + ); - add(new FillOutReportPanel<>(FILL_OUT_REPORT, report) { - { - TextArea textArea = new TextArea<>(THESIS_SUMMARY, LambdaModel.of(report, OppositionReport::getThesisSummary, OppositionReport::setThesisSummary)); - textArea.add(new AutoSavingBehaviour() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - oppositionReportService.save(report.getObject()); - } - }); - add(textArea); - } + add( + new FillOutReportPanel<>(FILL_OUT_REPORT, report) { + { + TextArea textArea = new TextArea<>( + THESIS_SUMMARY, + LambdaModel.of(report, OppositionReport::getThesisSummary, OppositionReport::setThesisSummary) + ); + textArea.add( + new AutoSavingBehaviour() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + oppositionReportService.save(report.getObject()); + } + } + ); + add(textArea); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(opposition.getUser().equals(SciProSession.get().getUser())); + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(opposition.getUser().equals(SciProSession.get().getUser())); + } } - }); + ); } private IModel getOppositionReport(final FinalSeminarOpposition opposition) { diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanel.java index 2a1bde4ab9..5d4bff6f06 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -15,8 +16,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - @ProjectModuleComponent(ProjectModule.FINAL_SEMINAR) public class OverviewSeminarPanel extends Panel { @@ -32,7 +31,6 @@ public class OverviewSeminarPanel extends Panel { public OverviewSeminarPanel(String id, final IModel model) { super(id, model); - final FinalSeminar seminar = finalSeminarService.findByProject(model.getObject()); PageParameters pp = new PageParameters(); diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateColumnPanel.java index f4dcdb973f..bfe9563eed 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ParticipateColumnPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.Component; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.link.StatelessLink; @@ -10,8 +11,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; - public abstract class ParticipateColumnPanel extends Panel { public static final String LINK = "link"; @@ -24,12 +23,10 @@ public abstract class ParticipateColumnPanel extends Panel { public ParticipateColumnPanel(String id, final IModel finalSeminarModel) { super(id, finalSeminarModel); - final Either canActiveParticipate = - finalSeminarService.canActiveParticipate(SciProSession.get().getUser(), finalSeminarModel.getObject()); - final Component participateLink = canActiveParticipate.fold( - this::showError, - allowed -> new ParticipateColumnPanel.ParticipateLink(LINK, finalSeminarModel) + finalSeminarService.canActiveParticipate(SciProSession.get().getUser(), finalSeminarModel.getObject()); + final Component participateLink = canActiveParticipate.fold(this::showError, allowed -> + new ParticipateColumnPanel.ParticipateLink(LINK, finalSeminarModel) ); add(participateLink); @@ -37,24 +34,21 @@ public abstract class ParticipateColumnPanel extends Panel { private Component showError(ActiveParticipationRegistrationErrorStatus notAllowed) { return notAllowed.fold( - tooManyParticipants -> getLabel("This seminar has reached the maximum number of active participants"), - manualParticipants -> getLabel("Active participants for this seminar are handled by the supervisor"), - alreadyParticipating -> getLabel("You are already participating in this seminar"), - alreadyHappened -> getLabel("This seminar has already happened"), - finalSeminarCancelled -> getLabel("This seminar has been cancelled")); - + tooManyParticipants -> getLabel("This seminar has reached the maximum number of active participants"), + manualParticipants -> getLabel("Active participants for this seminar are handled by the supervisor"), + alreadyParticipating -> getLabel("You are already participating in this seminar"), + alreadyHappened -> getLabel("This seminar has already happened"), + finalSeminarCancelled -> getLabel("This seminar has been cancelled") + ); } private Component getLabel(final String label) { // Dumb workaround to get the tag transformed into a final StatelessLink components = new StatelessLink<>(LINK) { @Override - public void onClick() { - } + public void onClick() {} }; - return components - .setBody(Model.of(label)) - .setEnabled(false); + return components.setBody(Model.of(label)).setEnabled(false); } private class ParticipateLink extends Link { @@ -70,5 +64,4 @@ public abstract class ParticipateColumnPanel extends Panel { ParticipateColumnPanel.this.onClick(getModel()); } } - -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanel.java index 40bb5744a8..83831b9869 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -13,49 +16,62 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class ProjectActiveParticipationListPanel extends GenericPanel { + @Inject private FinalSeminarService finalSeminarService; public ProjectActiveParticipationListPanel(final String id, final IModel model) { super(id, model); - add(new ListView<>("authors", model.map(Project::getProjectParticipants).map(ArrayList::new)) { - @Override - protected void populateItem(ListItem item) { - IModel> participations = LoadableDetachableModel.of(() -> + add( + new ListView<>("authors", model.map(Project::getProjectParticipants).map(ArrayList::new)) { + @Override + protected void populateItem(ListItem item) { + IModel> participations = LoadableDetachableModel.of(() -> finalSeminarService.findUserParticipating( - ProjectActiveParticipationListPanel.this.getModelObject(), - item.getModelObject())); + ProjectActiveParticipationListPanel.this.getModelObject(), + item.getModelObject() + ) + ); - item.add(new UserLabel("author", item.getModel())); + item.add(new UserLabel("author", item.getModel())); - IModel countRequired = model + IModel countRequired = model .map(Project::getProjectType) .map(ProjectType::getProjectTypeSettings) .map(ProjectTypeSettings::getMinActiveParticipationsToBeGraded); - item.add(new Label("count_required", countRequired)); - IModel countPerformed = participations.map(this::countApproved); - item.add(new Label("count_approved", countPerformed)); + item.add(new Label("count_required", countRequired)); + IModel countPerformed = participations.map(this::countApproved); + item.add(new Label("count_approved", countPerformed)); - item.add(new ListView<>("participations", participations) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("seminar", item.getModel() - .map(FinalSeminarParticipation::getFinalSeminar) - .map(FinalSeminar::getProjectTitle))); - item.add(new EnumLabel<>("grade", item.getModel() - .map(FinalSeminarActiveParticipation::getGrade))); - } - }); - } + item.add( + new ListView<>("participations", participations) { + @Override + protected void populateItem(ListItem item) { + item.add( + new Label( + "seminar", + item + .getModel() + .map(FinalSeminarParticipation::getFinalSeminar) + .map(FinalSeminar::getProjectTitle) + ) + ); + item.add( + new EnumLabel<>( + "grade", + item.getModel().map(FinalSeminarActiveParticipation::getGrade) + ) + ); + } + } + ); + } - private long countApproved(List p) { - return p.stream().filter(FinalSeminarParticipation::isApproved).count(); + private long countApproved(List p) { + return p.stream().filter(FinalSeminarParticipation::isApproved).count(); + } } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanel.java index bb9a5cb8de..82e036200b 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.panel.Panel; @@ -11,8 +12,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.List; - public class ProjectDetailsPanel extends Panel { public static final String PROJECT_TYPE = "projectType"; @@ -24,24 +23,36 @@ public class ProjectDetailsPanel extends Panel { public ProjectDetailsPanel(String id, IModel projectModel) { super(id, projectModel); - add(new Label(PROJECT_TYPE, projectModel.map(Project::getProjectTypeName))); - add(new UserLinkPanel(PROJECT_HEAD_SUPERVISOR, LambdaModel.of(projectModel, Project::getHeadSupervisor, Project::setHeadSupervisor))); + add( + new UserLinkPanel( + PROJECT_HEAD_SUPERVISOR, + LambdaModel.of(projectModel, Project::getHeadSupervisor, Project::setHeadSupervisor) + ) + ); - IModel> coSupervisors = new ListAdapterModel<>(LambdaModel.of(projectModel, Project::getCoSupervisors, Project::setCoSupervisors)); - add(new AutoHidingListView<>(PROJECT_CO_SUPERVISORS, coSupervisors) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(PROJECT_CO_SUPERVISOR, item.getModel())); + IModel> coSupervisors = new ListAdapterModel<>( + LambdaModel.of(projectModel, Project::getCoSupervisors, Project::setCoSupervisors) + ); + add( + new AutoHidingListView<>(PROJECT_CO_SUPERVISORS, coSupervisors) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(PROJECT_CO_SUPERVISOR, item.getModel())); + } } - }); + ); - IModel> reviewers = new ListAdapterModel<>(LambdaModel.of(projectModel, Project::getReviewers, Project::setReviewers)); - add(new AutoHidingListView<>(PROJECT_REVIEWERS, reviewers) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(PROJECT_REVIEWER, item.getModel())); + IModel> reviewers = new ListAdapterModel<>( + LambdaModel.of(projectModel, Project::getReviewers, Project::setReviewers) + ); + add( + new AutoHidingListView<>(PROJECT_REVIEWERS, reviewers) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(PROJECT_REVIEWER, item.getModel())); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPage.java index 887b63378c..02841f1eef 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -11,8 +12,6 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.project.pages.ProjectPage; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class ProjectFinalSeminarDetailsPage extends ProjectPage implements MenuHighlightAuthorFinalSeminars { public static final String SEMINAR_PANEL = "seminarPanel"; @@ -20,11 +19,15 @@ public class ProjectFinalSeminarDetailsPage extends ProjectPage implements MenuH @Inject private FinalSeminarService finalSeminarService; + @Inject private ProjectService projectService; public ProjectFinalSeminarDetailsPage(final PageParameters pp) { - DetachableServiceModel seminarModel = new DetachableServiceModel<>(finalSeminarService, getSeminarFromProject(pp)); + DetachableServiceModel seminarModel = new DetachableServiceModel<>( + finalSeminarService, + getSeminarFromProject(pp) + ); add(new FencedFeedbackPanel(FEEDBACK, this)); add(new SeminarPanel(SEMINAR_PANEL, seminarModel)); diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPage.java index 3e3517406f..4243882841 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -10,9 +11,7 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.FINAL_SEMINAR) public class ProjectFinalSeminarPage extends AbstractProjectDetailsPage { @@ -21,27 +20,29 @@ public class ProjectFinalSeminarPage extends AbstractProjectDetailsPage { public ProjectFinalSeminarPage(PageParameters pp) { super(pp); - final FinalSeminar seminar = finalSeminarService.findByProject(getActiveProject()); - add(new WebMarkupContainer(NOSEMINAR) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(seminar == null); + add( + new WebMarkupContainer(NOSEMINAR) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(seminar == null); + } } - }); + ); if (seminar != null) { - DetachableServiceModel seminarModel = new DetachableServiceModel<>(finalSeminarService, seminar); + DetachableServiceModel seminarModel = new DetachableServiceModel<>( + finalSeminarService, + seminar + ); add(new SeminarPanel(SEMINAR, seminarModel)); } else { add(new EmptyPanel(SEMINAR)); } - } static final String NOSEMINAR = "noSeminar"; static final String SEMINAR = "seminar"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPage.java index 32fd7d19b5..cfa0e41ff3 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPage.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -31,17 +36,12 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - @ProjectModuleComponent(ProjectModule.FINAL_SEMINAR) public class ProjectOppositionPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects { @Inject private FinalSeminarService finalSeminarService; + @Inject private NotificationController notificationController; @@ -49,7 +49,6 @@ public class ProjectOppositionPage extends AbstractProjectDetailsPage implements public ProjectOppositionPage(PageParameters pp) { super(pp); - filter = new FinalSeminarService.Filter(); filter.setFromDate(new Date()); filter.setLazyDeleted(Boolean.FALSE); @@ -77,48 +76,66 @@ public class ProjectOppositionPage extends AbstractProjectDetailsPage implements }; add(subscribeContainer); - final boolean isSubscribed = finalSeminarService.isSubscribedToSeminarCreationNotifications(getActiveProject(), loggedInUser()); + final boolean isSubscribed = finalSeminarService.isSubscribedToSeminarCreationNotifications( + getActiveProject(), + loggedInUser() + ); - subscribeContainer.add(new AjaxCheckBox("subscribe", Model.of(isSubscribed)) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - finalSeminarService.toggleSubscriptionToSeminarCreationNotifications(getActiveProject(), loggedInUser()); + subscribeContainer.add( + new AjaxCheckBox("subscribe", Model.of(isSubscribed)) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + finalSeminarService.toggleSubscriptionToSeminarCreationNotifications( + getActiveProject(), + loggedInUser() + ); + } } - }); + ); } private void createDataPanel() { - SortableDataProvider provider = new FilteredDataProvider<>(finalSeminarService, Model.of(this.filter)); + SortableDataProvider provider = new FilteredDataProvider<>( + finalSeminarService, + Model.of(this.filter) + ); provider.setSort("startDate", SortOrder.DESCENDING); add(new ExportableDataPanel<>("select", createColumns(), provider)); } public boolean submitOpposition(FinalSeminar finalSeminar) { - return finalSeminarService.attemptAddOpposition(SciProSession.get().getUser(), finalSeminar, getActiveProject()) - .fold( - notAllowed -> { - final String errorMessage = notAllowed.fold( - ungradedOpposition -> "You have ungraded oppositions", - finalSeminarCancelled -> "This seminar has been cancelled", - alreadyParticipating -> "You are already participating on this seminar", - alreadyHappened -> "This seminar has already happened", - tooManyOpponents -> "This seminar has reached the maximum number of opponents", - priorityForSeminarAuthors -> - "Authors with their own final seminar have " + - "priority to register for " + priorityForSeminarAuthors.getPriorityDays() + - " day(s). This priority will end at " + asDateTime(Date.from(priorityForSeminarAuthors.getPriorityEnd())), - alreadyOpposed -> "You have already completed an opposition and can't perform a second one", - manualOpponents -> "Opponents for this seminar are handled by the supervisor" - ); - error(errorMessage); - return Boolean.FALSE; - }, - opposed -> { - notificationController.notifySeminar(finalSeminar, SeminarEvent.Event.OPPOSITION_CHANGED, new NotificationSource()); - return Boolean.TRUE; - } - ); + return finalSeminarService + .attemptAddOpposition(SciProSession.get().getUser(), finalSeminar, getActiveProject()) + .fold( + notAllowed -> { + final String errorMessage = notAllowed.fold( + ungradedOpposition -> "You have ungraded oppositions", + finalSeminarCancelled -> "This seminar has been cancelled", + alreadyParticipating -> "You are already participating on this seminar", + alreadyHappened -> "This seminar has already happened", + tooManyOpponents -> "This seminar has reached the maximum number of opponents", + priorityForSeminarAuthors -> + "Authors with their own final seminar have " + + "priority to register for " + + priorityForSeminarAuthors.getPriorityDays() + + " day(s). This priority will end at " + + asDateTime(Date.from(priorityForSeminarAuthors.getPriorityEnd())), + alreadyOpposed -> "You have already completed an opposition and can't perform a second one", + manualOpponents -> "Opponents for this seminar are handled by the supervisor" + ); + error(errorMessage); + return Boolean.FALSE; + }, + opposed -> { + notificationController.notifySeminar( + finalSeminar, + SeminarEvent.Event.OPPOSITION_CHANGED, + new NotificationSource() + ); + return Boolean.TRUE; + } + ); } public String asDateTime(Date date) { @@ -127,69 +144,105 @@ public class ProjectOppositionPage extends AbstractProjectDetailsPage implements } public boolean submitParticipation(FinalSeminar finalSeminar) { - return finalSeminarService.attemptAddActiveParticipation(SciProSession.get().getUser(), finalSeminar, getActiveProject()) - .fold( - notAllowed -> { - final String errorMessage = notAllowed.fold( - tooManyParticipants -> "The seminar has already reached the maximum number of active participants", - manualParticipants -> "Active participants for this seminar are handled by the supervisor", - participationAlreadyParticipating -> "You are already participating in this seminar", - participationAlreadyHappened -> "This seminar has already happened", - participationFinalSeminarCancelled -> "This seminar has been cancelled"); - error(errorMessage); - return Boolean.FALSE; - }, - opposed -> { - notificationController.notifySeminar(finalSeminar, SeminarEvent.Event.PARTICIPATION_CHANGED, new NotificationSource()); - return Boolean.TRUE; - } - ); + return finalSeminarService + .attemptAddActiveParticipation(SciProSession.get().getUser(), finalSeminar, getActiveProject()) + .fold( + notAllowed -> { + final String errorMessage = notAllowed.fold( + tooManyParticipants -> + "The seminar has already reached the maximum number of active participants", + manualParticipants -> "Active participants for this seminar are handled by the supervisor", + participationAlreadyParticipating -> "You are already participating in this seminar", + participationAlreadyHappened -> "This seminar has already happened", + participationFinalSeminarCancelled -> "This seminar has been cancelled" + ); + error(errorMessage); + return Boolean.FALSE; + }, + opposed -> { + notificationController.notifySeminar( + finalSeminar, + SeminarEvent.Event.PARTICIPATION_CHANGED, + new NotificationSource() + ); + return Boolean.TRUE; + } + ); } private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of("Date"), FinalSeminar::getStartDate, "startDate", DateStyle.DATETIME)); - columns.add(new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Title"), "project.title") { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(LinkWrapper.apply(componentId, id -> { - final PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), rowModel.getObject().getProject().getId()); - final BookmarkablePageLink link = new BookmarkablePageLink<>(id, ProjectFinalSeminarDetailsPage.class, pp); - link.setBody(rowModel.map(FinalSeminar::getProjectTitle)); - return link; - })); + columns.add( + new LambdaColumn<>(Model.of("Type"), "project.projectType.name", fs -> fs.getProjectType().getName()) + ); + columns.add( + new AbstractColumn<>(Model.of("Title"), "project.title") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + LinkWrapper.apply(componentId, id -> { + final PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), rowModel.getObject().getProject().getId()); + final BookmarkablePageLink link = new BookmarkablePageLink<>( + id, + ProjectFinalSeminarDetailsPage.class, + pp + ); + link.setBody(rowModel.map(FinalSeminar::getProjectTitle)); + return link; + }) + ); + } } - }); + ); - columns.add(new AbstractColumn<>(Model.of("Oppose"), null) { - @Override - public void populateItem(Item> item, String s, final IModel iModel) { - item.add(new OpposeColumnPanel(s, iModel, projectModel) { - @Override - public void onClick(IModel clickedModel) { - if (submitOpposition(clickedModel.getObject())) { - ProjectOppositionPage.this.success(getString("oppositionAdded", clickedModel)); + columns.add( + new AbstractColumn<>(Model.of("Oppose"), null) { + @Override + public void populateItem( + Item> item, + String s, + final IModel iModel + ) { + item.add( + new OpposeColumnPanel(s, iModel, projectModel) { + @Override + public void onClick(IModel clickedModel) { + if (submitOpposition(clickedModel.getObject())) { + ProjectOppositionPage.this.success(getString("oppositionAdded", clickedModel)); + } + } } - } - }); + ); + } } - }); - columns.add(new AbstractColumn<>(Model.of("Participate"), null) { - @Override - public void populateItem(Item> item, String s, final IModel iModel) { - item.add(new ParticipateColumnPanel(s, iModel) { - @Override - public void onClick(IModel clickedModel) { - if (submitParticipation(clickedModel.getObject())) { - ProjectOppositionPage.this.success(getString("participationAdded", clickedModel)); + ); + columns.add( + new AbstractColumn<>(Model.of("Participate"), null) { + @Override + public void populateItem( + Item> item, + String s, + final IModel iModel + ) { + item.add( + new ParticipateColumnPanel(s, iModel) { + @Override + public void onClick(IModel clickedModel) { + if (submitParticipation(clickedModel.getObject())) { + ProjectOppositionPage.this.success(getString("participationAdded", clickedModel)); + } + } } - } - }); + ); + } } - }); + ); return columns; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanel.java index 1bcb145500..5fb2d31a93 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -16,39 +18,56 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class ProjectOppositionsListPanel extends GenericPanel { + @Inject private FinalSeminarService finalSeminarService; public ProjectOppositionsListPanel(final String id, final IModel model) { super(id, model); + add( + new AutoHidingListView<>("oppositions", getOpponents(model)) { + @Override + protected void populateItem(final ListItem item) { + PageParameters pp = new PageParameters(); + pp.add( + PageParameterKeys.MAP.get(Project.class), + item.getModelObject().getFinalSeminar().getProject().getId() + ); - add(new AutoHidingListView<>("oppositions", getOpponents(model)) { - @Override - protected void populateItem(final ListItem item) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), item.getModelObject().getFinalSeminar().getProject().getId()); - - BookmarkablePageLink finalSeminarLink = new BookmarkablePageLink<>("finalSeminar", SupervisorFinalSeminarDetailsPage.class, pp); - final IModel opposition = item.getModel(); - finalSeminarLink.add(new DateLabel("finalSeminar.startDate", opposition.map(o -> o.getFinalSeminar().getStartDate()), DateStyle.DATE)); - item.add(finalSeminarLink); - item.add(new UserLinkPanel("user", opposition.map(FinalSeminarParticipation::getUser))); - item.add(new Label("points", opposition.map(FinalSeminarOpposition::getPoints)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); - } - }); + BookmarkablePageLink finalSeminarLink = new BookmarkablePageLink<>( + "finalSeminar", + SupervisorFinalSeminarDetailsPage.class, + pp + ); + final IModel opposition = item.getModel(); + finalSeminarLink.add( + new DateLabel( + "finalSeminar.startDate", + opposition.map(o -> o.getFinalSeminar().getStartDate()), + DateStyle.DATE + ) + ); + item.add(finalSeminarLink); + item.add(new UserLinkPanel("user", opposition.map(FinalSeminarParticipation::getUser))); + item.add( + new Label("points", opposition.map(FinalSeminarOpposition::getPoints)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } + } + ); + } } - }); + ); - add(new Label("no.oppositions", new ResourceModel("no.oppositions")) - .add(new OppositeVisibility(get("oppositions")))); + add( + new Label("no.oppositions", new ResourceModel("no.oppositions")).add( + new OppositeVisibility(get("oppositions")) + ) + ); } private IModel> getOpponents(final IModel project) { diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/ScheduleFinalSeminarPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/ScheduleFinalSeminarPanel.java index e9200c8a47..087264c563 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/ScheduleFinalSeminarPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/ScheduleFinalSeminarPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; @@ -14,18 +18,13 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - public class ScheduleFinalSeminarPanel extends GenericPanel { - @Inject private FinalSeminarService finalSeminarService; + @Inject + private FinalSeminarService finalSeminarService; public ScheduleFinalSeminarPanel(String id, IModel model) { super(id, model); - add(new SchedulingForm("form", model)); } @@ -40,13 +39,13 @@ public class ScheduleFinalSeminarPanel extends GenericPanel { } private class SchedulingForm extends Form { + private final IModel detailsModel = new Model<>(); private final IModel dateModel = new Model<>(); private final IModel timeModel = new Model<>(); public SchedulingForm(String id, IModel model) { super(id, model); - Project project = model.getObject(); FinalSeminarDetailsParameters details = new FinalSeminarDetailsParameters(); @@ -55,26 +54,23 @@ public class ScheduleFinalSeminarPanel extends GenericPanel { details.setMaxParticipants(project.getMinFinalSeminarActiveParticipation()); details.setMaxOpponents(project.getMinOpponentsOnFinalSeminar()); detailsModel.setObject(details); - add(new FinalSeminarDetailsParametersPanel( + add( + new FinalSeminarDetailsParametersPanel( "details", detailsModel, project.getMinFinalSeminarActiveParticipation(), - project.getMinOpponentsOnFinalSeminar())); + project.getMinOpponentsOnFinalSeminar() + ) + ); - RequiredTextField dateField = new RequiredTextField<>( - "date", - dateModel, - LocalDate.class); + RequiredTextField dateField = new RequiredTextField<>("date", dateModel, LocalDate.class); dateField.add(new BootstrapDatePicker()); dateField.add(new SeminarDateValidator(model)); add(dateField); add(new Label("earliest", LoadableDetachableModel.of(finalSeminarService::getEarliestSeminarDate))); - RequiredTextField timeField = new RequiredTextField<>( - "time", - timeModel, - LocalTime.class); + RequiredTextField timeField = new RequiredTextField<>("time", timeModel, LocalTime.class); timeField.add(new BootstrapTimePicker()); add(timeField); } @@ -82,18 +78,23 @@ public class ScheduleFinalSeminarPanel extends GenericPanel { @Override protected void onSubmit() { LocalDateTime when = dateModel.getObject().atTime(timeModel.getObject()); - Either scheduled = - finalSeminarService.schedule(getModelObject(), when, detailsModel.getObject().asDetails()); + Either scheduled = finalSeminarService.schedule( + getModelObject(), + when, + detailsModel.getObject().asDetails() + ); if (scheduled.isRight()) { success("Final seminar scheduled"); - } - else { + } else { SchedulingError error = scheduled.left(); // TODO Pattern match if (error instanceof NonWorkDay nonWorkDay) { error(nonWorkDay + " is marked as a non work day, pick another date."); } else if (error instanceof NotEnoughWorkDays notEnoughWorkDays) { - error("Not enough time for people to prepare, earliest possible date is " + notEnoughWorkDays.earliest()); + error( + "Not enough time for people to prepare, earliest possible date is " + + notEnoughWorkDays.earliest() + ); } else if (error instanceof RoughDraftNotApproved) { error("You must get the rough draft approved to schedule a final seminar"); } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanel.java index f2eaefa593..44ea31774c 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanel.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.basic.Label; @@ -20,11 +24,6 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - public class SeminarActiveParticipantsPanel extends GenericPanel { public static final String PARTICIPANTS = "activeParticipations"; @@ -36,58 +35,72 @@ public class SeminarActiveParticipantsPanel extends GenericPanel { @Inject private EventBus eventBus; + @Inject private FinalSeminarActiveParticipationService finalSeminarActiveParticipationService; + @Inject private FinalSeminarService finalSeminarService; public SeminarActiveParticipantsPanel(String id, final IModel seminar) { super(id, seminar); - feedbackPanel = new FencedFeedbackPanel(FEEDBACK, this); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); - final IModel> participants = new ListAdapterModel<>(LambdaModel.of(seminar, FinalSeminar::getActiveParticipations, FinalSeminar::setActiveParticipations)); - add(new Label("noParticipants", new ResourceModel("no.participants")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(participants.getObject().isEmpty()); + final IModel> participants = new ListAdapterModel<>( + LambdaModel.of(seminar, FinalSeminar::getActiveParticipations, FinalSeminar::setActiveParticipations) + ); + add( + new Label("noParticipants", new ResourceModel("no.participants")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(participants.getObject().isEmpty()); + } } - }); - add(new ListView<>(PARTICIPANTS, participants) { - @Override - protected void populateItem(final ListItem item) { - item.add(new UserLinkPanel(USER, item.getModel().map(FinalSeminarParticipation::getUser))); + ); + add( + new ListView<>(PARTICIPANTS, participants) { + @Override + protected void populateItem(final ListItem item) { + item.add(new UserLinkPanel(USER, item.getModel().map(FinalSeminarParticipation::getUser))); - item.add(new Link<>(REMOVE_PARTICIPANT, item.getModel()) { - { - add(new JavascriptEventConfirmation("click", SeminarActiveParticipantsPanel.this.getString("confirm"))); - } + item.add( + new Link<>(REMOVE_PARTICIPANT, item.getModel()) { + { + add( + new JavascriptEventConfirmation( + "click", + SeminarActiveParticipantsPanel.this.getString("confirm") + ) + ); + } - @Override - public void onClick() { - SeminarActiveParticipantsPanel.this.success(getString("removed", item.getModel())); - FinalSeminar finalSeminar = getModelObject().getFinalSeminar(); - finalSeminar.removeActiveParticipant(getModelObject()); - finalSeminarService.save(finalSeminar); - // Detach the (cached) ListAdapterModel and remove the already added children - // or the ListView will not reflect the change in the underlying list - getParent().getParent().detach(); - getParent().getParent().removeAll(); - } + @Override + public void onClick() { + SeminarActiveParticipantsPanel.this.success(getString("removed", item.getModel())); + FinalSeminar finalSeminar = getModelObject().getFinalSeminar(); + finalSeminar.removeActiveParticipant(getModelObject()); + finalSeminarService.save(finalSeminar); + // Detach the (cached) ListAdapterModel and remove the already added children + // or the ListView will not reflect the change in the underlying list + getParent().getParent().detach(); + getParent().getParent().removeAll(); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(allowDeleteParticipation(getModelObject())); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(allowDeleteParticipation(getModelObject())); + } + } + ); - item.add(new ActiveParticipationRadioChoice(RADIOS, item.getModel())); + item.add(new ActiveParticipationRadioChoice(RADIOS, item.getModel())); + } } - }); + ); } private class ActiveParticipationRadioChoice extends AjaxRadioChoice { @@ -95,9 +108,17 @@ public class SeminarActiveParticipantsPanel extends GenericPanel { private IModel participant; public ActiveParticipationRadioChoice(String id, IModel participant) { - super(id, LambdaModel.of(participant, FinalSeminarActiveParticipation::getGrade, FinalSeminarActiveParticipation::setGrade), Arrays.asList(FinalSeminarGrade.values()), - new EnumChoiceRenderer<>(SeminarActiveParticipantsPanel.this), - SeminarActiveParticipantsPanel.this.getString("confirmation", participant)); + super( + id, + LambdaModel.of( + participant, + FinalSeminarActiveParticipation::getGrade, + FinalSeminarActiveParticipation::setGrade + ), + Arrays.asList(FinalSeminarGrade.values()), + new EnumChoiceRenderer<>(SeminarActiveParticipantsPanel.this), + SeminarActiveParticipantsPanel.this.getString("confirmation", participant) + ); this.participant = participant; setSuffix(" "); } @@ -136,11 +157,12 @@ public class SeminarActiveParticipantsPanel extends GenericPanel { } private boolean isAdmin() { - return SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN); + return ( + SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN) + ); } private boolean startDateHasPassed() { return getModelObject().getStartDate().before(new Date()); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanel.java index 5e50dda110..208daadb10 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -22,9 +24,6 @@ import se.su.dsv.scipro.system.UserSearchService; import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.util.*; - public class SeminarCRUDPanel extends GenericPanel { static final String FORM = "form"; @@ -33,12 +32,23 @@ public class SeminarCRUDPanel extends GenericPanel { static final String DELETE = "delete"; static final String MOVE_SEMINAR_LINK = "moveSeminarLink"; - @Inject private UserSearchService userSearchService; - @Inject private UserService userService; - @Inject private FinalSeminarService seminarService; - @Inject private ProjectService projectService; - @Inject private NotificationController notificationController; - @Inject private NonWorkDayPeriodService nonWorkDays; + @Inject + private UserSearchService userSearchService; + + @Inject + private UserService userService; + + @Inject + private FinalSeminarService seminarService; + + @Inject + private ProjectService projectService; + + @Inject + private NotificationController notificationController; + + @Inject + private NonWorkDayPeriodService nonWorkDays; private DefaultSelect2MultiChoice opponents; private DefaultSelect2MultiChoice activeParticipants; @@ -46,7 +56,6 @@ public class SeminarCRUDPanel extends GenericPanel { public SeminarCRUDPanel(String id, IModel seminar) { super(id, seminar); - add(new MoveFinalSeminarPanel("moveDateModal", seminar)); add(new FinalSeminarForm("form", seminar)); } @@ -63,61 +72,91 @@ public class SeminarCRUDPanel extends GenericPanel { } private class FinalSeminarForm extends Form { + private final IModel detailsParameters; FinalSeminarForm(String id, IModel seminar) { super(id, seminar); + detailsParameters = LoadableDetachableModel.of(() -> FinalSeminarDetailsParameters.from(seminar.getObject()) + ); + add( + new FinalSeminarDetailsParametersPanel( + "details", + detailsParameters, + seminar.getObject().getMinActiveParticipants(), + seminar.getObject().getMinOpponents() + ) + ); - detailsParameters = LoadableDetachableModel.of(() -> FinalSeminarDetailsParameters.from(seminar.getObject())); - add(new FinalSeminarDetailsParametersPanel("details", detailsParameters, seminar.getObject().getMinActiveParticipants(), seminar.getObject().getMinOpponents())); + add( + new WebMarkupContainer(CANCELLED) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject().isCancelled()); + } + } + ); + add( + new FinalSeminarDateTimeComponent( + DATE, + LambdaModel.of(seminar, FinalSeminar::getStartDate, FinalSeminar::setStartDate) + ) { + { + add(new SeminarDateValidator(seminar.map(FinalSeminar::getProject))); + } - add(new WebMarkupContainer(CANCELLED) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject().isCancelled()); + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(seminar.getObject().getId() == null); + } } - }); - add(new FinalSeminarDateTimeComponent(DATE, LambdaModel.of(seminar, FinalSeminar::getStartDate, FinalSeminar::setStartDate)) { - { - add(new SeminarDateValidator(seminar.map(FinalSeminar::getProject))); + ); + add( + new WebMarkupContainer(MOVE_SEMINAR_LINK) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(seminar.getObject().getId() != null); + } } + ); - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(seminar.getObject().getId() == null); - } - }); - add(new WebMarkupContainer(MOVE_SEMINAR_LINK) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(seminar.getObject().getId() != null); - } - }); - - final AutoCompleteRoleProvider authorChoices = new AutoCompleteRoleProvider(userSearchService, Set.of(Roles.AUTHOR)); - opponents = new DefaultSelect2MultiChoice<>("opponents", new DetachableServiceModelCollection<>(userService), authorChoices); + final AutoCompleteRoleProvider authorChoices = new AutoCompleteRoleProvider( + userSearchService, + Set.of(Roles.AUTHOR) + ); + opponents = new DefaultSelect2MultiChoice<>( + "opponents", + new DetachableServiceModelCollection<>(userService), + authorChoices + ); add(opponents); - activeParticipants = new DefaultSelect2MultiChoice<>("participants", new DetachableServiceModelCollection<>(userService), authorChoices); + activeParticipants = new DefaultSelect2MultiChoice<>( + "participants", + new DetachableServiceModelCollection<>(userService), + authorChoices + ); add(activeParticipants); - add(new ConfirmationLink<>(DELETE, seminar, new StringResourceModel("confirm", this)) { - @Override - public void onClick() { - Project project = getModelObject().getProject(); - seminarService.delete(getModelObject()); - setModelObject(new FinalSeminar(project)); - success(getString("deleted")); - } + add( + new ConfirmationLink<>(DELETE, seminar, new StringResourceModel("confirm", this)) { + @Override + public void onClick() { + Project project = getModelObject().getProject(); + seminarService.delete(getModelObject()); + setModelObject(new FinalSeminar(project)); + success(getString("deleted")); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().getId() != null); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject().getId() != null); + } } - }); + ); } @Override @@ -176,14 +215,16 @@ public class SeminarCRUDPanel extends GenericPanel { @Override protected void onValidateModelObjects() { FinalSeminar seminar = getModelObject(); - if (!seminar.getProject().isFinalSeminarRuleExempted() && nonWorkDays.isNonWorkDay(seminar.getStartDate())) { + if ( + !seminar.getProject().isFinalSeminarRuleExempted() && nonWorkDays.isNonWorkDay(seminar.getStartDate()) + ) { error(getString("nonworkday")); } } @Override protected void onSubmit() { - saveSeminar(detailsParameters.getObject().asDetails()); + saveSeminar(detailsParameters.getObject().asDetails()); } } @@ -209,7 +250,10 @@ public class SeminarCRUDPanel extends GenericPanel { private void addActiveParticipants(FinalSeminar finalSeminar) { for (User potentialParticipant : activeParticipants.getModelObject()) { boolean authorHasActiveProject; - Optional maybeProject = getPotentialParticipantProjectForUserAndType(potentialParticipant, finalSeminar.getProjectType()); + Optional maybeProject = getPotentialParticipantProjectForUserAndType( + potentialParticipant, + finalSeminar.getProjectType() + ); if (maybeProject.isEmpty()) { maybeProject = getPotentialParticipantProjectForUser(potentialParticipant); authorHasActiveProject = false; @@ -220,26 +264,47 @@ public class SeminarCRUDPanel extends GenericPanel { error(getString("UserHasNoActiveProject", Model.of(potentialParticipant))); } else { final Project project = maybeProject.get(); - Either result = seminarService.attemptAddActiveParticipationAsSupervisor(potentialParticipant, finalSeminar, project); + Either result = + seminarService.attemptAddActiveParticipationAsSupervisor( + potentialParticipant, + finalSeminar, + project + ); result.fold( - error -> { - switch (error) { - case IS_AUTHOR -> - error(potentialParticipant.getFullName() + " that you selected as an active participant is an author"); - case ALREADY_OPPONENT -> - error(potentialParticipant.getFullName() + " that you selected as an active participant is already an opponent"); - case ALREADY_PARTICIPANT -> - error(potentialParticipant.getFullName() + " that you selected as an active participant is already an active participant"); - } - return false; - }, - success -> { - success("Added " + potentialParticipant.getFullName() + " as a participant." + - (authorHasActiveProject ? "" : " Note! " + potentialParticipant.getFullName() + " doesn't have a project of the same type")); - events.add(SeminarEvent.Event.PARTICIPATION_CHANGED); - return true; - }); - }String test = authorHasActiveProject ? "test" : "test2"; + error -> { + switch (error) { + case IS_AUTHOR -> error( + potentialParticipant.getFullName() + + " that you selected as an active participant is an author" + ); + case ALREADY_OPPONENT -> error( + potentialParticipant.getFullName() + + " that you selected as an active participant is already an opponent" + ); + case ALREADY_PARTICIPANT -> error( + potentialParticipant.getFullName() + + " that you selected as an active participant is already an active participant" + ); + } + return false; + }, + success -> { + success( + "Added " + + potentialParticipant.getFullName() + + " as a participant." + + (authorHasActiveProject + ? "" + : " Note! " + + potentialParticipant.getFullName() + + " doesn't have a project of the same type") + ); + events.add(SeminarEvent.Event.PARTICIPATION_CHANGED); + return true; + } + ); + } + String test = authorHasActiveProject ? "test" : "test2"; } activeParticipants.clearInput(); activeParticipants.getModel().setObject(Collections.emptyList()); @@ -248,7 +313,10 @@ public class SeminarCRUDPanel extends GenericPanel { private void addOpponents(FinalSeminar finalSeminar) { for (User potentialOpponent : opponents.getModelObject()) { boolean authorHasActiveProject; - Optional maybeProject = getPotentialParticipantProjectForUserAndType(potentialOpponent, finalSeminar.getProjectType()); + Optional maybeProject = getPotentialParticipantProjectForUserAndType( + potentialOpponent, + finalSeminar.getProjectType() + ); if (maybeProject.isEmpty()) { maybeProject = getPotentialParticipantProjectForUser(potentialOpponent); authorHasActiveProject = false; @@ -259,25 +327,44 @@ public class SeminarCRUDPanel extends GenericPanel { error(getString("UserHasNoActiveProject", Model.of(potentialOpponent))); } else { final Project project = maybeProject.get(); - Either result = seminarService.attemptAddOppositionAsSupervisor(potentialOpponent, finalSeminar, project); + Either result = seminarService.attemptAddOppositionAsSupervisor( + potentialOpponent, + finalSeminar, + project + ); result.fold( - error -> { - switch (error) { - case IS_AUTHOR -> - error(potentialOpponent.getFullName() + " that you selected as an active participant is an author"); - case ALREADY_OPPONENT -> - error(potentialOpponent.getFullName() + " that you selected as an opponent is already an opponent"); - case ALREADY_PARTICIPANT -> - error(potentialOpponent.getFullName() + " that you selected as an opponent is already an active participant"); - } - return false; - }, - success -> { - success("Added " + potentialOpponent.getFullName() + " as an opponent." + - (authorHasActiveProject ? "" : " Note! " + potentialOpponent.getFullName() + " doesn't have a project of the same type")); - events.add(SeminarEvent.Event.OPPOSITION_CHANGED); - return true; - }); + error -> { + switch (error) { + case IS_AUTHOR -> error( + potentialOpponent.getFullName() + + " that you selected as an active participant is an author" + ); + case ALREADY_OPPONENT -> error( + potentialOpponent.getFullName() + + " that you selected as an opponent is already an opponent" + ); + case ALREADY_PARTICIPANT -> error( + potentialOpponent.getFullName() + + " that you selected as an opponent is already an active participant" + ); + } + return false; + }, + success -> { + success( + "Added " + + potentialOpponent.getFullName() + + " as an opponent." + + (authorHasActiveProject + ? "" + : " Note! " + + potentialOpponent.getFullName() + + " doesn't have a project of the same type") + ); + events.add(SeminarEvent.Event.OPPOSITION_CHANGED); + return true; + } + ); } } opponents.clearInput(); @@ -292,11 +379,15 @@ public class SeminarCRUDPanel extends GenericPanel { addActiveParticipants(finalSeminar); addOpponents(finalSeminar); if (roomChanged) { - notificationController.notifySeminar(finalSeminar, SeminarEvent.Event.ROOM_CHANGED, new NotificationSource()); + notificationController.notifySeminar( + finalSeminar, + SeminarEvent.Event.ROOM_CHANGED, + new NotificationSource() + ); } for (SeminarEvent.Event event : events) { notificationController.notifySeminar(finalSeminar, event, new NotificationSource()); } events = new HashSet<>(); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanel.java index 6296643a74..28331509df 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanel.java @@ -7,11 +7,12 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.StringResourceModel; public class SeminarCancelledInfoPanel extends Panel { + public SeminarCancelledInfoPanel(String id, final IModel model) { super(id, model); - WebMarkupContainer cancelled = new WebMarkupContainer(CANCELLED){ + WebMarkupContainer cancelled = new WebMarkupContainer(CANCELLED) { @Override - protected void onConfigure(){ + protected void onConfigure() { super.onConfigure(); setVisibilityAllowed(model.getObject().isDeleted()); } @@ -19,6 +20,7 @@ public class SeminarCancelledInfoPanel extends Panel { add(cancelled); cancelled.add(new MultiLineLabel(CANCELLED_INFO, new StringResourceModel(CANCELLED_INFO, this, null))); } + static final String CANCELLED = "cancelled"; static final String CANCELLED_INFO = "cancelledInfo"; } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarDateValidator.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarDateValidator.java index 09d1e2b90f..ea8a04d72e 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarDateValidator.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarDateValidator.java @@ -1,21 +1,20 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.time.LocalDate; import org.apache.wicket.Component; import org.apache.wicket.model.IModel; import org.apache.wicket.validation.validator.RangeValidator; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; -import java.time.LocalDate; - public class SeminarDateValidator extends RangeValidator { private final IModel project; + @Inject private FinalSeminarService finalSeminarService; - public SeminarDateValidator(IModel project) - { + public SeminarDateValidator(IModel project) { this.project = project; } @@ -29,9 +28,8 @@ public class SeminarDateValidator extends RangeValidator { public LocalDate getMinimum() { if (project.getObject().isFinalSeminarRuleExempted()) { return null; - } - else { + } else { return finalSeminarService.getEarliestSeminarDate(); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarNonCRUDPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarNonCRUDPanel.java index 9bb1759b86..ce0e5753a4 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarNonCRUDPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarNonCRUDPanel.java @@ -20,7 +20,6 @@ public class SeminarNonCRUDPanel extends Panel { public SeminarNonCRUDPanel(String id, IModel seminar) { super(id, seminar); - add(new Label(SEMINAR_MAX_OPPOSITIONS, seminar.map(FinalSeminar::getMaxOpponents))); add(new Label(SEMINAR_MAX_PARTICIPANTS, seminar.map(FinalSeminar::getMaxParticipants))); add(new Label(SEMINAR_ROOM, seminar.map(FinalSeminar::getRoom))); @@ -28,12 +27,14 @@ public class SeminarNonCRUDPanel extends Panel { add(new EnumLabel<>(SEMINAR_REPORT_LANGUAGE, seminar.map(FinalSeminar::getProject).map(Project::getLanguage))); add(new DateLabel(SEMINAR_DATE, seminar.map(FinalSeminar::getStartDate), DateStyle.DATETIME)); - add(new SmarterLinkMultiLineLabel("extraInfo", seminar.map(FinalSeminar::getExtraInfo)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isBlank()); + add( + new SmarterLinkMultiLineLabel("extraInfo", seminar.map(FinalSeminar::getExtraInfo)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanel.java index 6bcf0afc69..5315c6ff3d 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanel.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.util.Date; +import java.util.List; +import java.util.Objects; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.feedback.FencedFeedbackPanel; @@ -32,11 +36,6 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.Date; -import java.util.List; -import java.util.Objects; - public class SeminarOppositionPanel extends Panel { public static final String USER = "user"; @@ -55,14 +54,19 @@ public class SeminarOppositionPanel extends Panel { @Inject private FinalSeminarOppositionService finalSeminarOppositionService; + @Inject private EventBus eventBus; + @Inject private ProjectTypeService projectTypeService; + @Inject private FinalSeminarService finalSeminarService; + @Inject private GradingReportService gradingReportService; + @Inject private OppositionReportService oppositionReportService; @@ -82,15 +86,19 @@ public class SeminarOppositionPanel extends Panel { feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); - final IModel> oppositions = new ListAdapterModel<>(LambdaModel.of(seminar, FinalSeminar::getOppositions, FinalSeminar::setOppositions)); + final IModel> oppositions = new ListAdapterModel<>( + LambdaModel.of(seminar, FinalSeminar::getOppositions, FinalSeminar::setOppositions) + ); - add(new Label("noOpponents", new ResourceModel("no.opponents")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(oppositions.getObject().isEmpty()); + add( + new Label("noOpponents", new ResourceModel("no.opponents")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(oppositions.getObject().isEmpty()); + } } - }); + ); opponents = getOpponentsList(oppositions); oppositionContainer.add(opponents); @@ -106,7 +114,9 @@ public class SeminarOppositionPanel extends Panel { WebMarkupContainer gradeContainer = getGradeContainer(opposition); gradeContainer.add(new Label("gradedPoints", (item.getModel().map(FinalSeminarOpposition::getPoints)))); - gradeContainer.add(new Label("gradedFeedback", item.getModel().map(FinalSeminarOpposition::getFeedback))); + gradeContainer.add( + new Label("gradedFeedback", item.getModel().map(FinalSeminarOpposition::getFeedback)) + ); item.add(gradeContainer); item.add(getRemoveLink(item.getModel())); @@ -151,14 +161,21 @@ public class SeminarOppositionPanel extends Panel { FinalSeminar finalSeminar = getModelObject().getFinalSeminar(); finalSeminar.removeOpposition(getModelObject()); finalSeminarService.save(finalSeminar); - opponents.setModel(new ListAdapterModel<>(LambdaModel.of(seminar, FinalSeminar::getOppositions, FinalSeminar::setOppositions))); + opponents.setModel( + new ListAdapterModel<>( + LambdaModel.of(seminar, FinalSeminar::getOppositions, FinalSeminar::setOppositions) + ) + ); } @Override protected void onConfigure() { super.onConfigure(); if (gradingModuleIsOnForProjectType()) { - setVisibilityAllowed((isHeadSupervisor() || isAdmin() || isSelf()) && !hasSubmittedOppositionReport(model.getObject())); + setVisibilityAllowed( + (isHeadSupervisor() || isAdmin() || isSelf()) && + !hasSubmittedOppositionReport(model.getObject()) + ); } else { setVisibilityAllowed((isHeadSupervisor() || isAdmin() || isSelf())); //cant do the above check from this panel } @@ -179,7 +196,9 @@ public class SeminarOppositionPanel extends Panel { } private boolean isAdmin() { - return SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN); + return ( + SciProSession.get().authorizedForRole(Roles.SYSADMIN) && SciProSession.get().hasActualRole(Roles.SYSADMIN) + ); } private boolean isHeadSupervisor() { @@ -191,55 +210,88 @@ public class SeminarOppositionPanel extends Panel { } private class FinalSeminarOppositionForm extends Form { + public FinalSeminarOppositionForm(String id, final IModel finalSeminarOpposition) { super(id, finalSeminarOpposition); - - FormComponent pointsField = new TextField<>(POINTS, LambdaModel.of(finalSeminarOpposition, FinalSeminarOpposition::getPoints, FinalSeminarOpposition::setPoints)) - .add(RangeValidator.range(MIN_POINTS, MAX_POINTS)) - .setType(Integer.class).setRequired(true); + FormComponent pointsField = new TextField<>( + POINTS, + LambdaModel.of( + finalSeminarOpposition, + FinalSeminarOpposition::getPoints, + FinalSeminarOpposition::setPoints + ) + ) + .add(RangeValidator.range(MIN_POINTS, MAX_POINTS)) + .setType(Integer.class) + .setRequired(true); add(pointsField); - TextArea feedback = new TextArea<>(GRADING_FEEDBACK, LambdaModel.of(finalSeminarOpposition, FinalSeminarOpposition::getFeedback, FinalSeminarOpposition::setFeedback)); + TextArea feedback = new TextArea<>( + GRADING_FEEDBACK, + LambdaModel.of( + finalSeminarOpposition, + FinalSeminarOpposition::getFeedback, + FinalSeminarOpposition::setFeedback + ) + ); feedback.add(StringValidator.maximumLength(FEEDBACK_MAX_LENGTH)); feedback.setRequired(true); add(feedback); - add(new AjaxSubmitLink(SUBMIT) { - @Override - protected void onSubmit(AjaxRequestTarget target) { - if (getModelObject().getPoints().equals(0)){ - finalSeminarOpposition.getObject().setGrade(FinalSeminarGrade.NOT_APPROVED); - eventBus.post(new OppositionFailedEvent(finalSeminarOpposition.getObject())); - } else { - finalSeminarOpposition.getObject().setGrade(FinalSeminarGrade.APPROVED); - eventBus.post(new OppositionApprovedEvent(finalSeminarOpposition.getObject())); + add( + new AjaxSubmitLink(SUBMIT) { + @Override + protected void onSubmit(AjaxRequestTarget target) { + if (getModelObject().getPoints().equals(0)) { + finalSeminarOpposition.getObject().setGrade(FinalSeminarGrade.NOT_APPROVED); + eventBus.post(new OppositionFailedEvent(finalSeminarOpposition.getObject())); + } else { + finalSeminarOpposition.getObject().setGrade(FinalSeminarGrade.APPROVED); + eventBus.post(new OppositionApprovedEvent(finalSeminarOpposition.getObject())); + } + finalSeminarOppositionService.save(finalSeminarOpposition.getObject()); + boolean updated = true; + if (gradingModuleIsOnForProjectType()) { + SupervisorGradingReport report = gradingReportService.getSupervisorGradingReport( + finalSeminarOpposition.getObject().getProject(), + finalSeminarOpposition.getObject().getUser() + ); + updated = gradingReportService.updateOppositionCriteria( + report, + finalSeminarOpposition.getObject() + ); + } + success( + getString( + updated ? "feedback.opponent.updated" : "feedback.opponent.not.updated", + finalSeminarOpposition + ) + ); + target.add(feedbackPanel); + target.add(oppositionContainer); } - finalSeminarOppositionService.save(finalSeminarOpposition.getObject()); - boolean updated = true; - if (gradingModuleIsOnForProjectType()){ - SupervisorGradingReport report = gradingReportService.getSupervisorGradingReport(finalSeminarOpposition.getObject().getProject(), finalSeminarOpposition.getObject().getUser()); - updated = gradingReportService.updateOppositionCriteria(report, finalSeminarOpposition.getObject()); - } - success(getString(updated ? "feedback.opponent.updated" : "feedback.opponent.not.updated", finalSeminarOpposition)); - target.add(feedbackPanel); - target.add(oppositionContainer); - } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedbackPanel); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedbackPanel); + } } - }); + ); } @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(startDateHasPassed() && getModelObject().getPoints() == null && getModelObject().getFeedback() == null && isHeadSupervisor()); + setVisibilityAllowed( + startDateHasPassed() && + getModelObject().getPoints() == null && + getModelObject().getFeedback() == null && + isHeadSupervisor() + ); } } - private boolean gradingModuleIsOnForProjectType(){ + private boolean gradingModuleIsOnForProjectType() { return projectTypeService.findWithModule(ProjectModule.GRADING).contains(seminar.getObject().getProjectType()); } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanel.java index 0339452529..fd975f51ad 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.feedback.FencedFeedbackPanel; @@ -25,8 +26,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - @ProjectModuleComponent(ProjectModule.GRADING) public class SeminarOppositionReportPanel extends GenericPanel { @@ -40,7 +39,6 @@ public class SeminarOppositionReportPanel extends GenericPanel model) { super(id, model); - FinalSeminarOpposition opposition = getModelObject(); seminar = Model.of(opposition.getFinalSeminar()); @@ -79,11 +77,17 @@ public class SeminarOppositionReportPanel extends GenericPanel opposition) { - return new ViewAttachmentPanel("reportDownload", opposition.map(FinalSeminarOpposition::getOpponentReport).map(FileReference::getFileDescription), DateStyle.DATETIME) { + return new ViewAttachmentPanel( + "reportDownload", + opposition.map(FinalSeminarOpposition::getOpponentReport).map(FileReference::getFileDescription), + DateStyle.DATETIME + ) { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null && allowedToSeeOppositionReport(opposition.getObject())); + setVisibilityAllowed( + getDefaultModelObject() != null && allowedToSeeOppositionReport(opposition.getObject()) + ); } }; } @@ -99,16 +103,22 @@ public class SeminarOppositionReportPanel extends GenericPanel getOppositionReportLink(final FinalSeminarOpposition opposition, final PageParameters parameters) { + private BookmarkablePageLink getOppositionReportLink( + final FinalSeminarOpposition opposition, + final PageParameters parameters + ) { return new BookmarkablePageLink<>("oppositionReportLink", OppositionReportPage.class, parameters) { @Override protected void onConfigure() { @@ -118,8 +128,16 @@ public class SeminarOppositionReportPanel extends GenericPanel report) { - return new DownloadPdfReportPanel("downloadPdfPanel", seminar, report, new OppositionReportPdfResource(report)) { + private DownloadPdfReportPanel getDownloadPdfReportPanel( + final FinalSeminarOpposition opposition, + final IModel report + ) { + return new DownloadPdfReportPanel( + "downloadPdfPanel", + seminar, + report, + new OppositionReportPdfResource(report) + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -137,17 +155,29 @@ public class SeminarOppositionReportPanel extends GenericPanel report) { - return new ViewAttachmentPanel("downloadAttachment", report.map(OppositionReport::getAttachment).map(FileReference::getFileDescription)) { + private ViewAttachmentPanel getDownloadAttachment( + final FinalSeminarOpposition opposition, + final IModel report + ) { + return new ViewAttachmentPanel( + "downloadAttachment", + report.map(OppositionReport::getAttachment).map(FileReference::getFileDescription) + ) { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null && allowedToSeeOppositionReport(opposition) && report.getObject().isSubmitted()); + setVisibilityAllowed( + getDefaultModelObject() != null && + allowedToSeeOppositionReport(opposition) && + report.getObject().isSubmitted() + ); } }; } - private AjaxConfirmationLink getDeleteOpponentReportLink(final IModel opposition) { + private AjaxConfirmationLink getDeleteOpponentReportLink( + final IModel opposition + ) { return new AjaxConfirmationLink<>("removeReportLink", new StringResourceModel("are.you.sure", this, null)) { @Override public void onClick(AjaxRequestTarget target) { @@ -165,7 +195,9 @@ public class SeminarOppositionReportPanel extends GenericPanel getDeleteOppositionReportLink(final IModel opposition) { + private AjaxConfirmationLink getDeleteOppositionReportLink( + final IModel opposition + ) { return new AjaxConfirmationLink<>("removeOppositionLink", new StringResourceModel("are.you.sure", this, null)) { @Override public void onClick(AjaxRequestTarget target) { @@ -184,7 +216,9 @@ public class SeminarOppositionReportPanel extends GenericPanel seminar) { - - add(new ExternalLink("evaluation", finalSeminarSettings.getEvaluationURL(), finalSeminarSettings.getEvaluationURL()){ - @Override - protected void onConfigure() { - super.onConfigure(); - final FinalSeminar finalSeminar = seminar.getObject(); - final String evaluationURL = finalSeminarSettings.getEvaluationURL(); - final Project project = finalSeminar.getProject(); - final Date startDate = finalSeminar.getStartDate(); - final Date now = new Date(); - final User currentUser = SciProSession.get().getUser(); - final boolean seminarHappened = finalSeminar.getStartDate() != null && now.after(startDate); - final boolean thereIsAnEvaluation = evaluationURL != null && !evaluationURL.isEmpty(); - setVisibilityAllowed(project.isParticipant(currentUser) && seminarHappened && thereIsAnEvaluation); + add( + new ExternalLink( + "evaluation", + finalSeminarSettings.getEvaluationURL(), + finalSeminarSettings.getEvaluationURL() + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + final FinalSeminar finalSeminar = seminar.getObject(); + final String evaluationURL = finalSeminarSettings.getEvaluationURL(); + final Project project = finalSeminar.getProject(); + final Date startDate = finalSeminar.getStartDate(); + final Date now = new Date(); + final User currentUser = SciProSession.get().getUser(); + final boolean seminarHappened = finalSeminar.getStartDate() != null && now.after(startDate); + final boolean thereIsAnEvaluation = evaluationURL != null && !evaluationURL.isEmpty(); + setVisibilityAllowed(project.isParticipant(currentUser) && seminarHappened && thereIsAnEvaluation); + } } - }); + ); add(new Label(PROJECT_TITLE, seminar.map(FinalSeminar::getProject).map(Project::getTitle))); add(new ScheduleFinalSeminarPanel("schedule", getProject())); add(new SeminarCRUDPanel(CRUD, seminar)); add(new ProjectDetailsPanel(PROJECT, getProject())); - add(new UrkundSubmissionPanel("urkund", seminar.map(FinalSeminar::getDocument).map(FileReference::getFileDescription)) { - @Override - protected void onConfigure() { - super.onConfigure(); - final boolean isSupervisor = SciProSession.get().getUser().equals(seminar.getObject().getHeadSupervisor()); - setVisibilityAllowed(isVisibilityAllowed() && isSupervisor); + add( + new UrkundSubmissionPanel( + "urkund", + seminar.map(FinalSeminar::getDocument).map(FileReference::getFileDescription) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + final boolean isSupervisor = SciProSession.get() + .getUser() + .equals(seminar.getObject().getHeadSupervisor()); + setVisibilityAllowed(isVisibilityAllowed() && isSupervisor); + } } - }); + ); add(new SeminarRespondentsPanel("testRespondents", seminar)); add(new SeminarOppositionPanel("testOpposition", seminar)); add(new SeminarActiveParticipantsPanel("testParticipants", seminar)); - add(new WebMarkupContainer("supervisorOnly") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isSupervisor(seminar)); + add( + new WebMarkupContainer("supervisorOnly") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isSupervisor(seminar)); + } } - }); + ); initSeminarNonCRUDComponent(seminar); initThesisComponent(seminar); addCancelledInfo(seminar); @@ -101,13 +115,15 @@ public class SeminarPanel extends Panel { } private void initSeminarNonCRUDComponent(final IModel seminar) { - add(new SeminarNonCRUDPanel(CRUD_NOT_ALLOWED, seminar) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isSupervisor(seminar)); + add( + new SeminarNonCRUDPanel(CRUD_NOT_ALLOWED, seminar) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!isSupervisor(seminar)); + } } - }); + ); } private boolean isSupervisor(IModel seminar) { @@ -115,12 +131,14 @@ public class SeminarPanel extends Panel { } private void initThesisComponent(final IModel seminar) { - add(new SeminarThesisPanel(THESIS, seminar) { - @Override - protected void onDelete() { - setResponsePage(getPage()); + add( + new SeminarThesisPanel(THESIS, seminar) { + @Override + protected void onDelete() { + setResponsePage(getPage()); + } } - }); + ); } private void addCancelledInfo(final IModel seminar) { @@ -128,5 +146,4 @@ public class SeminarPanel extends Panel { cancelledInfoPanel.setOutputMarkupId(true); add(cancelledInfoPanel); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanel.java index f939badad0..21ce31cab3 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanel.java @@ -1,6 +1,10 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.eventbus.EventBus; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.form.EnumChoiceRenderer; @@ -15,11 +19,6 @@ import se.su.dsv.scipro.components.AjaxRadioChoice; import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - public class SeminarRespondentsPanel extends Panel { public static final String RESPONDENTS = "respondents"; @@ -32,6 +31,7 @@ public class SeminarRespondentsPanel extends Panel { @Inject private FinalSeminarRespondentService finalSeminarRespondentService; + @Inject private EventBus eventBus; @@ -43,13 +43,15 @@ public class SeminarRespondentsPanel extends Panel { feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); - add(new ListView<>(RESPONDENTS, getRespondents()) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(USER, item.getModel().map(FinalSeminarRespondent::getUser))); - item.add(new RespondentRadioChoice(RADIOS, item.getModel())); + add( + new ListView<>(RESPONDENTS, getRespondents()) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(USER, item.getModel().map(FinalSeminarRespondent::getUser))); + item.add(new RespondentRadioChoice(RADIOS, item.getModel())); + } } - }); + ); } private IModel> getRespondents() { @@ -62,12 +64,17 @@ public class SeminarRespondentsPanel extends Panel { } private class RespondentRadioChoice extends AjaxRadioChoice { + private IModel respondent; public RespondentRadioChoice(String id, IModel respondent) { - super(id, LambdaModel.of(respondent, FinalSeminarRespondent::getGrade, FinalSeminarRespondent::setGrade), Arrays.asList(FinalSeminarGrade.values()), - new EnumChoiceRenderer<>(SeminarRespondentsPanel.this), - SeminarRespondentsPanel.this.getString("confirmation", respondent)); + super( + id, + LambdaModel.of(respondent, FinalSeminarRespondent::getGrade, FinalSeminarRespondent::setGrade), + Arrays.asList(FinalSeminarGrade.values()), + new EnumChoiceRenderer<>(SeminarRespondentsPanel.this), + SeminarRespondentsPanel.this.getString("confirmation", respondent) + ); this.respondent = respondent; setSuffix(" "); } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanel.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanel.java index e5b3ae8039..59f3f7d950 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; +import java.util.Date; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.feedback.FencedFeedbackPanel; @@ -27,10 +29,8 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import jakarta.inject.Inject; -import java.util.Date; - public class SeminarThesisPanel extends GenericPanel { + static final String DEADLINE_INFORMATION = "deadlineInformation"; static final String DATE = "date"; static final String UPLOAD = "upload"; @@ -41,12 +41,12 @@ public class SeminarThesisPanel extends GenericPanel { @Inject private FinalSeminarService seminarService; + @Inject private FinalSeminarUploadController seminarUploadController; public SeminarThesisPanel(final String id, final IModel model) { super(id, model); - add(new FencedFeedbackPanel(FEEDBACK, this)); IModel deadline = new LoadableDetachableModel<>() { @@ -71,26 +71,26 @@ public class SeminarThesisPanel extends GenericPanel { super.onConfigure(); User currentUser = SciProSession.get().getUser(); FinalSeminar seminar = getSeminar(); - boolean isEmployee = currentUser - .getRoles() - .stream() - .anyMatch(role -> role.authorizedForRole(Roles.SUPERVISOR)); + boolean isEmployee = currentUser.getRoles().stream().anyMatch(role -> role.authorizedForRole(Roles.SUPERVISOR)); boolean projectMember = seminar - .getProject() - .getMembers() - .stream() - .map(Member::getUser) - .anyMatch(currentUser::equals); + .getProject() + .getMembers() + .stream() + .map(Member::getUser) + .anyMatch(currentUser::equals); boolean seminarParticipant = - seminar.getActiveParticipants().contains(currentUser) - || seminar.getOpponents().contains(currentUser); + seminar.getActiveParticipants().contains(currentUser) || seminar.getOpponents().contains(currentUser); setVisible(isEmployee || seminarParticipant || projectMember); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(JavaScriptReferenceHeaderItem.forUrl("https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.min.js")); + response.render( + JavaScriptReferenceHeaderItem.forUrl( + "https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.min.js" + ) + ); response.render(OnDomReadyHeaderItem.forScript("bsCustomFileInput.init();")); } @@ -98,8 +98,7 @@ public class SeminarThesisPanel extends GenericPanel { add(new ReplaceSeminarDocumentForm("replaceDocument", finalSeminarModel)); } - protected void onDelete() { - } + protected void onDelete() {} private void deleteThesis(AjaxRequestTarget target) { FinalSeminar seminar = seminarService.deleteThesis(getSeminar()); @@ -114,17 +113,22 @@ public class SeminarThesisPanel extends GenericPanel { } private void addNoThesisText() { - add(new Label(NO_THESIS, new StringResourceModel("noThesis", SeminarThesisPanel.this, null)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!seminarService.hasThesis(getModelObject())); + add( + new Label(NO_THESIS, new StringResourceModel("noThesis", SeminarThesisPanel.this, null)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!seminarService.hasThesis(getModelObject())); + } } - }); + ); } private void addDeleteLink() { - AjaxLink deleteLink = new AjaxConfirmationLink<>(DELETE_THESIS, "Are you sure you want to delete the final seminar thesis file?") { + AjaxLink deleteLink = new AjaxConfirmationLink<>( + DELETE_THESIS, + "Are you sure you want to delete the final seminar thesis file?" + ) { @Override public void onClick(AjaxRequestTarget target) { deleteThesis(target); @@ -141,7 +145,13 @@ public class SeminarThesisPanel extends GenericPanel { } private void addDownloadLink() { - add(new ViewAttachmentPanel(DOWNLOAD_THESIS, getModel().map(FinalSeminar::getDocument).map(FileReference::getFileDescription), DateStyle.DATETIME)); + add( + new ViewAttachmentPanel( + DOWNLOAD_THESIS, + getModel().map(FinalSeminar::getDocument).map(FileReference::getFileDescription), + DateStyle.DATETIME + ) + ); } private class NewSeminarDocumentUploadForm extends Form { @@ -150,7 +160,6 @@ public class SeminarThesisPanel extends GenericPanel { private NewSeminarDocumentUploadForm(final String id, final IModel seminar) { super(id, seminar); - fileUploadField = new FileUploadField("fileUpload"); fileUploadField.setRequired(true); add(fileUploadField); @@ -160,22 +169,28 @@ public class SeminarThesisPanel extends GenericPanel { protected void onSubmit() { FileUpload fileUpload = fileUploadField.getFileUpload(); SeminarDocumentUpload result = seminarUploadController.storeSeminarDocument( - WicketFileUpload.from(fileUpload), getModelObject()); + WicketFileUpload.from(fileUpload), + getModelObject() + ); switch (result) { case SUCCESS -> success(getString("upload.success")); case ERROR_MUST_BE_PDF -> error(getString("seminar_document_must_be_pdf")); - case ERROR_UPLOADER_MUST_BE_AUTHOR -> error(getString("seminar_document_can_only_be_uploaded_by_authors")); + case ERROR_UPLOADER_MUST_BE_AUTHOR -> error( + getString("seminar_document_can_only_be_uploaded_by_authors") + ); } } @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(getSeminar().getProject().isParticipant(SciProSession.get().getUser()) && !seminarService.hasThesis(getSeminar())); + setVisibilityAllowed( + getSeminar().getProject().isParticipant(SciProSession.get().getUser()) && + !seminarService.hasThesis(getSeminar()) + ); if (!getSeminar().getProject().isFinalSeminarRuleExempted()) { setEnabled(!getSeminar().isDeleted() && !seminarService.hasDeadlinePassed(getSeminar())); - } - else { + } else { setEnabled(true); } } @@ -199,7 +214,6 @@ public class SeminarThesisPanel extends GenericPanel { public ReplaceSeminarDocumentForm(final String id, final IModel finalSeminarModel) { super(id, finalSeminarModel); - fileUploadField = new FileUploadField("document"); fileUploadField.setRequired(true); add(fileUploadField); @@ -209,7 +223,8 @@ public class SeminarThesisPanel extends GenericPanel { protected void onConfigure() { super.onConfigure(); final boolean hasThesis = seminarService.hasThesis(getModelObject()); - final boolean seminarHasHappened = getModelObject().getStartDate() != null && getModelObject().getStartDate().before(new Date()); + final boolean seminarHasHappened = + getModelObject().getStartDate() != null && getModelObject().getStartDate().before(new Date()); final boolean isAuthor = getModelObject().getProject().isParticipant(SciProSession.get().getUser()); setVisible(hasThesis && !seminarHasHappened && isAuthor); } @@ -217,11 +232,15 @@ public class SeminarThesisPanel extends GenericPanel { @Override protected void onSubmit() { SeminarDocumentUpload result = seminarUploadController.replaceSeminarDocument( - getModelObject(), WicketFileUpload.from(fileUploadField.getFileUpload())); + getModelObject(), + WicketFileUpload.from(fileUploadField.getFileUpload()) + ); switch (result) { case SUCCESS -> success(getString("upload.success")); case ERROR_MUST_BE_PDF -> error(getString("seminar_document_must_be_pdf")); - case ERROR_UPLOADER_MUST_BE_AUTHOR -> error(getString("seminar_document_can_only_be_uploaded_by_authors")); + case ERROR_UPLOADER_MUST_BE_AUTHOR -> error( + getString("seminar_document_can_only_be_uploaded_by_authors") + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPage.java index c38c00feff..4202bc97da 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -11,19 +12,24 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorPage; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -public class SupervisorFinalSeminarDetailsPage extends AbstractSupervisorPage implements MenuHighlightSupervisorFinalSeminars { +public class SupervisorFinalSeminarDetailsPage + extends AbstractSupervisorPage + implements MenuHighlightSupervisorFinalSeminars { public static final String SEMINAR_PANEL = "seminarPanel"; + @Inject private ProjectService projectService; + @Inject private FinalSeminarService finalSeminarService; public SupervisorFinalSeminarDetailsPage(PageParameters pp) { super(pp); - DetachableServiceModel seminarModel = new DetachableServiceModel<>(finalSeminarService, getSeminarFromProject(pp)); + DetachableServiceModel seminarModel = new DetachableServiceModel<>( + finalSeminarService, + getSeminarFromProject(pp) + ); init(seminarModel); } diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPage.java index e184ccc4d6..cee23205f1 100755 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPage.java @@ -4,6 +4,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; public class SupervisorFinalSeminarListingPage extends AbstractSupervisorAllProjectsPage { + public SupervisorFinalSeminarListingPage(PageParameters pp) { super(pp); add(new FinalSeminarDataPanel("dp", true)); diff --git a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPage.java b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPage.java index b1c77f5442..be83252129 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -16,17 +17,17 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.FINAL_SEMINAR) -public class SupervisorFinalSeminarPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects, MenuHighlightFinalSeminar { +public class SupervisorFinalSeminarPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects, MenuHighlightFinalSeminar { + @Inject private FinalSeminarService finalSeminarService; public SupervisorFinalSeminarPage(final PageParameters pp) { super(pp); - IModel seminar = getSeminar(); add(new FeedbackPanel("feedback")); @@ -43,13 +44,20 @@ public class SupervisorFinalSeminarPage extends AbstractSupervisorProjectDetails } }; add(info); - info.add(new UrkundSubmissionPanel("urkund", seminar.map(FinalSeminar::getDocument).map(FileReference::getFileDescription))); - info.add(new SeminarThesisPanel("thesis", seminar) { - @Override - protected void onDelete() { - setResponsePage(getPage()); + info.add( + new UrkundSubmissionPanel( + "urkund", + seminar.map(FinalSeminar::getDocument).map(FileReference::getFileDescription) + ) + ); + info.add( + new SeminarThesisPanel("thesis", seminar) { + @Override + protected void onDelete() { + setResponsePage(getPage()); + } } - }); + ); info.add(new SeminarRespondentsPanel("testRespondents", seminar)); info.add(new SeminarOppositionPanel("testOpposition", seminar)); info.add(new SeminarActiveParticipantsPanel("testParticipants", seminar)); @@ -62,4 +70,4 @@ public class SupervisorFinalSeminarPage extends AbstractSupervisorProjectDetails return current != null ? current : new FinalSeminar(project); }); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanel.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanel.java index b95b1b7e48..9aa5c2bb77 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalthesis; +import static se.su.dsv.scipro.finalthesis.FinalThesis.Status.*; + +import jakarta.inject.Inject; +import java.util.Date; +import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -21,14 +26,9 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.Date; -import java.util.Optional; - -import static se.su.dsv.scipro.finalthesis.FinalThesis.Status.*; - @ProjectModuleComponent(ProjectModule.GRADING) public class ApproveFinalThesisPanel extends GenericPanel { + public static final String REJECT = "reject"; public static final String REJECT_PANEL = "rejectPanel"; public static final String REJECT_CONTAINER = "rejectContainer"; @@ -45,13 +45,13 @@ public class ApproveFinalThesisPanel extends GenericPanel { public static final String STATUS_NO_THESIS_LABEL = "statusNoThesisLabel"; public static final String REJECTED_INFO_LABEL = "rejectedInfoLabel"; - private final ThesisContainer thesisContainer; private final WebMarkupContainer waitingForAuthorContainer; private final WebMarkupContainer thesisApprovedContainer; @Inject private FinalThesisService finalThesisService; + @Inject private FinalSeminarService finalSeminarService; @@ -61,27 +61,38 @@ public class ApproveFinalThesisPanel extends GenericPanel { thesisContainer.setVisibilityAllowed(visibilityAllowed()); waitingForAuthorContainer.setVisibilityAllowed(visibilityAllowed()); thesisApprovedContainer.setVisibilityAllowed(visibilityAllowed()); - thesisContainer.setVisible(finalThesisService.hasFinalThesis(getModelObject()) && getFinalThesis().getObject().getStatus() == NO_DECISION); - waitingForAuthorContainer.setVisible(!finalThesisService.hasFinalThesis(getModelObject()) || thesisHasStatus(REJECTED)); - thesisApprovedContainer.setVisible(getFinalThesis().getObject() != null && getFinalThesis().getObject().getStatus() == APPROVED); + thesisContainer.setVisible( + finalThesisService.hasFinalThesis(getModelObject()) && + getFinalThesis().getObject().getStatus() == NO_DECISION + ); + waitingForAuthorContainer.setVisible( + !finalThesisService.hasFinalThesis(getModelObject()) || thesisHasStatus(REJECTED) + ); + thesisApprovedContainer.setVisible( + getFinalThesis().getObject() != null && getFinalThesis().getObject().getStatus() == APPROVED + ); } private boolean visibilityAllowed() { - if (finalSeminarService.hasHadFinalSeminar(getModelObject()) && !getModelObject().isReviewer(SciProSession.get().getUser())) { + if ( + finalSeminarService.hasHadFinalSeminar(getModelObject()) && + !getModelObject().isReviewer(SciProSession.get().getUser()) + ) { return true; } else return thesisHasStatus(APPROVED); } public ApproveFinalThesisPanel(String id, final IModel projectIModel) { super(id, projectIModel); - - add(new WebMarkupContainer("help") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!finalThesisService.hasFinalThesis(projectIModel.getObject())); + add( + new WebMarkupContainer("help") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!finalThesisService.hasFinalThesis(projectIModel.getObject())); + } } - }); + ); thesisContainer = new ThesisContainer(THESIS_CONTAINER); add(thesisContainer); @@ -93,80 +104,92 @@ public class ApproveFinalThesisPanel extends GenericPanel { thesisApprovedContainer.setOutputMarkupId(true); add(thesisApprovedContainer); thesisApprovedContainer.add(new ThesisApprovedPanel(THESIS_APPROVED_PANEL, projectIModel)); - } private class WaitingForAuthorContainer extends WebMarkupContainer { + public WaitingForAuthorContainer(String id) { super(id); - - add(new Label(STATUS_NO_THESIS_LABEL, new ResourceModel("no.thesis.status.label")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!finalThesisService.hasFinalThesis(getModelObject())); + add( + new Label(STATUS_NO_THESIS_LABEL, new ResourceModel("no.thesis.status.label")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!finalThesisService.hasFinalThesis(getModelObject())); + } } - }); - add(new Label(STATUS_REJECTED_LABEL, new ResourceModel("thesis.rejected.status.label")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(thesisHasStatus(REJECTED)); + ); + add( + new Label(STATUS_REJECTED_LABEL, new ResourceModel("thesis.rejected.status.label")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(thesisHasStatus(REJECTED)); + } } - }); + ); - - add(new DateLabel(REJECTED_DATE_LABEL, getRejectedDate()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(thesisHasStatus(REJECTED)); + add( + new DateLabel(REJECTED_DATE_LABEL, getRejectedDate()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(thesisHasStatus(REJECTED)); + } } - }); + ); - add(new Label("rejection_comment", getFinalThesis().map(FinalThesis::getRejectionComment)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(thesisHasStatus(REJECTED)); + add( + new Label("rejection_comment", getFinalThesis().map(FinalThesis::getRejectionComment)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(thesisHasStatus(REJECTED)); + } } - }); + ); - add(new Label(REJECTED_INFO_LABEL, new ResourceModel("thesis.rejected.info.label")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(thesisHasStatus(REJECTED)); + add( + new Label(REJECTED_INFO_LABEL, new ResourceModel("thesis.rejected.info.label")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(thesisHasStatus(REJECTED)); + } } - }); + ); add(new FinalThesisUploadFormPanel(UPLOAD_FORM_PANEL, getModel())); } } private class ThesisContainer extends WebMarkupContainer { + private final RejectFinalThesisPanel rejectFinalThesisPanel; private final WebMarkupContainer decisionContainer; public ThesisContainer(String id) { super(id); - final IModel finalThesis = getFinalThesis(); final RequiredTextField englishTitleField = new RequiredTextField<>( - "englishTitle", - LambdaModel.of(finalThesis, FinalThesis::getEnglishTitle, FinalThesis::setEnglishTitle), - String.class); + "englishTitle", + LambdaModel.of(finalThesis, FinalThesis::getEnglishTitle, FinalThesis::setEnglishTitle), + String.class + ); final RequiredTextField swedishTitleField = new RequiredTextField<>( - "swedishTitle", - LambdaModel.of(finalThesis, FinalThesis::getSwedishTitle, FinalThesis::setSwedishTitle), - String.class) { + "swedishTitle", + LambdaModel.of(finalThesis, FinalThesis::getSwedishTitle, FinalThesis::setSwedishTitle), + String.class + ) { @Override protected void onConfigure() { super.onConfigure(); - final boolean inSwedish = Optional.ofNullable(ApproveFinalThesisPanel.this.getModelObject().getLanguage()) - .map(Language.SWEDISH::equals) - .orElse(false); + final boolean inSwedish = Optional.ofNullable( + ApproveFinalThesisPanel.this.getModelObject().getLanguage() + ) + .map(Language.SWEDISH::equals) + .orElse(false); setRequired(inSwedish); setVisibilityAllowed(inSwedish); } @@ -177,9 +200,10 @@ public class ApproveFinalThesisPanel extends GenericPanel { protected void onSubmit() { Project project = ApproveFinalThesisPanel.this.getModelObject(); finalThesisService.approve( - project, - englishTitleField.getModelObject(), - swedishTitleField.getModelObject()); + project, + englishTitleField.getModelObject(), + swedishTitleField.getModelObject() + ); setResponsePage(getPage()); } }; @@ -188,12 +212,17 @@ public class ApproveFinalThesisPanel extends GenericPanel { LoadableDetachableModel fileDescriptionModel = getFileDescription(); decisionContainer.add(new ViewAttachmentPanel(FILE_PANEL, fileDescriptionModel)); - decisionContainer.add(new DateLabel(DATE_LABEL, LambdaModel.of(finalThesis, FinalThesis::getDateCreated, FinalThesis::setDateCreated), DateStyle.DATETIME)); + decisionContainer.add( + new DateLabel( + DATE_LABEL, + LambdaModel.of(finalThesis, FinalThesis::getDateCreated, FinalThesis::setDateCreated), + DateStyle.DATETIME + ) + ); decisionContainer.add(englishTitleField); decisionContainer.add(swedishTitleField); - rejectFinalThesisPanel = new RejectFinalThesisPanel(REJECT_PANEL, - ApproveFinalThesisPanel.this.getModel()) { + rejectFinalThesisPanel = new RejectFinalThesisPanel(REJECT_PANEL, ApproveFinalThesisPanel.this.getModel()) { @Override protected void cancel() { showRejectionPanel(false); @@ -210,20 +239,26 @@ public class ApproveFinalThesisPanel extends GenericPanel { rejectContainer.setOutputMarkupId(true); add(rejectContainer); - decisionContainer.add(new AjaxLink(REJECT) { - @Override - public void onClick(AjaxRequestTarget target) { - showRejectionPanel(true); - target.add(rejectContainer); - target.add(decisionContainer); + decisionContainer.add( + new AjaxLink(REJECT) { + @Override + public void onClick(AjaxRequestTarget target) { + showRejectionPanel(true); + target.add(rejectContainer); + target.add(decisionContainer); + } } - }); + ); final WebMarkupContainer approve = new WebMarkupContainer("approve"); - approve.add(new JavascriptEventConfirmation("click", Model.of("Are you sure that you want to approve this final thesis?"))); + approve.add( + new JavascriptEventConfirmation( + "click", + Model.of("Are you sure that you want to approve this final thesis?") + ) + ); decisionContainer.add(approve); } - private void showRejectionPanel(boolean show) { rejectFinalThesisPanel.setVisibilityAllowed(show); decisionContainer.setVisibilityAllowed(!show); diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisPanel.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisPanel.java index 008bf88212..7f595875cb 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.finalthesis; +import static se.su.dsv.scipro.finalthesis.FinalThesis.Status; + +import jakarta.inject.Inject; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.List; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.EnumLabel; @@ -26,16 +32,9 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.List; - -import static se.su.dsv.scipro.finalthesis.FinalThesis.Status; - @ProjectModuleComponent(ProjectModule.GRADING) public class FinalThesisPanel extends GenericPanel { + public static final String UPLOAD_PANEL = "formPanel"; public static final String DOWNLOAD = "download"; public static final String REVISION_PANEL = "revisionPanel"; @@ -48,28 +47,33 @@ public class FinalThesisPanel extends GenericPanel { @Inject private FinalThesisService finalThesisService; + @Inject private FinalSeminarService finalSeminarService; + @Inject private PublishingConsentService publishingConsentService; + @Inject private ReflectionService reflectionService; + @Inject private GradingReportService gradingReportService; public FinalThesisPanel(String id, IModel project) { super(id, project); - add(new FileDescriptionPanel(DOWNLOAD, getFinalThesisFileDescription())); add(new RevisionPanel(REVISION_PANEL)); add(new ApprovedPanel(APPROVED_PANEL)); - add(new WebMarkupContainer(NO_DECISION_PANEL) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isFinalThesisStatus(Status.NO_DECISION)); + add( + new WebMarkupContainer(NO_DECISION_PANEL) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isFinalThesisStatus(Status.NO_DECISION)); + } } - }); + ); add(new FinalThesisUploadFormPanel(UPLOAD_PANEL, project)); add(new ConsentForm("consent_form", project)); } @@ -77,10 +81,14 @@ public class FinalThesisPanel extends GenericPanel { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(finalSeminarService.hasHadFinalSeminar(getModelObject()) && !reflectionService.hasToFillInReflection(getModelObject(), SciProSession.get().getUser())); + setVisibilityAllowed( + finalSeminarService.hasHadFinalSeminar(getModelObject()) && + !reflectionService.hasToFillInReflection(getModelObject(), SciProSession.get().getUser()) + ); } private class RevisionPanel extends Panel { + public RevisionPanel(String id) { super(id); add(new DateLabel(REJECTED_DATE_LABEL, getFinalThesis().map(FinalThesis::getDateRejected))); @@ -97,23 +105,27 @@ public class FinalThesisPanel extends GenericPanel { } private boolean isFinalThesisStatus(Status status) { - return getFinalThesis().getObject() != null && getFinalThesis().getObject().getStatus() == status; + return (getFinalThesis().getObject() != null && getFinalThesis().getObject().getStatus() == status); } private class ApprovedPanel extends Panel { + public ApprovedPanel(String id) { super(id); add(new EnumLabel<>("status", getModel().map(Project::getProjectStatus))); add(new DateLabel(APPROVED_DATE, getFinalThesis().map(FinalThesis::getDateApproved))); - IModel submittedToExaminerTimestamp = LoadableDetachableModel.of(() -> gradingReportService.getDateSentToExaminer(getModelObject())) - .map(instant -> instant.atZone(ZoneId.systemDefault())); - add(new Label(SUBMITTED_TO_EXAMINER_TIMESTAMP, submittedToExaminerTimestamp) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(submittedToExaminerTimestamp.getObject() != null); + IModel submittedToExaminerTimestamp = LoadableDetachableModel.of(() -> + gradingReportService.getDateSentToExaminer(getModelObject()) + ).map(instant -> instant.atZone(ZoneId.systemDefault())); + add( + new Label(SUBMITTED_TO_EXAMINER_TIMESTAMP, submittedToExaminerTimestamp) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(submittedToExaminerTimestamp.getObject() != null); + } } - }); + ); } @Override @@ -142,22 +154,20 @@ public class FinalThesisPanel extends GenericPanel { } private class ConsentForm extends Form { + final IModel levelModel; private final IModel> availableLevels; public ConsentForm(final String id, IModel project) { super(id, project); - IModel publishingConsent = LoadableDetachableModel.of( - () -> publishingConsentService.getPublishingConsent(project.getObject(), SciProSession.get().getUser())); + IModel publishingConsent = LoadableDetachableModel.of(() -> + publishingConsentService.getPublishingConsent(project.getObject(), SciProSession.get().getUser()) + ); availableLevels = publishingConsent.map(PublishingConsentService.PublishingConsent::available); levelModel = LoadableDetachableModel.of(() -> publishingConsent.getObject().selected()); - add(new DropDownChoice<>( - "consent_level", - levelModel, - availableLevels, - new EnumChoiceRenderer<>(this))); + add(new DropDownChoice<>("consent_level", levelModel, availableLevels, new EnumChoiceRenderer<>(this))); add(new FencedFeedbackPanel("feedback", this)); } @@ -165,17 +175,25 @@ public class FinalThesisPanel extends GenericPanel { @Override protected void onConfigure() { super.onConfigure(); - boolean submittedReflection = !reflectionService.hasToFillInReflection(getModelObject(), SciProSession.get().getUser()); - setVisibilityAllowed(finalThesisService.hasFinalThesis(getModelObject()) && !availableLevels.getObject().isEmpty() && submittedReflection); + boolean submittedReflection = !reflectionService.hasToFillInReflection( + getModelObject(), + SciProSession.get().getUser() + ); + setVisibilityAllowed( + finalThesisService.hasFinalThesis(getModelObject()) && + !availableLevels.getObject().isEmpty() && + submittedReflection + ); } @Override protected void onSubmit() { super.onSubmit(); final boolean success = publishingConsentService.setPublishingConsent( - getModelObject(), - SciProSession.get().getUser(), - levelModel.getObject()); + getModelObject(), + SciProSession.get().getUser(), + levelModel.getObject() + ); if (success) { success(getString("publishing_consent_level_changed")); } else { diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUpload.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUpload.java index 8068322e6d..ef194fe783 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUpload.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUpload.java @@ -2,5 +2,4 @@ package se.su.dsv.scipro.finalthesis; import org.apache.wicket.markup.html.form.upload.FileUpload; -public record FinalThesisUpload(String swedishTitle, String englishTitle, FileUpload fileUpload) { -} +public record FinalThesisUpload(String swedishTitle, String englishTitle, FileUpload fileUpload) {} diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadComponent.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadComponent.java index 9cc21d4c8f..9b78c01c6f 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadComponent.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadComponent.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalthesis; +import java.util.List; import org.apache.wicket.markup.html.form.FormComponentPanel; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.TextField; @@ -13,8 +14,6 @@ import org.apache.wicket.validation.ValidationError; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.Language; -import java.util.List; - public class FinalThesisUploadComponent extends FormComponentPanel { private final FileUploadField uploadField; @@ -43,7 +42,13 @@ public class FinalThesisUploadComponent extends FormComponentPanel> { + @Override public void validate(IValidatable> validatable) { for (FileUpload fileUpload : validatable.getValue()) { diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanel.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanel.java index 3a4c15d025..f3a30689bf 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalthesis; +import jakarta.inject.Inject; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.upload.FileUpload; @@ -9,8 +10,6 @@ import se.su.dsv.scipro.files.WicketProjectFileUpload; import se.su.dsv.scipro.finalseminar.FinalSeminarService; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; - class FinalThesisUploadFormPanel extends GenericPanel { public static final String FILE = "file"; @@ -18,6 +17,7 @@ class FinalThesisUploadFormPanel extends GenericPanel { @Inject private FinalThesisService finalThesisService; + @Inject private FinalSeminarService finalSeminarService; @@ -43,7 +43,11 @@ class FinalThesisUploadFormPanel extends GenericPanel { FileUpload fileUpload = finalThesisUpload.fileUpload(); String englishTitle = finalThesisUpload.englishTitle(); String swedishTitle = finalThesisUpload.swedishTitle(); - finalThesisService.upload(new WicketProjectFileUpload(fileUpload, getModelObject()), englishTitle, swedishTitle); + finalThesisService.upload( + new WicketProjectFileUpload(fileUpload, getModelObject()), + englishTitle, + swedishTitle + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanel.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanel.java index 6c79b27565..318cce9434 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.finalthesis; +import jakarta.inject.Inject; +import java.util.*; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton; import org.apache.wicket.markup.html.basic.Label; @@ -21,10 +24,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; -import java.util.stream.Collectors; - public class RejectFinalThesisPanel extends GenericPanel { private final IModel project; @@ -66,23 +65,27 @@ public class RejectFinalThesisPanel extends GenericPanel { feedbackPanel.setOutputMarkupId(true); subjectField = newSubjectField(Model.of("")); form.add(subjectField); - form.add(new Label(MESSAGE_LABEL,new ResourceModel("why.description.needed"))); + form.add(new Label(MESSAGE_LABEL, new ResourceModel("why.description.needed"))); contentArea = new TextArea<>(CONTENT, Model.of("")).setRequired(true); form.add(contentArea); upload = new FileUploadField(ATTACHMENT); form.add(upload); - form.add(new Link(CANCEL_REJECTION) { - @Override - public void onClick() { - cancel(); + form.add( + new Link(CANCEL_REJECTION) { + @Override + public void onClick() { + cancel(); + } } - }); - form.add(new AjaxFallbackButton(CREATE, form) { - @Override - protected void onError(Optional target) { - target.ifPresent(t -> t.add(feedbackPanel)); + ); + form.add( + new AjaxFallbackButton(CREATE, form) { + @Override + protected void onError(Optional target) { + target.ifPresent(t -> t.add(feedbackPanel)); + } } - }); + ); } private RequiredTextField newSubjectField(IModel subject) { @@ -91,24 +94,23 @@ public class RejectFinalThesisPanel extends GenericPanel { return field; } - protected void cancel(){} + protected void cancel() {} - protected void onRejection() { - } + protected void onRejection() {} protected void onSubmit() { User user = SciProSession.get().getUser(); - Set uploads = upload.getFileUploads().stream() - .map(WicketFileUpload::from) - .map(Attachment::newUpload) - .collect(Collectors.toSet()); + Set uploads = upload + .getFileUploads() + .stream() + .map(WicketFileUpload::from) + .map(Attachment::newUpload) + .collect(Collectors.toSet()); - projectForumService.createThread(project.getObject(), user, - REJECTED_SUBJECT, contentArea.getInput(), uploads); + projectForumService.createThread(project.getObject(), user, REJECTED_SUBJECT, contentArea.getInput(), uploads); finalThesisService.reject(getModelObject(), contentArea.getInput()); onRejection(); setResponsePage(getPage()); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPage.java b/view/src/main/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPage.java index 7a27339a55..c15cc54bef 100644 --- a/view/src/main/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPage.java @@ -1,68 +1,83 @@ -package se.su.dsv.scipro.finalthesis; - -import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; -import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; -import org.apache.wicket.markup.html.panel.Fragment; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.*; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.components.DateColumn; -import se.su.dsv.scipro.components.ExportableDataPanel; -import se.su.dsv.scipro.components.datatables.UserColumn; -import se.su.dsv.scipro.dataproviders.FilteredDataProvider; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.repository.components.FileDownloadLink; -import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; - -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - -public class SupervisorFinalThesisListingPage extends AbstractSupervisorAllProjectsPage { - - @Inject - private FinalThesisService finalThesisService; - - public SupervisorFinalThesisListingPage(PageParameters pp) { - super(pp); - FilteredDataProvider provider = new FilteredDataProvider<>(finalThesisService, getFilter()); - provider.setSort("dateApproved", SortOrder.DESCENDING); - add(new ExportableDataPanel<>("table", columns(), provider)); - } - - private IModel getFilter() { - FinalThesisService.Filter filter = new FinalThesisService.Filter(); - filter.setStatus(FinalThesis.Status.APPROVED); - return Model.of(filter); - } - - private List> columns() { - return Arrays.asList( - new DateColumn<>(new StringResourceModel("date.approved", this), FinalThesis::getDateApproved, "dateApproved"), - new LambdaColumn<>(new StringResourceModel("project.type", this), "project.projectType.name", ft -> ft.getProject().getProjectType().getName()), - new LambdaColumn<>(new StringResourceModel("project.title", this), "project.title", ft -> ft.getProject().getTitle()), - new UserColumn<>(new StringResourceModel("supervisor", this), "project.headSupervisor.fullName", ft -> ft.getProject().getHeadSupervisor()), - new ThesisFileColumn() - ); - } - - private class ThesisFileColumn extends AbstractColumn { - public ThesisFileColumn() { - super(new StringResourceModel("thesis.file", SupervisorFinalThesisListingPage.this, null)); - } - - @Override - public void populateItem(Item> item, String id, IModel model) { - FileDownloadLink link = new FileDownloadLink<>("name", model.map(FinalThesis::getDocument).map(FileReference::getFileDescription)); - link.setBody(model.map(FinalThesis::getDocument).map(FileReference::getName)); - Fragment cell = new Fragment(id, "_name", SupervisorFinalThesisListingPage.this); - cell.add(link); - item.add(cell); - } - } - -} +package se.su.dsv.scipro.finalthesis; + +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; +import org.apache.wicket.markup.html.panel.Fragment; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.*; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import se.su.dsv.scipro.components.DateColumn; +import se.su.dsv.scipro.components.ExportableDataPanel; +import se.su.dsv.scipro.components.datatables.UserColumn; +import se.su.dsv.scipro.dataproviders.FilteredDataProvider; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.repository.components.FileDownloadLink; +import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; + +public class SupervisorFinalThesisListingPage extends AbstractSupervisorAllProjectsPage { + + @Inject + private FinalThesisService finalThesisService; + + public SupervisorFinalThesisListingPage(PageParameters pp) { + super(pp); + FilteredDataProvider provider = new FilteredDataProvider<>( + finalThesisService, + getFilter() + ); + provider.setSort("dateApproved", SortOrder.DESCENDING); + add(new ExportableDataPanel<>("table", columns(), provider)); + } + + private IModel getFilter() { + FinalThesisService.Filter filter = new FinalThesisService.Filter(); + filter.setStatus(FinalThesis.Status.APPROVED); + return Model.of(filter); + } + + private List> columns() { + return Arrays.asList( + new DateColumn<>( + new StringResourceModel("date.approved", this), + FinalThesis::getDateApproved, + "dateApproved" + ), + new LambdaColumn<>(new StringResourceModel("project.type", this), "project.projectType.name", ft -> + ft.getProject().getProjectType().getName() + ), + new LambdaColumn<>(new StringResourceModel("project.title", this), "project.title", ft -> + ft.getProject().getTitle() + ), + new UserColumn<>(new StringResourceModel("supervisor", this), "project.headSupervisor.fullName", ft -> + ft.getProject().getHeadSupervisor() + ), + new ThesisFileColumn() + ); + } + + private class ThesisFileColumn extends AbstractColumn { + + public ThesisFileColumn() { + super(new StringResourceModel("thesis.file", SupervisorFinalThesisListingPage.this, null)); + } + + @Override + public void populateItem(Item> item, String id, IModel model) { + FileDownloadLink link = new FileDownloadLink<>( + "name", + model.map(FinalThesis::getDocument).map(FileReference::getFileDescription) + ); + link.setBody(model.map(FinalThesis::getDocument).map(FileReference::getName)); + Fragment cell = new Fragment(id, "_name", SupervisorFinalThesisListingPage.this); + cell.add(link); + item.add(cell); + } + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanel.java index 701bfd17aa..63ea65884e 100755 --- a/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.firstmeeting; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -12,47 +13,52 @@ import se.su.dsv.scipro.date.DateService; import se.su.dsv.scipro.match.Idea; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public abstract class FirstMeetingColumnPanel extends GenericPanel { @Inject private DateService dateService; - public FirstMeetingColumnPanel(String id, final IModel model) { - super(id, model); - if (getModelObject().getMatchStatus() == Idea.Status.UNMATCHED) { - add(new Label("label", "-")); - } else { - add(new AjaxLinkPanel<>("label", getModel(), getDisplayModel()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(!(model.getObject().isInactive() || (!isSupervisor(getModelObject()) && getModelObject().getFirstMeeting() == null))); - } + public FirstMeetingColumnPanel(String id, final IModel model) { + super(id, model); + if (getModelObject().getMatchStatus() == Idea.Status.UNMATCHED) { + add(new Label("label", "-")); + } else { + add( + new AjaxLinkPanel<>("label", getModel(), getDisplayModel()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled( + !(model.getObject().isInactive() || + (!isSupervisor(getModelObject()) && getModelObject().getFirstMeeting() == null)) + ); + } - @Override - public void onClick(AjaxRequestTarget target, final IModel model) { - onColumnClick(target, model); - } - }); - } - } + @Override + public void onClick(AjaxRequestTarget target, final IModel model) { + onColumnClick(target, model); + } + } + ); + } + } - private IModel getDisplayModel() { - if (getModelObject().getFirstMeeting() == null) { - if (isSupervisor(getModelObject()) && !getModelObject().isInactive()) { - return new ResourceModel("none_create_one"); - } - } else { - return new Model<>(dateService.format(getModelObject().getFirstMeeting().getFirstMeetingDate(), DateStyle.DATETIME)); - } - return new ResourceModel("none"); - } + private IModel getDisplayModel() { + if (getModelObject().getFirstMeeting() == null) { + if (isSupervisor(getModelObject()) && !getModelObject().isInactive()) { + return new ResourceModel("none_create_one"); + } + } else { + return new Model<>( + dateService.format(getModelObject().getFirstMeeting().getFirstMeetingDate(), DateStyle.DATETIME) + ); + } + return new ResourceModel("none"); + } - protected abstract void onColumnClick(AjaxRequestTarget target, IModel model); + protected abstract void onColumnClick(AjaxRequestTarget target, IModel model); - private boolean isSupervisor(Idea idea) { - return SciProSession.get().getUser().equals(idea.getMatch().getSupervisor()); - } + private boolean isSupervisor(Idea idea) { + return SciProSession.get().getUser().equals(idea.getMatch().getSupervisor()); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanel.java b/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanel.java index 04645c91e5..c7b62f64cd 100644 --- a/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.firstmeeting; +import static java.lang.String.format; + +import jakarta.inject.Inject; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Date; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -25,13 +31,6 @@ import se.su.dsv.scipro.notifications.dataobject.IdeaEvent; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.time.Instant; -import java.time.ZoneId; -import java.util.Date; - -import static java.lang.String.format; - public class FirstMeetingPanel extends GenericPanel { public static final String MEETING_FORM = "meetingForm"; @@ -49,12 +48,14 @@ public class FirstMeetingPanel extends GenericPanel { @Inject private FirstMeetingRepository firstMeetingRepository; + @Inject private NotificationController notificationController; + @Inject private DateService dateService; - public void onSaved(AjaxRequestTarget target){} + public void onSaved(AjaxRequestTarget target) {} public FirstMeetingPanel(String id, IModel model) { super(id, model); @@ -77,9 +78,17 @@ public class FirstMeetingPanel extends GenericPanel { setVisibilityAllowed(!isSupervisor(firstMeetingModel.getObject())); } }; - studentWMC.add(new DateLabel(DATE_LABEL, model.map(Idea::getFirstMeeting).map(FirstMeeting::getFirstMeetingDate), DateStyle.DATETIME)); + studentWMC.add( + new DateLabel( + DATE_LABEL, + model.map(Idea::getFirstMeeting).map(FirstMeeting::getFirstMeetingDate), + DateStyle.DATETIME + ) + ); studentWMC.add(new Label(ROOM_LABEL, model.map(Idea::getFirstMeeting).map(FirstMeeting::getRoom))); - studentWMC.add(new MultiLineLabel(DESCRIPTION_LABEL, model.map(Idea::getFirstMeeting).map(FirstMeeting::getDescription))); + studentWMC.add( + new MultiLineLabel(DESCRIPTION_LABEL, model.map(Idea::getFirstMeeting).map(FirstMeeting::getDescription)) + ); add(studentWMC); } @@ -90,9 +99,10 @@ public class FirstMeetingPanel extends GenericPanel { private Date getCourseStartDate() { ApplicationPeriod period = getModelObject().getApplicationPeriod(); if (period != null) { - final Instant courseStartDateTime = period.getCourseStartDateTime() - .atZone(ZoneId.systemDefault()) - .toInstant(); + final Instant courseStartDateTime = period + .getCourseStartDateTime() + .atZone(ZoneId.systemDefault()) + .toInstant(); return Date.from(courseStartDateTime); } else { return new Date(); @@ -107,38 +117,55 @@ public class FirstMeetingPanel extends GenericPanel { } private class MeetingForm extends Form { + public MeetingForm(String id, final IModel model) { super(id, model); final FeedbackPanel feedback = new FeedbackPanel(FEEDBACK); feedback.setOutputMarkupId(true); add(feedback); - FormComponent date = new BootstrapDateTimeComponent(FIRST_MEETING_DATE, LambdaModel.of(model, FirstMeeting::getFirstMeetingDate, FirstMeeting::setFirstMeetingDate)); + FormComponent date = new BootstrapDateTimeComponent( + FIRST_MEETING_DATE, + LambdaModel.of(model, FirstMeeting::getFirstMeetingDate, FirstMeeting::setFirstMeetingDate) + ); date.setRequired(true); date.add(DateValidator.minimum(new Date())); add(date); - add(new TextArea<>(DESCRIPTION, LambdaModel.of(model, FirstMeeting::getDescription, FirstMeeting::setDescription))); - add(new RequiredTextField<>(ROOM_FIELD, LambdaModel.of(model, FirstMeeting::getRoom, FirstMeeting::setRoom))); + add( + new TextArea<>( + DESCRIPTION, + LambdaModel.of(model, FirstMeeting::getDescription, FirstMeeting::setDescription) + ) + ); + add( + new RequiredTextField<>(ROOM_FIELD, LambdaModel.of(model, FirstMeeting::getRoom, FirstMeeting::setRoom)) + ); add(new InfoPanel(ROOM_HELP, new ResourceModel("roomInfo"))); - add(new AjaxSubmitLink(SUBMIT_BUTTON) { - @Override - protected void onSubmit(final AjaxRequestTarget target) { - target.add(feedback); - onSaved(target); - } + add( + new AjaxSubmitLink(SUBMIT_BUTTON) { + @Override + protected void onSubmit(final AjaxRequestTarget target) { + target.add(feedback); + onSaved(target); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedback); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedback); + } } - }); + ); } @Override protected void onSubmit() { saveAndNotify(); - info(format(getString("meeting.scheduled", FirstMeetingPanel.this.getModel()), - dateService.format(getModelObject().getFirstMeetingDate(), DateStyle.DATETIME))); + info( + format( + getString("meeting.scheduled", FirstMeetingPanel.this.getModel()), + dateService.format(getModelObject().getFirstMeetingDate(), DateStyle.DATETIME) + ) + ); } private void saveAndNotify() { @@ -148,8 +175,11 @@ public class FirstMeetingPanel extends GenericPanel { String room = getModelObject().getRoom(); source.setMessage(date + "\n" + getString("room") + ": " + room); source.setAdditionalMessage(getModelObject().getDescription()); - notificationController.notifyIdea(FirstMeetingPanel.this.getModelObject(), - IdeaEvent.Event.FIRST_MEETING, source); + notificationController.notifyIdea( + FirstMeetingPanel.this.getModelObject(), + IdeaEvent.Event.FIRST_MEETING, + source + ); } } @@ -158,6 +188,7 @@ public class FirstMeetingPanel extends GenericPanel { } private class FirstMeetingModel extends LoadableDetachableModel { + private final IModel ideaModel; public FirstMeetingModel(IModel ideaModel) { @@ -169,8 +200,7 @@ public class FirstMeetingPanel extends GenericPanel { final Idea idea = ideaModel.getObject(); if (idea.getFirstMeeting() != null) { return idea.getFirstMeeting(); - } - else { + } else { return new FirstMeeting(getCourseStartDate(), idea); } } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/Forum.java b/view/src/main/java/se/su/dsv/scipro/forum/Forum.java index 599d82601c..33948038df 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/Forum.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/Forum.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.forum; +import java.util.*; import org.apache.wicket.util.io.IClusterable; import se.su.dsv.scipro.system.User; -import java.util.*; - public interface Forum extends IClusterable { A createThread(User user, String subject, String content, Set attachments); } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/ForumThread.java b/view/src/main/java/se/su/dsv/scipro/forum/ForumThread.java index 2babb3db1a..d291c15e25 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/ForumThread.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/ForumThread.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.forum; +import java.util.*; import org.apache.wicket.util.io.IClusterable; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.system.User; -import java.util.*; - public interface ForumThread extends IClusterable { List getPosts(A a); ForumPost reply(A a, User poster, String content, Set attachments); diff --git a/view/src/main/java/se/su/dsv/scipro/forum/ProjectForum.java b/view/src/main/java/se/su/dsv/scipro/forum/ProjectForum.java index c52ae43d50..78b4401a5f 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/ProjectForum.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/ProjectForum.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.forum; +import java.util.*; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.*; - public class ProjectForum implements Forum { + private final ProjectForumService projectForumService; private final IModel projectModel; @@ -17,9 +17,13 @@ public class ProjectForum implements Forum { } @Override - public ProjectThread createThread(final User user, final String subject, final String content, final Set attachments) { + public ProjectThread createThread( + final User user, + final String subject, + final String content, + final Set attachments + ) { Project project = projectModel.getObject(); return projectForumService.createThread(project, user, subject, content, attachments); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePage.java index 5a0de1f228..dd6850f5b5 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePage.java @@ -16,13 +16,12 @@ public class ProjectForumBasePage extends AbstractProjectDetailsPage { public ProjectForumBasePage(PageParameters pp) { super(pp); - StringValue value = pp.get(PageParameterKeys.MAP.get(ForumThread.class)); Long threadId = null; - if(!value.isNull()) { + if (!value.isNull()) { threadId = value.toLongObject(); } - if(threadId==null) { + if (threadId == null) { throw new RestartResponseException(ProjectThreadedForumPage.class, pp); } throw new RestartResponseException(ProjectViewForumThreadPage.class, pp); diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePage.java index 2be707e4ff..ac82d146a5 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePage.java @@ -16,13 +16,12 @@ public class SupervisorForumBasePage extends AbstractSupervisorProjectDetailsPag public SupervisorForumBasePage(PageParameters pp) { super(pp); - StringValue value = pp.get(PageParameterKeys.MAP.get(ForumThread.class)); Long threadId = null; - if(!value.isNull()) { + if (!value.isNull()) { threadId = value.toLongObject(); } - if(threadId==null) { + if (threadId == null) { throw new RestartResponseException(SupervisorThreadedForumPage.class, pp); } throw new RestartResponseException(SupervisorViewForumThreadPage.class, pp); diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ForumThreadDiscussable.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ForumThreadDiscussable.java index c7bb5fde65..170bdddb5f 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ForumThreadDiscussable.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ForumThreadDiscussable.java @@ -7,6 +7,7 @@ import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; public class ForumThreadDiscussable implements Discussable { + @Override public IModel discussion(final IModel a) { return LambdaModel.of(a, ProjectThread::getForumThread, ProjectThread::setForumThread); diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPage.java index c0eed424bb..26d4d02170 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.pages.threaded; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorMyProjects; @@ -17,28 +18,36 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class ProjectCreateForumThreadPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects, MenuHighlightForum { +public class ProjectCreateForumThreadPage + extends AbstractProjectDetailsPage + implements MenuHighlightAuthorMyProjects, MenuHighlightForum { -@Inject -private ProjectForumService projectForumService; + @Inject + private ProjectForumService projectForumService; public ProjectCreateForumThreadPage(PageParameters pp) { super(pp); - add(new BookmarkablePageLink(BACK_LINK, ProjectForumBasePage.class, getPageParameters(projectModel.getObject()))); - add(new SubmitForumThreadPanel<>(CREATE_THREAD, new ProjectForum(projectForumService, projectModel)) { - @Override - public void onThreadCreated(final ProjectThread thread) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), projectModel.getObject().getId()); - setResponsePage(ProjectThreadedForumPage.class, pp); + add( + new BookmarkablePageLink( + BACK_LINK, + ProjectForumBasePage.class, + getPageParameters(projectModel.getObject()) + ) + ); + add( + new SubmitForumThreadPanel<>(CREATE_THREAD, new ProjectForum(projectForumService, projectModel)) { + @Override + public void onThreadCreated(final ProjectThread thread) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), projectModel.getObject().getId()); + setResponsePage(ProjectThreadedForumPage.class, pp); + } } - }); + ); } static final String BACK_LINK = "backLink"; static final String CREATE_THREAD = "createThread"; -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPage.java index 646abb3393..e42a52aaed 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -18,29 +22,28 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class ProjectThreadedForumPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects, MenuHighlightForum { +public class ProjectThreadedForumPage + extends AbstractProjectDetailsPage + implements MenuHighlightAuthorMyProjects, MenuHighlightForum { @Inject private ProjectForumService projectForumService; public ProjectThreadedForumPage(final PageParameters pp) { super(pp); - add(new BookmarkablePageLink(CREATE_THREAD_LINK, ProjectCreateForumThreadPage.class, pp)); add(new FeedbackPanel(FEEDBACK)); - add(new ThreadsOverviewPanel<>(FORUM, getThreads(), new ForumThreadDiscussable(), - (id, thread) -> { - PageParameters parameters = new PageParameters(pp) - .set(PageParameterKeys.MAP.get(ForumThread.class), thread.getObject().getId()); - return new BookmarkablePageLink<>(id, ProjectViewForumThreadPage.class, parameters); - })); + add( + new ThreadsOverviewPanel<>(FORUM, getThreads(), new ForumThreadDiscussable(), (id, thread) -> { + PageParameters parameters = new PageParameters(pp).set( + PageParameterKeys.MAP.get(ForumThread.class), + thread.getObject().getId() + ); + return new BookmarkablePageLink<>(id, ProjectViewForumThreadPage.class, parameters); + }) + ); } private IModel> getThreads() { diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPage.java index f883dbc2e0..2c9f6567a5 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.pages.threaded; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; @@ -24,25 +25,26 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class ProjectViewForumThreadPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects, MenuHighlightForum { +public class ProjectViewForumThreadPage + extends AbstractProjectDetailsPage + implements MenuHighlightAuthorMyProjects, MenuHighlightForum { @Inject private ProjectForumService projectForumService; + @Inject private BasicForumService basicForumService; + @Inject private ProjectFileService projectFileService; public ProjectViewForumThreadPage(PageParameters pp) { super(pp); - StringValue value = pp.get(PageParameterKeys.MAP.get(ForumThread.class)); Long threadId = null; - if(!value.isNull()) { + if (!value.isNull()) { threadId = value.toLongObject(); } if (threadId == null) { @@ -67,9 +69,15 @@ public class ProjectViewForumThreadPage extends AbstractProjectDetailsPage imple return projectForumService.findOne(finalThreadId); } }; - add(new ViewProjectForumThreadPanel(FORUM_THREAD, threadModel, new ProjectForumThread(projectForumService), projectModel)); + add( + new ViewProjectForumThreadPanel( + FORUM_THREAD, + threadModel, + new ProjectForumThread(projectForumService), + projectModel + ) + ); } static final String FORUM_THREAD = "forumThread"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPage.java index b9c2f27796..39b4a8634c 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.pages.threaded; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightForum; @@ -17,28 +18,36 @@ import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class SupervisorCreateForumThreadPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { +public class SupervisorCreateForumThreadPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { @Inject private ProjectForumService projectForumService; public SupervisorCreateForumThreadPage(PageParameters pp) { super(pp); - add(new BookmarkablePageLink(BACK_LINK, SupervisorForumBasePage.class, getPageParameters(projectModel.getObject()))); - add(new SubmitForumThreadPanel<>(CREATE_THREAD, new ProjectForum(projectForumService, projectModel)) { - @Override - public void onThreadCreated(final ProjectThread thread) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), projectModel.getObject().getId()); - setResponsePage(SupervisorThreadedForumPage.class, pp); + add( + new BookmarkablePageLink( + BACK_LINK, + SupervisorForumBasePage.class, + getPageParameters(projectModel.getObject()) + ) + ); + add( + new SubmitForumThreadPanel<>(CREATE_THREAD, new ProjectForum(projectForumService, projectModel)) { + @Override + public void onThreadCreated(final ProjectThread thread) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), projectModel.getObject().getId()); + setResponsePage(SupervisorThreadedForumPage.class, pp); + } } - }); + ); } static final String BACK_LINK = "backLink"; static final String CREATE_THREAD = "createThread"; -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPage.java index c418c3a313..ffbf9664d9 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -17,31 +23,28 @@ import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) +@Authorization(authorizedRoles = { SUPERVISOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class SupervisorThreadedForumPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { +public class SupervisorThreadedForumPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { @Inject private ProjectForumService projectForumService; public SupervisorThreadedForumPage(final PageParameters pp) { super(pp); - add(new BookmarkablePageLink(CREATE_THREAD_LINK, SupervisorCreateForumThreadPage.class, pp)); add(new FeedbackPanel(FEEDBACK)); - add(new ThreadsOverviewPanel<>(FORUM, getThreads(), new ForumThreadDiscussable(), - (id, thread) -> { - PageParameters parameters = new PageParameters(pp) - .set(PageParameterKeys.MAP.get(ForumThread.class), thread.getObject().getId()); - return new BookmarkablePageLink<>(id, SupervisorViewForumThreadPage.class, parameters); - })); + add( + new ThreadsOverviewPanel<>(FORUM, getThreads(), new ForumThreadDiscussable(), (id, thread) -> { + PageParameters parameters = new PageParameters(pp).set( + PageParameterKeys.MAP.get(ForumThread.class), + thread.getObject().getId() + ); + return new BookmarkablePageLink<>(id, SupervisorViewForumThreadPage.class, parameters); + }) + ); } private IModel> getThreads() { diff --git a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPage.java b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPage.java index 1e95bebb46..4d31c6d428 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.pages.threaded; +import jakarta.inject.Inject; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; @@ -24,22 +25,23 @@ import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.FORUM) -public class SupervisorViewForumThreadPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { +public class SupervisorViewForumThreadPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects, MenuHighlightForum { @Inject private ProjectForumService projectForumService; + @Inject private BasicForumService basicForumService; + @Inject private ProjectFileService projectFileService; public SupervisorViewForumThreadPage(PageParameters pp) { super(pp); - StringValue value = pp.get(PageParameterKeys.MAP.get(ForumThread.class)); Long threadId = null; if (!value.isNull()) { @@ -63,14 +65,20 @@ public class SupervisorViewForumThreadPage extends AbstractSupervisorProjectDeta return projectForumService.findOne(finalThreadId); } }; - add(new ViewProjectForumThreadPanel(FORUM_THREAD, threadModel, new ProjectForumThread(projectForumService), projectModel) { - @Override - protected Class getForumPage() { - return SupervisorForumBasePage.class; + add( + new ViewProjectForumThreadPanel( + FORUM_THREAD, + threadModel, + new ProjectForumThread(projectForumService), + projectModel + ) { + @Override + protected Class getForumPage() { + return SupervisorForumBasePage.class; + } } - }); + ); } static final String FORUM_THREAD = "forumThread"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/AbstractReadStatePanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/AbstractReadStatePanel.java index 25eea67afa..92a80a83ef 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/AbstractReadStatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/AbstractReadStatePanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.panels; +import java.util.Optional; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; @@ -7,15 +8,12 @@ import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.WebComponent; import org.apache.wicket.markup.html.panel.Panel; -import java.util.Optional; - public abstract class AbstractReadStatePanel extends Panel { private final Component icon; public AbstractReadStatePanel(final String id) { super(id); - AjaxFallbackLink link = new AjaxFallbackLink<>(TOGGLE) { @Override public void onClick(final Optional target) { @@ -33,6 +31,7 @@ public abstract class AbstractReadStatePanel extends Panel { } protected abstract boolean isRead(); + protected abstract void onFlagClick(final AjaxRequestTarget target); public static final String TOGGLE = "toggle"; diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanel.java index 9dc3656da1..004d99561a 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanel.java @@ -25,28 +25,42 @@ public class ForumPostPanel extends Panel { public ForumPostPanel(String id, final IModel model) { super(id); add(new UserLinkPanel(POSTED_BY, LambdaModel.of(model, ForumPost::getPostedBy, ForumPost::setPostedBy))); - add(new WebMarkupContainer("postedBySystem") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(model.getObject().getPostedBy() == null); + add( + new WebMarkupContainer("postedBySystem") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(model.getObject().getPostedBy() == null); + } } - }); - add(new DateLabel(DATE_CREATED, LambdaModel.of(model, ForumPost::getDateCreated, ForumPost::setDateCreated), DateStyle.DATETIME)); - add(new SmarterLinkMultiLineLabel(CONTENT, LambdaModel.of(model, ForumPost::getContent, ForumPost::setContent))); + ); + add( + new DateLabel( + DATE_CREATED, + LambdaModel.of(model, ForumPost::getDateCreated, ForumPost::setDateCreated), + DateStyle.DATETIME + ) + ); + add( + new SmarterLinkMultiLineLabel(CONTENT, LambdaModel.of(model, ForumPost::getContent, ForumPost::setContent)) + ); - add(new DisplayMultiplesPanel<>(ATTACHMENT, new ListAdapterModel<>(LambdaModel.of(model, ForumPost::getAttachments, ForumPost::setAttachments))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new ViewAttachmentPanel(componentId, t.map(FileReference::getFileDescription)); + add( + new DisplayMultiplesPanel<>( + ATTACHMENT, + new ListAdapterModel<>(LambdaModel.of(model, ForumPost::getAttachments, ForumPost::setAttachments)) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new ViewAttachmentPanel(componentId, t.map(FileReference::getFileDescription)); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!model.getObject().getAttachments().isEmpty()); + } } - - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!model.getObject().getAttachments().isEmpty()); - } - }); - + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ProjectForumThread.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ProjectForumThread.java index 26fef8f71a..f8239b1732 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ProjectForumThread.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ProjectForumThread.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.util.*; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.ForumThread; import se.su.dsv.scipro.forum.ProjectForumService; @@ -7,9 +8,8 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.system.User; -import java.util.*; - public class ProjectForumThread implements ForumThread { + private final ProjectForumService projectForumService; public ProjectForumThread(final ProjectForumService projectForumService) { @@ -22,7 +22,12 @@ public class ProjectForumThread implements ForumThread { } @Override - public ForumPost reply(final ProjectThread projectThread, final User poster, final String content, final Set attachments) { + public ForumPost reply( + final ProjectThread projectThread, + final User poster, + final String content, + final Set attachments + ) { return projectForumService.createReply(projectThread, poster, content, attachments); } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanel.java index 224eea4abb..9e9faf3b96 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.util.*; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.StatelessForm; import org.apache.wicket.markup.html.form.TextArea; @@ -13,14 +15,11 @@ import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.ForumThread; import se.su.dsv.scipro.session.SciProSession; -import java.util.*; -import java.util.stream.Collectors; - public class SubmitForumReplyPanel extends GenericPanel { final ForumThread wicketForumService; - protected void updateOnSubmit() { } + protected void updateOnSubmit() {} public SubmitForumReplyPanel(String id, IModel threadModel, final ForumThread wicketForumService) { super(id, threadModel); @@ -35,7 +34,6 @@ public class SubmitForumReplyPanel extends GenericPanel { public ForumForm(String id) { super(id); - final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback"); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); @@ -49,11 +47,18 @@ public class SubmitForumReplyPanel extends GenericPanel { @Override protected void onSubmit() { - Set attachments = upload.getFileUploads().stream() - .map(WicketFileUpload::from) - .map(Attachment::newUpload) - .collect(Collectors.toSet()); - wicketForumService.reply(SubmitForumReplyPanel.this.getModelObject(), SciProSession.get().getUser(), contentArea.getModelObject(), attachments); + Set attachments = upload + .getFileUploads() + .stream() + .map(WicketFileUpload::from) + .map(Attachment::newUpload) + .collect(Collectors.toSet()); + wicketForumService.reply( + SubmitForumReplyPanel.this.getModelObject(), + SciProSession.get().getUser(), + contentArea.getModelObject(), + attachments + ); contentArea.setModel(Model.of("")); updateOnSubmit(); } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanel.java index 26182d753c..4e2a5b8171 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton; import org.apache.wicket.markup.html.form.Form; @@ -16,15 +19,11 @@ import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.Forum; import se.su.dsv.scipro.session.SciProSession; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - public class SubmitForumThreadPanel extends Panel { private final Forum forum; - public void onThreadCreated(final A thread) { } + public void onThreadCreated(final A thread) {} public SubmitForumThreadPanel(String id, final Forum forum) { super(id); @@ -36,12 +35,11 @@ public class SubmitForumThreadPanel extends Panel { public ForumForm(String id) { super(id); - final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback"); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); - final IModel subject = new Model<>(); + final IModel subject = new Model<>(); final FormComponent contentArea = new TextArea<>("content", new Model()).setRequired(true); add(contentArea); @@ -49,22 +47,32 @@ public class SubmitForumThreadPanel extends Panel { final FileUploadField upload = new FileUploadField("attachment"); add(upload); - add(new AjaxFallbackButton("postLink", this) { - @Override - protected void onError(Optional target) { - target.ifPresent(t -> t.add(feedbackPanel)); - } - @Override - protected void onSubmit(Optional target) { - String subjectString = subject.getObject(); - Set attachments = upload.getFileUploads().stream() + add( + new AjaxFallbackButton("postLink", this) { + @Override + protected void onError(Optional target) { + target.ifPresent(t -> t.add(feedbackPanel)); + } + + @Override + protected void onSubmit(Optional target) { + String subjectString = subject.getObject(); + Set attachments = upload + .getFileUploads() + .stream() .map(WicketFileUpload::from) .map(Attachment::newUpload) .collect(Collectors.toSet()); - A thread = forum.createThread(SciProSession.get().getUser(), subjectString, contentArea.getModelObject(), attachments); - onThreadCreated(thread); + A thread = forum.createThread( + SciProSession.get().getUser(), + subjectString, + contentArea.getModelObject(), + attachments + ); + onThreadCreated(thread); + } } - }); + ); add(new RequiredTextField<>("subject", subject)); } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanel.java index 908c096695..482b3e601c 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.forum.panels.threaded; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.forum.BasicForumService; @@ -7,8 +8,6 @@ import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.forum.panels.AbstractReadStatePanel; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - /** * @author : emil-siv * Date: 2013-07-01 @@ -34,6 +33,5 @@ public class ThreadReadStatePanel extends AbstractReadStatePanel { protected void onFlagClick(final AjaxRequestTarget target) { boolean read = isRead(); basicForumService.setThreadRead(SciProSession.get().getUser(), model.getObject(), !read); - } } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanel.java index 60cf3de2a1..02a9d00bd5 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.io.Serializable; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -17,42 +21,58 @@ import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; -import java.io.Serializable; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - public class ThreadsOverviewPanel extends Panel { - public ThreadsOverviewPanel(final String id, final IModel> model, final Discussable discussable, final ThreadLinkSupplier threadLinkSupplier) { - super(id, model); - add(new ListView<>("threads", model) { - @Override - protected void populateItem(final ListItem item) { - final IModel discussion = discussable.discussion(item.getModel()); - item.add(new ThreadReadStatePanel("readState", discussion)); - item.add(new WebMarkupContainer("attachmentIcon") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(discussion.getObject().hasAttachments()); - } - }); - item.add(new ThreadTitleColumn<>("threadTitle", discussion, item.getModel(), threadLinkSupplier)); - item.add(new Label("replies", discussion.map(ForumThread::getPostCount))); - item.add(new LastPostColumn("lastPost", discussion)); + public ThreadsOverviewPanel( + final String id, + final IModel> model, + final Discussable discussable, + final ThreadLinkSupplier threadLinkSupplier + ) { + super(id, model); + add( + new ListView<>("threads", model) { + @Override + protected void populateItem(final ListItem item) { + final IModel discussion = discussable.discussion(item.getModel()); + item.add(new ThreadReadStatePanel("readState", discussion)); + item.add( + new WebMarkupContainer("attachmentIcon") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(discussion.getObject().hasAttachments()); + } + } + ); + item.add(new ThreadTitleColumn<>("threadTitle", discussion, item.getModel(), threadLinkSupplier)); + item.add(new Label("replies", discussion.map(ForumThread::getPostCount))); + item.add(new LastPostColumn("lastPost", discussion)); + } } - }); + ); } private static class ThreadTitleColumn extends WebMarkupContainer { - public ThreadTitleColumn(final String id, final IModel thread, final IModel model, final ThreadLinkSupplier threadLinkSupplier) { + + public ThreadTitleColumn( + final String id, + final IModel thread, + final IModel model, + final ThreadLinkSupplier threadLinkSupplier + ) { super(id); final BookmarkablePageLink threadLink = threadLinkSupplier.newThreadLink("threadLink", model); threadLink.setBody(LambdaModel.of(thread, ForumThread::getSubject, ForumThread::setSubject)); add(threadLink); add(new Label("createdBy", thread.map(ForumThread::getCreatedBy).map(User::getFullName).orElse("SciPro"))); - add(new DateLabel("dateCreated", LambdaModel.of(thread, ForumThread::getDateCreated, ForumThread::setDateCreated), DateStyle.DATETIME)); + add( + new DateLabel( + "dateCreated", + LambdaModel.of(thread, ForumThread::getDateCreated, ForumThread::setDateCreated), + DateStyle.DATETIME + ) + ); } } @@ -61,25 +81,39 @@ public class ThreadsOverviewPanel extends Panel { } private static class LastPostColumn extends WebMarkupContainer { + public LastPostColumn(String id, final IModel model) { super(id); IModel postModel = getLastPost(model); - add(new UserLinkPanel("postedBy", LambdaModel.of(postModel, ForumPost::getPostedBy, ForumPost::setPostedBy))); - add(new WebMarkupContainer("postedBySystem") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(postModel.getObject().getPostedBy() == null); + add( + new UserLinkPanel("postedBy", LambdaModel.of(postModel, ForumPost::getPostedBy, ForumPost::setPostedBy)) + ); + add( + new WebMarkupContainer("postedBySystem") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(postModel.getObject().getPostedBy() == null); + } } - }); - add(new DateLabel("lastPostDate", LambdaModel.of(postModel, ForumPost::getDateCreated, ForumPost::setDateCreated), DateStyle.DATETIME)); + ); + add( + new DateLabel( + "lastPostDate", + LambdaModel.of(postModel, ForumPost::getDateCreated, ForumPost::setDateCreated), + DateStyle.DATETIME + ) + ); } private IModel getLastPost(final IModel model) { return new LoadableDetachableModel<>() { @Override protected ForumPost load() { - return Collections.max(model.getObject().getPosts(), Comparator.comparing(ForumPost::getDateCreated).thenComparing(ForumPost::getId)); + return Collections.max( + model.getObject().getPosts(), + Comparator.comparing(ForumPost::getDateCreated).thenComparing(ForumPost::getId) + ); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanel.java index 9709914a25..9c62f77122 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -14,9 +16,6 @@ import se.su.dsv.scipro.forum.ForumThread; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.session.SciProSession; -import java.util.Comparator; -import java.util.List; - public class ViewForumThreadPanel extends GenericPanel { private final ForumThread forumThread; @@ -55,14 +54,14 @@ public class ViewForumThreadPanel extends GenericPanel { } private void addPostList() { - - wrapper.add(new ListView<>(POST_LIST, new PostProvider()) { - - @Override - protected void populateItem(ListItem item) { - item.add(new ForumPostPanel(POST, item.getModel())); + wrapper.add( + new ListView<>(POST_LIST, new PostProvider()) { + @Override + protected void populateItem(ListItem item) { + item.add(new ForumPostPanel(POST, item.getModel())); + } } - }); + ); } private void addReplyButtons() { diff --git a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanel.java b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanel.java index 29c94b9e37..6613c3a397 100644 --- a/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanel.java @@ -11,9 +11,15 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.util.PageParameterKeys; public class ViewProjectForumThreadPanel extends ViewForumThreadPanel { + private final IModel projectModel; - public ViewProjectForumThreadPanel(final String id, final IModel model, final se.su.dsv.scipro.forum.ForumThread forumThread, final IModel projectModel) { + public ViewProjectForumThreadPanel( + final String id, + final IModel model, + final se.su.dsv.scipro.forum.ForumThread forumThread, + final IModel projectModel + ) { super(id, model, forumThread); this.projectModel = projectModel; } diff --git a/view/src/main/java/se/su/dsv/scipro/gdpr/AdminGDPRPage.java b/view/src/main/java/se/su/dsv/scipro/gdpr/AdminGDPRPage.java index 6781a555e5..80b08026ab 100644 --- a/view/src/main/java/se/su/dsv/scipro/gdpr/AdminGDPRPage.java +++ b/view/src/main/java/se/su/dsv/scipro/gdpr/AdminGDPRPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.gdpr; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.model.IModel; @@ -12,13 +13,12 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - @Authorization(authorizedRoles = Roles.SYSADMIN) public class AdminGDPRPage extends AbstractAdminSystemPage { @Inject private UserService userService; + @Inject private Reporter reporter; @@ -44,11 +44,13 @@ public class AdminGDPRPage extends AbstractAdminSystemPage { downloadReport.setOutputMarkupPlaceholderTag(true); add(downloadReport); - add(new AuthorAutoComplete("author", this.userModel) { - @Override - protected void action(final AjaxRequestTarget target, final User object) { - target.add(downloadReport); + add( + new AuthorAutoComplete("author", this.userModel) { + @Override + protected void action(final AjaxRequestTarget target, final User object) { + target.add(downloadReport); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRReportResourceReference.java b/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRReportResourceReference.java index 269ad8f59e..bdc1e9f924 100644 --- a/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRReportResourceReference.java +++ b/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRReportResourceReference.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.gdpr; +import jakarta.inject.Inject; +import java.util.Collection; +import java.util.EnumSet; +import java.util.Optional; +import java.util.Set; import org.apache.wicket.injection.Injector; import org.apache.wicket.request.Request; import org.apache.wicket.request.http.WebRequest; @@ -12,19 +17,15 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserSearchService; -import jakarta.inject.Inject; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Optional; -import java.util.Set; - public class GDPRReportResourceReference extends ResourceReference { + private static final String GDPR_ENTITLEMENT = "urn:mace:swami.se:gmai:dsv-user:gdpr"; private static final ResourceResponse BAD_REQUEST = new ResourceResponse(); private static final ResourceResponse NO_CONTENT = new ResourceResponse(); private static final ResourceResponse CONFLICT = new ResourceResponse(); private static final ResourceResponse UNAUTHORIZED = new ResourceResponse(); + static { BAD_REQUEST.setError(400); NO_CONTENT.setError(204); @@ -34,8 +35,10 @@ public class GDPRReportResourceReference extends ResourceReference { @Inject private Reporter reporter; + @Inject private OAuthService oAuthService; + @Inject private UserSearchService userSearchService; @@ -79,10 +82,11 @@ public class GDPRReportResourceReference extends ResourceReference { return UNAUTHORIZED; } - final String identity = attributes.getRequest() - .getQueryParameters() - .getParameterValue("identity") - .toOptionalString(); + final String identity = attributes + .getRequest() + .getQueryParameters() + .getParameterValue("identity") + .toOptionalString(); if (identity == null) { return BAD_REQUEST; } @@ -90,11 +94,9 @@ public class GDPRReportResourceReference extends ResourceReference { final Collection users = userSearchService.search(identity, EnumSet.allOf(Roles.class), 2); if (users.isEmpty()) { return NO_CONTENT; - } - else if (users.size() > 1) { + } else if (users.size() > 1) { return CONFLICT; - } - else { + } else { return respondWithUser(users.iterator().next()); } } diff --git a/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRResource.java b/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRResource.java index fb0f982c56..8c470eec31 100644 --- a/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRResource.java +++ b/view/src/main/java/se/su/dsv/scipro/gdpr/GDPRResource.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.gdpr; -import org.apache.wicket.request.resource.AbstractResource; -import org.apache.wicket.request.resource.ContentDisposition; -import se.su.dsv.scipro.system.User; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import org.apache.wicket.request.resource.AbstractResource; +import org.apache.wicket.request.resource.ContentDisposition; +import se.su.dsv.scipro.system.User; public abstract class GDPRResource extends AbstractResource { + protected final Reporter reporter; public GDPRResource(final Reporter reporter) { @@ -22,17 +22,18 @@ public abstract class GDPRResource extends AbstractResource { resourceResponse.setContentLength(Files.size(reportArchive)); resourceResponse.setContentDisposition(ContentDisposition.ATTACHMENT); resourceResponse.setFileName("gdpr-report.zip"); - resourceResponse.setWriteCallback(new WriteCallback() { - @Override - public void writeData(final Attributes attributes) throws IOException { - try { - Files.copy(reportArchive, attributes.getResponse().getOutputStream()); - } - finally { - Files.deleteIfExists(reportArchive); + resourceResponse.setWriteCallback( + new WriteCallback() { + @Override + public void writeData(final Attributes attributes) throws IOException { + try { + Files.copy(reportArchive, attributes.getResponse().getOutputStream()); + } finally { + Files.deleteIfExists(reportArchive); + } } } - }); + ); return resourceResponse; } catch (IOException e) { throw new RuntimeException(e); diff --git a/view/src/main/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPage.java index 37f2110139..0e0aa081f6 100755 --- a/view/src/main/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.generalsystemsettings; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.markup.html.form.*; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; @@ -12,10 +14,7 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.SystemModule; -import jakarta.inject.Inject; -import java.util.Arrays; - -@Authorization(authorizedRoles = { Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class AdminGeneralSettingsPage extends AbstractAdminSystemPage { static final String SETTINGS_FORM = "generalSettings"; @@ -26,8 +25,8 @@ public class AdminGeneralSettingsPage extends AbstractAdminSystemPage { private GeneralSystemSettingsService settingsService; public AdminGeneralSettingsPage() { - add(new GeneralSystemSettingsForm(SETTINGS_FORM, getSettingsModel())); - } + add(new GeneralSystemSettingsForm(SETTINGS_FORM, getSettingsModel())); + } private IModel getSettingsModel() { return new LoadableDetachableModel<>() { @@ -39,29 +38,184 @@ public class AdminGeneralSettingsPage extends AbstractAdminSystemPage { } private final class GeneralSystemSettingsForm extends Form { + private GeneralSystemSettingsForm(String id, final IModel model) { super(id, model); - add(new RequiredTextField<>("mailFromName", LambdaModel.of(model, GeneralSystemSettings::getMailFromName, GeneralSystemSettings::setMailFromName), String.class)); - add(new RequiredTextField<>("systemFromMail", LambdaModel.of(model, GeneralSystemSettings::getSystemFromMail, GeneralSystemSettings::setSystemFromMail), String.class)); - add(new RequiredTextField<>("smtpServer", LambdaModel.of(model, GeneralSystemSettings::getSmtpServer, GeneralSystemSettings::setSmtpServer), String.class)); - add(new RequiredTextField<>("sciproURL", LambdaModel.of(model, GeneralSystemSettings::getSciproURL, GeneralSystemSettings::setSciproURL), String.class)); - add(new TextField<>("thesisSupportMail", LambdaModel.of(model, GeneralSystemSettings::getThesisSupportMail, GeneralSystemSettings::setThesisSupportMail)) - .add(EmailAddressValidator.getInstance())); - add(new TextField<>("reviewerSupportMail", LambdaModel.of(model, GeneralSystemSettings::getReviewerSupportMail, GeneralSystemSettings::setReviewerSupportMail)) - .add(EmailAddressValidator.getInstance())); - add(new TextField<>("matchResponsibleMail", LambdaModel.of(model, GeneralSystemSettings::getMatchResponsibleMail, GeneralSystemSettings::setMatchResponsibleMail)) - .add(EmailAddressValidator.getInstance())); - add(new CheckBox("mailNotifications", LambdaModel.of(model, GeneralSystemSettings::isMailNotifications, GeneralSystemSettings::setMailNotifications)).setOutputMarkupId(true)); - add(new CheckBox("showSingleSignOn", LambdaModel.of(model, GeneralSystemSettings::isShowSingleSignOn, GeneralSystemSettings::setShowSingleSignOn)).setOutputMarkupId(true)); - add(new ListField<>(ALARM_MAILS, LambdaModel.of(model, GeneralSystemSettings::getAlarmMails, GeneralSystemSettings::setAlarmMails), null)); - add(new ListField<>(SUPERVISOR_CHANGE_MAILS, LambdaModel.of(model, GeneralSystemSettings::getSupervisorChangeMails, GeneralSystemSettings::setSupervisorChangeMails), null)); - add(new TextField<>("daisyProfileLinkBaseURL", LambdaModel.of(model, GeneralSystemSettings::getDaisyProfileLinkBaseURL, GeneralSystemSettings::setDaisyProfileLinkBaseURL), String.class)); - add(new TextField<>("daisySelectResearchAreaURL", LambdaModel.of(model, GeneralSystemSettings::getDaisySelectResearchAreaURL, GeneralSystemSettings::setDaisySelectResearchAreaURL), String.class)); - add(new TextField<>("externalRoomBookingURL", LambdaModel.of(model, GeneralSystemSettings::getExternalRoomBookingURL, GeneralSystemSettings::setExternalRoomBookingURL))); - add(new TextField<>("externalGettingStartedWithIdeaURL", LambdaModel.of(model, GeneralSystemSettings::getExternalGettingStartedWithIdeaURL, GeneralSystemSettings::setExternalGettingStartedWithIdeaURL))); - add(new TextField<>("externalGradingURL", LambdaModel.of(model, GeneralSystemSettings::getExternalGradingURL, GeneralSystemSettings::setExternalGradingURL), String.class)); - add(new BootstrapCheckBoxMultipleChoice<>("systemModules", model.map(GeneralSystemSettings::getSystemModules), Arrays.asList(SystemModule.values()), new EnumChoiceRenderer<>(this))); - add(new TextField<>("activeProjectIdeaSupportMail", LambdaModel.of(model, GeneralSystemSettings::getActiveProjectIdeaSupportMail, GeneralSystemSettings::setActiveProjectIdeaSupportMail))); + add( + new RequiredTextField<>( + "mailFromName", + LambdaModel.of( + model, + GeneralSystemSettings::getMailFromName, + GeneralSystemSettings::setMailFromName + ), + String.class + ) + ); + add( + new RequiredTextField<>( + "systemFromMail", + LambdaModel.of( + model, + GeneralSystemSettings::getSystemFromMail, + GeneralSystemSettings::setSystemFromMail + ), + String.class + ) + ); + add( + new RequiredTextField<>( + "smtpServer", + LambdaModel.of(model, GeneralSystemSettings::getSmtpServer, GeneralSystemSettings::setSmtpServer), + String.class + ) + ); + add( + new RequiredTextField<>( + "sciproURL", + LambdaModel.of(model, GeneralSystemSettings::getSciproURL, GeneralSystemSettings::setSciproURL), + String.class + ) + ); + add( + new TextField<>( + "thesisSupportMail", + LambdaModel.of( + model, + GeneralSystemSettings::getThesisSupportMail, + GeneralSystemSettings::setThesisSupportMail + ) + ).add(EmailAddressValidator.getInstance()) + ); + add( + new TextField<>( + "reviewerSupportMail", + LambdaModel.of( + model, + GeneralSystemSettings::getReviewerSupportMail, + GeneralSystemSettings::setReviewerSupportMail + ) + ).add(EmailAddressValidator.getInstance()) + ); + add( + new TextField<>( + "matchResponsibleMail", + LambdaModel.of( + model, + GeneralSystemSettings::getMatchResponsibleMail, + GeneralSystemSettings::setMatchResponsibleMail + ) + ).add(EmailAddressValidator.getInstance()) + ); + add( + new CheckBox( + "mailNotifications", + LambdaModel.of( + model, + GeneralSystemSettings::isMailNotifications, + GeneralSystemSettings::setMailNotifications + ) + ).setOutputMarkupId(true) + ); + add( + new CheckBox( + "showSingleSignOn", + LambdaModel.of( + model, + GeneralSystemSettings::isShowSingleSignOn, + GeneralSystemSettings::setShowSingleSignOn + ) + ).setOutputMarkupId(true) + ); + add( + new ListField<>( + ALARM_MAILS, + LambdaModel.of(model, GeneralSystemSettings::getAlarmMails, GeneralSystemSettings::setAlarmMails), + null + ) + ); + add( + new ListField<>( + SUPERVISOR_CHANGE_MAILS, + LambdaModel.of( + model, + GeneralSystemSettings::getSupervisorChangeMails, + GeneralSystemSettings::setSupervisorChangeMails + ), + null + ) + ); + add( + new TextField<>( + "daisyProfileLinkBaseURL", + LambdaModel.of( + model, + GeneralSystemSettings::getDaisyProfileLinkBaseURL, + GeneralSystemSettings::setDaisyProfileLinkBaseURL + ), + String.class + ) + ); + add( + new TextField<>( + "daisySelectResearchAreaURL", + LambdaModel.of( + model, + GeneralSystemSettings::getDaisySelectResearchAreaURL, + GeneralSystemSettings::setDaisySelectResearchAreaURL + ), + String.class + ) + ); + add( + new TextField<>( + "externalRoomBookingURL", + LambdaModel.of( + model, + GeneralSystemSettings::getExternalRoomBookingURL, + GeneralSystemSettings::setExternalRoomBookingURL + ) + ) + ); + add( + new TextField<>( + "externalGettingStartedWithIdeaURL", + LambdaModel.of( + model, + GeneralSystemSettings::getExternalGettingStartedWithIdeaURL, + GeneralSystemSettings::setExternalGettingStartedWithIdeaURL + ) + ) + ); + add( + new TextField<>( + "externalGradingURL", + LambdaModel.of( + model, + GeneralSystemSettings::getExternalGradingURL, + GeneralSystemSettings::setExternalGradingURL + ), + String.class + ) + ); + add( + new BootstrapCheckBoxMultipleChoice<>( + "systemModules", + model.map(GeneralSystemSettings::getSystemModules), + Arrays.asList(SystemModule.values()), + new EnumChoiceRenderer<>(this) + ) + ); + add( + new TextField<>( + "activeProjectIdeaSupportMail", + LambdaModel.of( + model, + GeneralSystemSettings::getActiveProjectIdeaSupportMail, + GeneralSystemSettings::setActiveProjectIdeaSupportMail + ) + ) + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/grading/AbstractExaminationsPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/AbstractExaminationsPanel.java index f24d065eb0..df49723836 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/AbstractExaminationsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/AbstractExaminationsPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -30,55 +33,55 @@ import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - abstract class AbstractExaminationsPanel extends GenericPanel { - private static final SeminarParticipationGradingRequirements NO_REQUIREMENTS - = new SeminarParticipationGradingRequirements(new Requirement(0, 0), new Requirement(0, 0)); + private static final SeminarParticipationGradingRequirements NO_REQUIREMENTS = + new SeminarParticipationGradingRequirements(new Requirement(0, 0), new Requirement(0, 0)); @Inject private GradingService gradingService; + @Inject private FinalSeminarService finalSeminarService; private final IModel projectModel; public AbstractExaminationsPanel( - final String id, - final IModel projectModel, - final IModel userModel, - final IModel> examinations, - final IModel suggestedReportDate) - { + final String id, + final IModel projectModel, + final IModel userModel, + final IModel> examinations, + final IModel suggestedReportDate + ) { super(id, userModel); this.projectModel = projectModel; - add(new ListView<>("examinations", examinations) { - { - setReuseItems(true); - } + add( + new ListView<>("examinations", examinations) { + { + setReuseItems(true); + } - @Override - protected void populateItem(final ListItem item) { - item.add(new ReportingForm("examination", item.getModel(), userModel, suggestedReportDate)); + @Override + protected void populateItem(final ListItem item) { + item.add(new ReportingForm("examination", item.getModel(), userModel, suggestedReportDate)); + } } - }); + ); } private class ReportingForm extends StatelessForm { + private final IModel userModel; private final IModel gradeModel = new StatelessModel<>(); private final IModel reportedModel = new Model<>(); public ReportingForm( - final String id, - final IModel examinationModel, - final IModel userModel, - final IModel suggestedReportDate) - { + final String id, + final IModel examinationModel, + final IModel userModel, + final IModel suggestedReportDate + ) { super(id, examinationModel); this.userModel = userModel; this.reportedModel.setObject(suggestedReportDate.getObject()); @@ -90,51 +93,61 @@ abstract class AbstractExaminationsPanel extends GenericPanel { @Override protected Either> load() { return gradingService.getResult( - getSession().getMetaData(OAuth.TOKEN), - projectModel.getObject().getIdentifier(), - userModel.getObject().getIdentifier(), - examinationModel.getObject().id()); + getSession().getMetaData(OAuth.TOKEN), + projectModel.getObject().getIdentifier(), + userModel.getObject().getIdentifier(), + examinationModel.getObject().id() + ); } }; - final IModel getGradeErrorModel = getResultModel.map(either -> either.fold(x -> x, r -> null)); - queue(new EnumLabel<>("getGradeError", getGradeErrorModel) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject() != null); + final IModel getGradeErrorModel = getResultModel.map(either -> either.fold(x -> x, r -> null) + ); + queue( + new EnumLabel<>("getGradeError", getGradeErrorModel) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject() != null); + } } - }); + ); - queue(new WebMarkupContainer("allowedToGrade") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getResultModel.getObject().isRight()); + queue( + new WebMarkupContainer("allowedToGrade") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getResultModel.getObject().isRight()); + } } - }); + ); final IModel resultModel = getResultModel.map(e -> e.fold(error -> null, x -> x.orElse(null))); - queue(new WebMarkupContainer("resultContainer") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(resultModel.getObject() != null); + queue( + new WebMarkupContainer("resultContainer") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(resultModel.getObject() != null); + } } - }); + ); queue(new Label("examinationName1", examinationModel.map(Examination::name).map(Name::english))); queue(new Label("points", examinationModel.map(Examination::points))); queue(new Label("letter", resultModel.map(Result::letter))); queue(new Label("reported", resultModel.map(Result::reported))); - queue(new WebMarkupContainer("reportingContainer") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(resultModel.getObject() == null); + queue( + new WebMarkupContainer("reportingContainer") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(resultModel.getObject() == null); + } } - }); + ); queue(new Label("examinationName2", examinationModel.map(Examination::name).map(Name::english))); queue(new Label("points2", examinationModel.map(Examination::points))); final IModel> grades = examinationModel.map(Examination::grades); @@ -145,16 +158,14 @@ abstract class AbstractExaminationsPanel extends GenericPanel { } }; final DropDownChoice gradeField = new DropDownChoice<>( - "gradeField", - gradeModel, - passing, - new LambdaChoiceRenderer<>(Grade::letter, Grade::letter)); + "gradeField", + gradeModel, + passing, + new LambdaChoiceRenderer<>(Grade::letter, Grade::letter) + ); gradeField.setRequired(true); queue(gradeField); - final TextField reportedField = new TextField<>( - "reportedField", - reportedModel, - LocalDate.class); + final TextField reportedField = new TextField<>("reportedField", reportedModel, LocalDate.class); reportedField.setRequired(true); final LocalDate projectStarted = projectModel.getObject().getStartDate(); reportedField.add(new BootstrapDatePicker(projectStarted, LocalDate.now())); @@ -163,24 +174,29 @@ abstract class AbstractExaminationsPanel extends GenericPanel { final Button submit = new Button("submit"); queue(submit); - IModel seminarParticipationGradingRequirements - = LoadableDetachableModel.of(this::getSeminarParticipationGradingRequirements); + IModel seminarParticipationGradingRequirements = + LoadableDetachableModel.of(this::getSeminarParticipationGradingRequirements); - final Label missingSeminarRequirements = new Label("missing_seminar_participation", - new StringResourceModel( - "seminar_participation_grading_requirement_not_fulfilled", - seminarParticipationGradingRequirements)); + final Label missingSeminarRequirements = new Label( + "missing_seminar_participation", + new StringResourceModel( + "seminar_participation_grading_requirement_not_fulfilled", + seminarParticipationGradingRequirements + ) + ); missingSeminarRequirements.setVisible(!seminarParticipationGradingRequirements.getObject().isFulfilled()); missingSeminarRequirements.setEscapeModelStrings(false); queue(missingSeminarRequirements); - queue(new AjaxLink<>("ignore_seminar_participation_requirement") { - @Override - public void onClick(AjaxRequestTarget target) { - submit.setVisible(true); - missingSeminarRequirements.setVisible(false); - target.add(ReportingForm.this); + queue( + new AjaxLink<>("ignore_seminar_participation_requirement") { + @Override + public void onClick(AjaxRequestTarget target) { + submit.setVisible(true); + missingSeminarRequirements.setVisible(false); + target.add(ReportingForm.this); + } } - }); + ); if (!seminarParticipationGradingRequirements.getObject().isFulfilled()) { submit.setVisible(false); } @@ -189,11 +205,12 @@ abstract class AbstractExaminationsPanel extends GenericPanel { @Override protected void onSubmit() { reportGrade( - projectModel.getObject(), - userModel.getObject(), - getModelObject(), - gradeModel.getObject().letter(), - reportedModel.getObject()); + projectModel.getObject(), + userModel.getObject(), + getModelObject(), + gradeModel.getObject().letter(), + reportedModel.getObject() + ); } private SeminarParticipationGradingRequirements getSeminarParticipationGradingRequirements() { @@ -204,27 +221,31 @@ abstract class AbstractExaminationsPanel extends GenericPanel { if (!examination.hasManyPassingGrades()) { return NO_REQUIREMENTS; } - final long completedOppositions = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), user) - .stream() - .filter(FinalSeminarOpposition::isApproved) - .count(); - final long completedParticipations = finalSeminarService.findUserParticipating(project, user) - .stream() - .filter(FinalSeminarActiveParticipation::isApproved) - .count(); + final long completedOppositions = finalSeminarService + .findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), user) + .stream() + .filter(FinalSeminarOpposition::isApproved) + .count(); + final long completedParticipations = finalSeminarService + .findUserParticipating(project, user) + .stream() + .filter(FinalSeminarActiveParticipation::isApproved) + .count(); final ProjectTypeSettings projectTypeSettings = project.getProjectType().getProjectTypeSettings(); final int requiredOppositions = projectTypeSettings.getMinOppositionsToBeGraded(); final int requiredActiveParticipations = projectTypeSettings.getMinActiveParticipationsToBeGraded(); return new SeminarParticipationGradingRequirements( - new Requirement(requiredOppositions, completedOppositions), - new Requirement(requiredActiveParticipations, completedParticipations)); + new Requirement(requiredOppositions, completedOppositions), + new Requirement(requiredActiveParticipations, completedParticipations) + ); } } protected abstract void reportGrade( - final Project project, - final User user, - final Examination examination, - final String letter, - final LocalDate reported); + final Project project, + final User user, + final Examination examination, + final String letter, + final LocalDate reported + ); } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/CriteriaPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/CriteriaPanel.java index 011cb74f9f..a3fddc9517 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/CriteriaPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/CriteriaPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.util.List; +import java.util.Objects; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -41,10 +44,6 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Objects; - public class CriteriaPanel extends GenericPanel { public static final String CRITERIA = "criteria"; @@ -55,136 +54,173 @@ public class CriteriaPanel extends GenericPanel { public CriteriaPanel(String id, IModel model) { super(id, model); - IModel language = model - .map(SupervisorGradingReport::getProject) - .map(Project::getReportLanguage); + IModel language = model.map(SupervisorGradingReport::getProject).map(Project::getReportLanguage); IModel author = model.map(SupervisorGradingReport::getUser); - add(new ListView<>(CRITERIA, model.map(SupervisorGradingReport::getIndividualCriteria)) { - { - setReuseItems(true); - } + add( + new ListView<>(CRITERIA, model.map(SupervisorGradingReport::getIndividualCriteria)) { + { + setReuseItems(true); + } - @Override - protected void populateItem(final ListItem item) { - final WebMarkupContainer grading = new WebMarkupContainer("grading"); - grading.setOutputMarkupId(true); - item.add(grading); - item.add(new Label(TITLE, item.getModel().combineWith(language, GradingCriterion::getTitle))); - grading.add(new Label(MAX_POINTS, - new StringResourceModel( + @Override + protected void populateItem(final ListItem item) { + final WebMarkupContainer grading = new WebMarkupContainer("grading"); + grading.setOutputMarkupId(true); + item.add(grading); + item.add(new Label(TITLE, item.getModel().combineWith(language, GradingCriterion::getTitle))); + grading.add( + new Label( + MAX_POINTS, + new StringResourceModel( "point_requirement", - item.getModel().map(AbstractGradingCriterion::getPointsRequiredToPass)))); + item.getModel().map(AbstractGradingCriterion::getPointsRequiredToPass) + ) + ) + ); - IModel> gradingCriterionPoints = item.getModel().map(GradingCriterion::getGradingCriterionPoints); - RadioChoice pointsRadioChoice = new BootstrapRadioChoice<>( + IModel> gradingCriterionPoints = item + .getModel() + .map(GradingCriterion::getGradingCriterionPoints); + RadioChoice pointsRadioChoice = new BootstrapRadioChoice<>( POINTS, new GradingCriterionPointsModelConverter(item.getModel()), gradingCriterionPoints, - getPointsRenderer()) - { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!item.getModelObject().isPassFail()); - } - }; - pointsRadioChoice.add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(grading); - } - }); - grading.add(pointsRadioChoice); + getPointsRenderer() + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!item.getModelObject().isPassFail()); + } + }; + pointsRadioChoice.add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(grading); + } + } + ); + grading.add(pointsRadioChoice); - IModel pfModel = new AbstractCheckBoxModel() { - @Override - public boolean isSelected() { - return Objects.equals(item.getModelObject().getPoints(), 1); - } + IModel pfModel = new AbstractCheckBoxModel() { + @Override + public boolean isSelected() { + return Objects.equals(item.getModelObject().getPoints(), 1); + } - @Override - public void select() { - item.getModelObject().setPoints(1); - } + @Override + public void select() { + item.getModelObject().setPoints(1); + } - @Override - public void unselect() { - item.getModelObject().setPoints(null); - } - }; - final CheckBox pf = new CheckBox("pf", pfModel) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(item.getModelObject().isPassFail()); - } - }; - pf.setOutputMarkupId(true); // required for wicket:for - grading.add(pf); - grading.add(new Label("pfCriteria", item.getModel().combineWith(language, (gc, lang) -> gc.getGradingCriterionPoints().get(1).getDescription(lang)))); + @Override + public void unselect() { + item.getModelObject().setPoints(null); + } + }; + final CheckBox pf = new CheckBox("pf", pfModel) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(item.getModelObject().isPassFail()); + } + }; + pf.setOutputMarkupId(true); // required for wicket:for + grading.add(pf); + grading.add( + new Label( + "pfCriteria", + item + .getModel() + .combineWith(language, (gc, lang) -> + gc.getGradingCriterionPoints().get(1).getDescription(lang) + ) + ) + ); - if (item.getModelObject().getFlag() == AbstractGradingCriterion.Flag.OPPOSITION) { - grading.setEnabled(false); + if (item.getModelObject().getFlag() == AbstractGradingCriterion.Flag.OPPOSITION) { + grading.setEnabled(false); + } + item.add( + new AjaxConfirmationLink<>( + "enable", + "Are you sure you want to grade this criteria? It is usually filled in by the seminar supervisor" + ) { + @Override + public void onClick(final AjaxRequestTarget target) { + grading.setEnabled(true); + target.add(grading); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!grading.isEnabled() && isEnabledInHierarchy()); + } + } + ); + item.add(new OppositionFeedbackPanel("opposition", author, item.getModel())); + item.add(new ReflectionFeedbackPanel("reflection", author, item.getModel())); } - item.add(new AjaxConfirmationLink<>("enable", "Are you sure you want to grade this criteria? It is usually filled in by the seminar supervisor") { - @Override - public void onClick(final AjaxRequestTarget target) { - grading.setEnabled(true); - target.add(grading); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!grading.isEnabled() && isEnabledInHierarchy()); - } - }); - item.add(new OppositionFeedbackPanel("opposition", author, item.getModel())); - item.add(new ReflectionFeedbackPanel("reflection", author, item.getModel())); + private IChoiceRenderer getPointsRenderer() { + return new ChoiceRenderer<>() { + @Override + public Object getDisplayValue(GradingCriterionPoint object) { + String description = object.getDescription(language.getObject()); + return ( + object.getPoint().toString() + + " p" + + (description != null && !description.isBlank() ? " - " + description : "") + ); + } + + @Override + public String getIdValue(GradingCriterionPoint object, int index) { + return object.getPoint().toString(); + } + }; + } } - - private IChoiceRenderer getPointsRenderer() { - return new ChoiceRenderer<>() { - @Override - public Object getDisplayValue(GradingCriterionPoint object) { - String description = object.getDescription(language.getObject()); - return object.getPoint().toString() + " p" - + (description != null && !description.isBlank() ? " - " + description : ""); - } - - @Override - public String getIdValue(GradingCriterionPoint object, int index) { - return object.getPoint().toString(); - } - }; - } - }); + ); } private class OppositionFeedbackPanel extends GenericWebMarkupContainer { + @Inject FinalSeminarService finalSeminarService; private final IModel gradingCriterion; private ModalWindowPlus modal; - public OppositionFeedbackPanel(final String id, final IModel author, final IModel gradingCriterion) { + public OppositionFeedbackPanel( + final String id, + final IModel author, + final IModel gradingCriterion + ) { super(id, author); this.gradingCriterion = gradingCriterion; final IModel> authorOppositions = LoadableDetachableModel.of(() -> - finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(CriteriaPanel.this.getModelObject().getProject().getProjectType(), author.getObject())); + finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType( + CriteriaPanel.this.getModelObject().getProject().getProjectType(), + author.getObject() + ) + ); modal = new ModalWindowPlus("modal"); modal.setTitle("Opposition feedback"); add(modal); - add(new AjaxLink("showFeedback") { - @Override - public void onClick(final AjaxRequestTarget target) { - modal.setContent(id -> new OppositionFeedbackList(id, authorOppositions)); - modal.show(target); + add( + new AjaxLink("showFeedback") { + @Override + public void onClick(final AjaxRequestTarget target) { + modal.setContent(id -> new OppositionFeedbackList(id, authorOppositions)); + modal.show(target); + } } - }); + ); } @Override @@ -196,34 +232,61 @@ public class CriteriaPanel extends GenericPanel { @Override protected void onConfigure() { super.onConfigure(); - final boolean isOppositionCriteria = gradingCriterion.getObject().getFlag() == AbstractGradingCriterion.Flag.OPPOSITION; + final boolean isOppositionCriteria = + gradingCriterion.getObject().getFlag() == AbstractGradingCriterion.Flag.OPPOSITION; setVisibilityAllowed(isOppositionCriteria && isEnabledInHierarchy()); } private class OppositionFeedbackList extends Fragment { - public OppositionFeedbackList(final String id, final IModel> authorOppositions) { + + public OppositionFeedbackList( + final String id, + final IModel> authorOppositions + ) { super(id, "oppositionFeedback", OppositionFeedbackPanel.this, authorOppositions); - add(new WebMarkupContainer("noOppositionsRegistered") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(authorOppositions.getObject().isEmpty()); + add( + new WebMarkupContainer("noOppositionsRegistered") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(authorOppositions.getObject().isEmpty()); + } } - }); - add(new ListView<>("list", authorOppositions) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label("project", item.getModel().map(FinalSeminarOpposition::getFinalSeminar).map(FinalSeminar::getProject).map(Project::getTitle))); - item.add(new DateLabel("date", item.getModel().map(FinalSeminarOpposition::getFinalSeminar).map(FinalSeminar::getStartDate))); - item.add(new Label("points", item.getModel().map(FinalSeminarOpposition::getPoints))); - item.add(new Label("feedback", item.getModel().map(FinalSeminarOpposition::getFeedback))); + ); + add( + new ListView<>("list", authorOppositions) { + @Override + protected void populateItem(final ListItem item) { + item.add( + new Label( + "project", + item + .getModel() + .map(FinalSeminarOpposition::getFinalSeminar) + .map(FinalSeminar::getProject) + .map(Project::getTitle) + ) + ); + item.add( + new DateLabel( + "date", + item + .getModel() + .map(FinalSeminarOpposition::getFinalSeminar) + .map(FinalSeminar::getStartDate) + ) + ); + item.add(new Label("points", item.getModel().map(FinalSeminarOpposition::getPoints))); + item.add(new Label("feedback", item.getModel().map(FinalSeminarOpposition::getFeedback))); + } } - }); + ); } } } private static final class GradingCriterionPointsModelConverter implements IModel { + private final IModel criterionIModel; public GradingCriterionPointsModelConverter(IModel criterionIModel) { @@ -238,7 +301,9 @@ public class CriteriaPanel extends GenericPanel { @Override public GradingCriterionPoint getObject() { Integer points = criterionIModel.getObject().getPoints(); - for (GradingCriterionPoint gradingCriterionPoint : criterionIModel.getObject().getGradingCriterionPoints()) { + for (GradingCriterionPoint gradingCriterionPoint : criterionIModel + .getObject() + .getGradingCriterionPoints()) { if (gradingCriterionPoint.getPoint().equals(points)) { return gradingCriterionPoint; } @@ -271,16 +336,18 @@ public class CriteriaPanel extends GenericPanel { return reflectionService.getReflection(project, author.getObject()); }); IModel improvementsNeeded = reflection - .as(Reflection.ImprovementsNeeded.class) - .map(Reflection.ImprovementsNeeded::commentBySupervisor); + .as(Reflection.ImprovementsNeeded.class) + .map(Reflection.ImprovementsNeeded::commentBySupervisor); - add(new MultiLineLabel("improvementsNeeded", improvementsNeeded) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isBlank()); + add( + new MultiLineLabel("improvementsNeeded", improvementsNeeded) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); modal = new LargeModalWindow("modal"); modal.setTitle("Reflection"); @@ -302,7 +369,9 @@ public class CriteriaPanel extends GenericPanel { // Doing it with a completely client-side JavaScript since // the form containing this component gets disabled which // prevents a regular AjaxLink from continuing to work. - response.render(OnEventHeaderItem.forComponent(this, "click", modal.getShowJavascript() + "; return false;")); + response.render( + OnEventHeaderItem.forComponent(this, "click", modal.getShowJavascript() + "; return false;") + ); } }; add(showReflection); @@ -317,7 +386,8 @@ public class CriteriaPanel extends GenericPanel { @Override protected void onConfigure() { super.onConfigure(); - boolean isReflectionCriteria = gradingCriterion.getObject().getFlag() == AbstractGradingCriterion.Flag.REFLECTION; + boolean isReflectionCriteria = + gradingCriterion.getObject().getFlag() == AbstractGradingCriterion.Flag.REFLECTION; setVisibilityAllowed(isReflectionCriteria); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/DataExposedGradingReportPdf.java b/view/src/main/java/se/su/dsv/scipro/grading/DataExposedGradingReportPdf.java index e1fccce6ee..85b90d63fc 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/DataExposedGradingReportPdf.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/DataExposedGradingReportPdf.java @@ -7,12 +7,13 @@ import se.su.dsv.scipro.report.SupervisorGradingReport; import se.su.dsv.scipro.reviewing.RoughDraftApproval; class DataExposedGradingReportPdf extends GradingReportPdfResource { + DataExposedGradingReportPdf( - IModel supervisorGradingReport, - IModel reflection, - IModel roughDraftApproval, - IModel finalThesis) - { + IModel supervisorGradingReport, + IModel reflection, + IModel roughDraftApproval, + IModel finalThesis + ) { super(new SupervisorGradingReportPdf(supervisorGradingReport, reflection, roughDraftApproval, finalThesis)); } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/EventPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/EventPanel.java index 350fe40643..af22bd5d45 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/EventPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/EventPanel.java @@ -8,13 +8,9 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.grading.ExaminerTimelineService.Event; import se.su.dsv.scipro.profile.UserLabel; -public abstract class EventPanel - extends GenericPanel -{ - protected EventPanel( - String id, - IModel model) - { +public abstract class EventPanel extends GenericPanel { + + protected EventPanel(String id, IModel model) { super(id, model); add(new Label("when", model.map(Event::when))); } @@ -25,43 +21,33 @@ public abstract class EventPanel setVisibilityAllowed(getModelObject() != null); } - public static class InitialSubmissionPanel - extends EventPanel - { - public InitialSubmissionPanel( - String id, - IModel model) - { - super(id, model); + public static class InitialSubmissionPanel extends EventPanel { - add(new UserLabel( - "author", - model.map(Event.InitialSubmission::author))); + public InitialSubmissionPanel(String id, IModel model) { + super(id, model); + add(new UserLabel("author", model.map(Event.InitialSubmission::author))); } } public static class RejectedPanel extends EventPanel { + public RejectedPanel(String id, IModel model) { super(id, model); - - add(new MultiLineLabel( - "feedback", - model.map(Event.Rejected::feedback))); + add(new MultiLineLabel("feedback", model.map(Event.Rejected::feedback))); } } public static class ResubmissionPanel extends EventPanel { + public ResubmissionPanel(String id, IModel model) { super(id, model); - add(new UserLabel("author", model.map(Event.Resubmitted::author))); - add(new Label( - "corrections", - model.map(Event.Resubmitted::corrections))); + add(new Label("corrections", model.map(Event.Resubmitted::corrections))); } } public static class ApprovedPanel extends EventPanel { + public ApprovedPanel(String id, IModel model) { super(id, model); } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelinePanel.java b/view/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelinePanel.java index 85906e3c15..20f2e14149 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelinePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/ExaminerTimelinePanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -8,9 +10,6 @@ import org.apache.wicket.model.LoadableDetachableModel; import se.su.dsv.scipro.grading.ExaminerTimelineService.Event; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; -import java.util.List; - public class ExaminerTimelinePanel extends GenericPanel { @Inject @@ -18,32 +17,34 @@ public class ExaminerTimelinePanel extends GenericPanel { public ExaminerTimelinePanel(String id, IModel model) { super(id, model); + IModel> events = LoadableDetachableModel.of(() -> + examinerTimelineService.getTimeline(model.getObject()) + ); - IModel> events = LoadableDetachableModel.of( - () -> examinerTimelineService.getTimeline(model.getObject())); + add( + new ListView<>("events", events) { + @Override + protected void populateItem(ListItem listItem) { + listItem.add( + new EventPanel.InitialSubmissionPanel( + "initial_submission", + listItem.getModel().as(Event.InitialSubmission.class) + ) + ); - add(new ListView<>("events", events) { - @Override - protected void populateItem(ListItem listItem) { - listItem.add(new EventPanel.InitialSubmissionPanel( - "initial_submission", - listItem.getModel().as(Event.InitialSubmission.class))); + listItem.add( + new EventPanel.RejectedPanel("rejected", listItem.getModel().as(Event.Rejected.class)) + ); - listItem.add(new EventPanel.RejectedPanel( - "rejected", - listItem.getModel().as(Event.Rejected.class) - )); + listItem.add( + new EventPanel.ResubmissionPanel("resubmitted", listItem.getModel().as(Event.Resubmitted.class)) + ); - listItem.add(new EventPanel.ResubmissionPanel( - "resubmitted", - listItem.getModel().as(Event.Resubmitted.class))); - - listItem.add(new EventPanel.ApprovedPanel( - "approved", - listItem.getModel().as(Event.Approved.class) - )); + listItem.add( + new EventPanel.ApprovedPanel("approved", listItem.getModel().as(Event.Approved.class)) + ); + } } - }); + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/FillOutReportPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/FillOutReportPanel.java index 05a45ee3ec..95bfd72a34 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/FillOutReportPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/FillOutReportPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.border.Border; @@ -26,11 +30,6 @@ import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Optional; - public class FillOutReportPanel extends Border { public static final String FORM = "form"; @@ -47,7 +46,6 @@ public class FillOutReportPanel extends Border { public FillOutReportPanel(String id, final IModel model) { super(id, model); - ReportForm form = new ReportForm(FORM, model); addToBorder(new ScrollingSaveButtonPanel(SAVE, form)); addToBorder(form); @@ -60,23 +58,31 @@ public class FillOutReportPanel extends Border { public ReportForm(String id, final IModel model) { super(id, model); add(new ComponentFeedbackPanel(FEEDBACK_PANEL, this)); - IModel language = model - .map(OppositionReport::getLanguage); - add(new ListView<>(GRADING_CRITERIA, model.map(OppositionReport::getCriteria)) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(TITLE, item.getModel().combineWith(language, Criterion::getTitle))); - item.add(new Label(DESCRIPTION, item.getModel().combineWith(language, Criterion::getDescription))); - TextArea textArea = new TextArea<>(FEEDBACK, LambdaModel.of(item.getModel(), Criterion::getFeedback, Criterion::setFeedback)); - textArea.add(new AutoSavingBehaviour() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - reportService.save(model.getObject()); - } - }); - item.add(textArea); + IModel language = model.map(OppositionReport::getLanguage); + add( + new ListView<>(GRADING_CRITERIA, model.map(OppositionReport::getCriteria)) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(TITLE, item.getModel().combineWith(language, Criterion::getTitle))); + item.add( + new Label(DESCRIPTION, item.getModel().combineWith(language, Criterion::getDescription)) + ); + TextArea textArea = new TextArea<>( + FEEDBACK, + LambdaModel.of(item.getModel(), Criterion::getFeedback, Criterion::setFeedback) + ); + textArea.add( + new AutoSavingBehaviour() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + reportService.save(model.getObject()); + } + } + ); + item.add(textArea); + } } - }); + ); attachment = new FileUploadField("uploadAttachment") { @Override @@ -86,7 +92,12 @@ public class FillOutReportPanel extends Border { } }; add(attachment); - add(new ViewAttachmentPanel("viewAttachment", getModel().map(AttachmentReport::getAttachment).map(FileReference::getFileDescription))); + add( + new ViewAttachmentPanel( + "viewAttachment", + getModel().map(AttachmentReport::getAttachment).map(FileReference::getFileDescription) + ) + ); add(new DeleteAttachmentLink("deleteAttachment", getModel())); SubmitLink finishLink = new SubmitLink(SUBMIT) { @@ -102,11 +113,12 @@ public class FillOutReportPanel extends Border { @Override protected CharSequence getTriggerJavaScript() { - String confirmationMessage = getString("confirmFinish") - .replace("'", "\\\\'"); - return String.format("if (confirm('%s')) { %s } else { event.preventDefault() }", - confirmationMessage, - super.getTriggerJavaScript()); + String confirmationMessage = getString("confirmFinish").replace("'", "\\\\'"); + return String.format( + "if (confirm('%s')) { %s } else { event.preventDefault() }", + confirmationMessage, + super.getTriggerJavaScript() + ); } }; add(finishLink); diff --git a/view/src/main/java/se/su/dsv/scipro/grading/GradingBasisPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/GradingBasisPanel.java index 52c9adeca8..154c008d27 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/GradingBasisPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/GradingBasisPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Objects; import org.apache.wicket.extensions.model.AbstractCheckBoxModel; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -27,12 +32,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.report.GradingCriterion; import se.su.dsv.scipro.report.GradingReportService; -import jakarta.inject.Inject; -import java.time.LocalTime; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Objects; - public class GradingBasisPanel extends GenericPanel { @Inject @@ -40,17 +39,17 @@ public class GradingBasisPanel extends GenericPanel { public GradingBasisPanel(String id, IModel projectModel) { super(id, projectModel); - - IModel gradingBasis = LoadableDetachableModel.of( - () -> gradingReportService.getGradingBasis(projectModel.getObject())); + IModel gradingBasis = LoadableDetachableModel.of(() -> + gradingReportService.getGradingBasis(projectModel.getObject()) + ); add(new GradingBasisForm("form", gradingBasis)); } private class GradingBasisForm extends Form { + public GradingBasisForm(String id, IModel gradingBasis) { super(id, gradingBasis); - add(new FencedFeedbackPanel("feedback", this)); ListView criterion = new ListView<>("criterion", gradingBasis.map(GradingBasis::criteria)) { @@ -58,18 +57,20 @@ public class GradingBasisPanel extends GenericPanel { protected void populateItem(ListItem item) { IModel criteriaModel = item.getModel().map(Assessment::criterion); item.add(new Label("title", criteriaModel.map(Criterion::title))); - item.add(new Label("point_requirement", - new StringResourceModel( - "point_requirement", - criteriaModel.map(Criterion::minimumPoints)))); + item.add( + new Label( + "point_requirement", + new StringResourceModel("point_requirement", criteriaModel.map(Criterion::minimumPoints)) + ) + ); IModel> requirements = criteriaModel.map(Criterion::requirements); RadioChoice pointsRadioChoice = new BootstrapRadioChoice<>( - "points", - new GradedCriterionModel(item.getModel(), requirements), - requirements, - new LambdaChoiceRenderer<>(GradingBasisForm::fullDescriptionWithPoints, Requirement::points)) - { + "points", + new GradedCriterionModel(item.getModel(), requirements), + requirements, + new LambdaChoiceRenderer<>(GradingBasisForm::fullDescriptionWithPoints, Requirement::points) + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -93,55 +94,80 @@ public class GradingBasisPanel extends GenericPanel { criterion.setReuseItems(true); add(criterion); - IModel> criteriaNotMet = gradingBasis.map(GradingBasis::criteria).map(criteria -> criteria.stream() - .filter(assessment -> Objects.requireNonNullElse( - assessment.getPoints(), - 0) < assessment.criterion().minimumPoints()) - .toList()); + IModel> criteriaNotMet = gradingBasis + .map(GradingBasis::criteria) + .map(criteria -> + criteria + .stream() + .filter( + assessment -> + Objects.requireNonNullElse(assessment.getPoints(), 0) < + assessment.criterion().minimumPoints() + ) + .toList() + ); WebMarkupContainer gradingBasisMissing = new WebMarkupContainer("grading_basis_missing") { @Override protected void onConfigure() { super.onConfigure(); String overallMotivation = gradingBasis.getObject().getOverallMotivation(); - setVisible(!criteriaNotMet.getObject().isEmpty() || overallMotivation == null || overallMotivation.isBlank()); + setVisible( + !criteriaNotMet.getObject().isEmpty() || + overallMotivation == null || + overallMotivation.isBlank() + ); } }; add(gradingBasisMissing); - gradingBasisMissing.add(new AutoHidingListView<>("grading_basis_requirements_not_met", criteriaNotMet) { - @Override - protected void populateItem(ListItem item) { - IModel criterion = item.getModel().map(Assessment::criterion); - item.add(new Label("title", criterion.map(Criterion::title))); - item.add(new Label("given_points", item.getModel().map(Assessment::getPoints).orElse(0))); - item.add(new Label("maximum_points", criterion.map(Criterion::maxPoints))); - item.add(new Label("required_points", criterion.map(Criterion::minimumPoints))); + gradingBasisMissing.add( + new AutoHidingListView<>("grading_basis_requirements_not_met", criteriaNotMet) { + @Override + protected void populateItem(ListItem item) { + IModel criterion = item.getModel().map(Assessment::criterion); + item.add(new Label("title", criterion.map(Criterion::title))); + item.add(new Label("given_points", item.getModel().map(Assessment::getPoints).orElse(0))); + item.add(new Label("maximum_points", criterion.map(Criterion::maxPoints))); + item.add(new Label("required_points", criterion.map(Criterion::minimumPoints))); + } } - }); - gradingBasisMissing.add(new WebMarkupContainer("overall_motivation_missing") { - @Override - protected void onConfigure() { - super.onConfigure(); - String overallMotivation = gradingBasis.getObject().getOverallMotivation(); - setVisible(overallMotivation == null || overallMotivation.isBlank()); + ); + gradingBasisMissing.add( + new WebMarkupContainer("overall_motivation_missing") { + @Override + protected void onConfigure() { + super.onConfigure(); + String overallMotivation = gradingBasis.getObject().getOverallMotivation(); + setVisible(overallMotivation == null || overallMotivation.isBlank()); + } } - }); + ); - IModel overallMotivation = LambdaModel.of(gradingBasis, - GradingBasis::getOverallMotivation, - GradingBasis::setOverallMotivation); + IModel overallMotivation = LambdaModel.of( + gradingBasis, + GradingBasis::getOverallMotivation, + GradingBasis::setOverallMotivation + ); TextArea overallMotivationField = new TextArea<>("overall_motivation", overallMotivation); add(overallMotivationField); - add(new Label("rejection_comment", gradingBasis.map(GradingBasis::rejectionComment)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isBlank()); + add( + new Label("rejection_comment", gradingBasis.map(GradingBasis::rejectionComment)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isBlank()); + } } - }); - IModel rejectionCommentFeedback = LambdaModel.of(gradingBasis, - GradingBasis::getRejectionCommentFeedback, GradingBasis::setRejectionCommentFeedback); - TextArea rejectionCommentFeedbackField = new TextArea<>("rejection_comment_feedback", rejectionCommentFeedback) { + ); + IModel rejectionCommentFeedback = LambdaModel.of( + gradingBasis, + GradingBasis::getRejectionCommentFeedback, + GradingBasis::setRejectionCommentFeedback + ); + TextArea rejectionCommentFeedbackField = new TextArea<>( + "rejection_comment_feedback", + rejectionCommentFeedback + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -189,6 +215,7 @@ public class GradingBasisPanel extends GenericPanel { } private class PassFailCriterionModel extends AbstractCheckBoxModel { + private static final Integer PASS = 1; private static final Integer FAIL = null; @@ -215,6 +242,7 @@ public class GradingBasisPanel extends GenericPanel { } private class GradedCriterionModel implements IModel { + private final IModel assessment; private final IModel> requirements; @@ -226,11 +254,12 @@ public class GradingBasisPanel extends GenericPanel { @Override public Requirement getObject() { Integer givenPoints = assessment.getObject().getPoints(); - return requirements.getObject() - .stream() - .filter(requirement -> Objects.equals(requirement.points(), givenPoints)) - .findAny() - .orElse(null); + return requirements + .getObject() + .stream() + .filter(requirement -> Objects.equals(requirement.points(), givenPoints)) + .findAny() + .orElse(null); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdf.java b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdf.java index c382b69b53..b44d442654 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdf.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdf.java @@ -1,10 +1,9 @@ package se.su.dsv.scipro.grading; -import se.su.dsv.scipro.report.GradingCriterion; - import java.io.Serializable; import java.util.Date; import java.util.List; +import se.su.dsv.scipro.report.GradingCriterion; public interface GradingReportPdf extends Serializable { String getProjectTitle(); diff --git a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdfResource.java b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdfResource.java index 99dc411bfb..114bc4f559 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdfResource.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPdfResource.java @@ -1,32 +1,37 @@ -package se.su.dsv.scipro.grading; - -import net.sf.jasperreports.engine.JRDataSource; -import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; -import org.apache.wicket.model.Model; - -import java.util.Collections; - -public class GradingReportPdfResource extends ReportPdfResource { - - private final GradingReportPdf gradingReportPdf; - - public GradingReportPdfResource(GradingReportPdf gradingReportPdf) { - super(new Model<>()); - this.gradingReportPdf = gradingReportPdf; - } - - @Override - public JRDataSource getReportDataSource() { - return new JRBeanCollectionDataSource(Collections.singleton(gradingReportPdf)); - } - - @Override - protected String getTemplateName() { - return "template.jrxml"; - } - - @Override - public String getFileName() { - return gradingReportPdf.getProjectTypeName() + "_grading_report_" + gradingReportPdf.getAuthorName() + "." + getExtension(); - } -} +package se.su.dsv.scipro.grading; + +import java.util.Collections; +import net.sf.jasperreports.engine.JRDataSource; +import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; +import org.apache.wicket.model.Model; + +public class GradingReportPdfResource extends ReportPdfResource { + + private final GradingReportPdf gradingReportPdf; + + public GradingReportPdfResource(GradingReportPdf gradingReportPdf) { + super(new Model<>()); + this.gradingReportPdf = gradingReportPdf; + } + + @Override + public JRDataSource getReportDataSource() { + return new JRBeanCollectionDataSource(Collections.singleton(gradingReportPdf)); + } + + @Override + protected String getTemplateName() { + return "template.jrxml"; + } + + @Override + public String getFileName() { + return ( + gradingReportPdf.getProjectTypeName() + + "_grading_report_" + + gradingReportPdf.getAuthorName() + + "." + + getExtension() + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPointsPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPointsPanel.java index ad4c49050d..593ee532c5 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPointsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/GradingReportPointsPanel.java @@ -15,9 +15,12 @@ public class GradingReportPointsPanel extends Panel { public static final String POINTS_LABEL = "pointsLabel"; public static final String NO_GRADE_EXPLANATION = "noGradeExplanation"; - public GradingReportPointsPanel(String id, final IModel gradingReportIModel, final GradeCalculator gradeCalculator) { + public GradingReportPointsPanel( + String id, + final IModel gradingReportIModel, + final GradeCalculator gradeCalculator + ) { super(id, gradingReportIModel); - final IModel gradeModel = new LoadableDetachableModel<>() { @Override protected GradingReport.Grade load() { @@ -41,7 +44,6 @@ public class GradingReportPointsPanel extends Panel { }; add(new Label(POINTS_LABEL, points)); - add(new WebMarkupContainer(NO_GRADE_EXPLANATION) - .add(new OppositeVisibility(grade))); + add(new WebMarkupContainer(NO_GRADE_EXPLANATION).add(new OppositeVisibility(grade))); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/IndividualAuthorAssessmentPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/IndividualAuthorAssessmentPanel.java index 6dff147635..6d4ba8e0d6 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/IndividualAuthorAssessmentPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/IndividualAuthorAssessmentPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -26,25 +32,23 @@ import se.su.dsv.scipro.report.GradingReportService; import se.su.dsv.scipro.report.SupervisorGradingReport; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.LocalTime; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; - public class IndividualAuthorAssessmentPanel extends GenericPanel { @Inject private NationalSubjectCategoryService nationalSubjectCategoryService; + @Inject private GradingReportService gradingReportService; + @Inject private GradeCalculatorService gradeCalculatorService; + @Inject private FinalThesisService finalThesisService; + @Inject private FinalSeminarService finalSeminarService; + @Inject private PublicationMetadataService publicationMetadataService; @@ -54,41 +58,61 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { super(id, authorModel); this.projectModel = projectModel; - IModel gradingReport = LoadableDetachableModel.of( - () -> gradingReportService.getSupervisorGradingReport(projectModel.getObject(), authorModel.getObject())); + IModel gradingReport = LoadableDetachableModel.of(() -> + gradingReportService.getSupervisorGradingReport(projectModel.getObject(), authorModel.getObject()) + ); add(new AssessmentForm("form", gradingReport)); IModel> gradingBasisCriterionNotMet = gradingReport.map(gr -> - gr.getProjectCriteria() - .stream() - .filter(Predicate.not(GradingCriterion::meetsMinimumPointRequirement)) - .toList()); + gr + .getProjectCriteria() + .stream() + .filter(Predicate.not(GradingCriterion::meetsMinimumPointRequirement)) + .toList() + ); IModel> individualCriterionNotMet = gradingReport.map(gr -> - gr.getIndividualCriteria() - .stream() - .filter(Predicate.not(GradingCriterion::meetsMinimumPointRequirement)) - .toList()); + gr + .getIndividualCriteria() + .stream() + .filter(Predicate.not(GradingCriterion::meetsMinimumPointRequirement)) + .toList() + ); IModel hasApprovedFinalThesis = hasApprovedFinalThesis(projectModel); - redGreen("status_final_thesis", hasApprovedFinalThesis, - "must_approve_final_thesis", - "final_thesis_approved"); + redGreen("status_final_thesis", hasApprovedFinalThesis, "must_approve_final_thesis", "final_thesis_approved"); IModel hasSubmittedPlagiarismAnalysis = hasSubmittedPlagiarismAnalysis(projectModel); - redGreen("status_plagiarism", hasSubmittedPlagiarismAnalysis, - "must_perform_plagiarism_check", - "plagiarism_check_performed"); - IModel hasSuppliedPublicationMetadata = Model.of(publicationMetadataService.hasSuppliedPublicationMetadata(projectModel.getObject(), nationalSubjectCategoryService.listCategories().isEmpty())); - redGreen("status_publication_metadata", hasSuppliedPublicationMetadata, - "must_supply_publication_metadata", - "publication_metadata_supplied"); + redGreen( + "status_plagiarism", + hasSubmittedPlagiarismAnalysis, + "must_perform_plagiarism_check", + "plagiarism_check_performed" + ); + IModel hasSuppliedPublicationMetadata = Model.of( + publicationMetadataService.hasSuppliedPublicationMetadata( + projectModel.getObject(), + nationalSubjectCategoryService.listCategories().isEmpty() + ) + ); + redGreen( + "status_publication_metadata", + hasSuppliedPublicationMetadata, + "must_supply_publication_metadata", + "publication_metadata_supplied" + ); IModel hasFilledInGradingBasis = gradingReport.map(this::gradingBasisDone); - redGreen("status_grading_basis", hasFilledInGradingBasis, - "grading_basis_must_meet_minimum_requirements", - "grading_basis_minimum_requirements_met"); + redGreen( + "status_grading_basis", + hasFilledInGradingBasis, + "grading_basis_must_meet_minimum_requirements", + "grading_basis_minimum_requirements_met" + ); IModel hasFilledInIndividualAssessment = individualCriterionNotMet.map(List::isEmpty); - redGreen("status_individual_assessment", hasFilledInIndividualAssessment, - "individual_assessment_must_meet_minimum_requirements", - "individual_assessment_meets_minimum_requirements"); + redGreen( + "status_individual_assessment", + hasFilledInIndividualAssessment, + "individual_assessment_must_meet_minimum_requirements", + "individual_assessment_meets_minimum_requirements" + ); add(new UserLabel("author_name", authorModel)); @@ -100,31 +124,41 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { } }; add(gradingBasisMissing); - gradingBasisMissing.add(new AutoHidingListView<>("grading_basis_requirements_not_met", gradingBasisCriterionNotMet) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("title", item.getModel().map(GradingCriterion::getTitle))); - item.add(new Label("given_points", item.getModel().map(GradingCriterion::getPoints).orElse(0))); - item.add(new Label("maximum_points", item.getModel().map(GradingCriterion::getMaxPoints))); - item.add(new Label("required_points", item.getModel().map(GradingCriterion::getPointsRequiredToPass))); + gradingBasisMissing.add( + new AutoHidingListView<>("grading_basis_requirements_not_met", gradingBasisCriterionNotMet) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("title", item.getModel().map(GradingCriterion::getTitle))); + item.add(new Label("given_points", item.getModel().map(GradingCriterion::getPoints).orElse(0))); + item.add(new Label("maximum_points", item.getModel().map(GradingCriterion::getMaxPoints))); + item.add( + new Label("required_points", item.getModel().map(GradingCriterion::getPointsRequiredToPass)) + ); + } } - }); - gradingBasisMissing.add(new WebMarkupContainer("grading_basis_overall_motivation_missing") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!gradingReport.getObject().hasProvidedOverallMotivation()); + ); + gradingBasisMissing.add( + new WebMarkupContainer("grading_basis_overall_motivation_missing") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!gradingReport.getObject().hasProvidedOverallMotivation()); + } } - }); - add(new AutoHidingListView<>("individual_assessment_requirements_not_met", individualCriterionNotMet) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("title", item.getModel().map(GradingCriterion::getTitle))); - item.add(new Label("given_points", item.getModel().map(GradingCriterion::getPoints).orElse(0))); - item.add(new Label("maximum_points", item.getModel().map(GradingCriterion::getMaxPoints))); - item.add(new Label("required_points", item.getModel().map(GradingCriterion::getPointsRequiredToPass))); + ); + add( + new AutoHidingListView<>("individual_assessment_requirements_not_met", individualCriterionNotMet) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("title", item.getModel().map(GradingCriterion::getTitle))); + item.add(new Label("given_points", item.getModel().map(GradingCriterion::getPoints).orElse(0))); + item.add(new Label("maximum_points", item.getModel().map(GradingCriterion::getMaxPoints))); + item.add( + new Label("required_points", item.getModel().map(GradingCriterion::getPointsRequiredToPass)) + ); + } } - }); + ); IModel minimumActiveParticipationsToBeGraded = LoadableDetachableModel.of(() -> { Project project = projectModel.getObject(); @@ -133,14 +167,18 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { IModel completedParticipations = LoadableDetachableModel.of(() -> { Project project = projectModel.getObject(); List participations = finalSeminarService.findUserParticipating( - project, - authorModel.getObject()); + project, + authorModel.getObject() + ); return participations.size(); }); - IModel leftToDo = minimumActiveParticipationsToBeGraded - .combineWith(completedParticipations, (required, completed) -> required - completed); - IModel completedActiveParticipationsRequirement = LoadableDetachableModel.of(() -> - completedParticipations.getObject() >= minimumActiveParticipationsToBeGraded.getObject()); + IModel leftToDo = minimumActiveParticipationsToBeGraded.combineWith( + completedParticipations, + (required, completed) -> required - completed + ); + IModel completedActiveParticipationsRequirement = LoadableDetachableModel.of( + () -> completedParticipations.getObject() >= minimumActiveParticipationsToBeGraded.getObject() + ); WebMarkupContainer activeParticipationsMissing = new WebMarkupContainer("active_participations_missing") { @Override @@ -163,32 +201,40 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { }; add(activeParticipationsCompleted); - IModel confirmationMessage = completedActiveParticipationsRequirement - .flatMap(completed -> { - if (Objects.equals(Boolean.TRUE, completed)) { - return null; - } - return new StringResourceModel("active_participations_missing_confirmation_message", this); - }); - - add(new SendToExaminer("send_to_examiner", projectModel, authorModel, confirmationMessage) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasApprovedFinalThesis.getObject() - && hasSubmittedPlagiarismAnalysis.getObject() - && hasSuppliedPublicationMetadata.getObject() - && hasFilledInGradingBasis.getObject() - && hasFilledInIndividualAssessment.getObject()); + IModel confirmationMessage = completedActiveParticipationsRequirement.flatMap(completed -> { + if (Objects.equals(Boolean.TRUE, completed)) { + return null; } + return new StringResourceModel("active_participations_missing_confirmation_message", this); }); + + add( + new SendToExaminer("send_to_examiner", projectModel, authorModel, confirmationMessage) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + hasApprovedFinalThesis.getObject() && + hasSubmittedPlagiarismAnalysis.getObject() && + hasSuppliedPublicationMetadata.getObject() && + hasFilledInGradingBasis.getObject() && + hasFilledInIndividualAssessment.getObject() + ); + } + } + ); } private boolean gradingBasisDone(SupervisorGradingReport supervisorGradingReport) { - boolean criteriaMet = supervisorGradingReport.getProjectCriteria() - .stream() - .allMatch(GradingCriterion::meetsMinimumPointRequirement); - return criteriaMet && supervisorGradingReport.hasProvidedRejectionFeedback() && supervisorGradingReport.hasProvidedOverallMotivation(); + boolean criteriaMet = supervisorGradingReport + .getProjectCriteria() + .stream() + .allMatch(GradingCriterion::meetsMinimumPointRequirement); + return ( + criteriaMet && + supervisorGradingReport.hasProvidedRejectionFeedback() && + supervisorGradingReport.hasProvidedOverallMotivation() + ); } private void redGreen(String id, IModel finished, String redTextKey, String greenTextKey) { @@ -197,14 +243,14 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { private IModel hasApprovedFinalThesis(IModel projectModel) { return LoadableDetachableModel.of(() -> finalThesisService.findByProject(projectModel.getObject())) - .filter(ft -> ft.getStatus() == FinalThesis.Status.APPROVED) - .isPresent(); + .filter(ft -> ft.getStatus() == FinalThesis.Status.APPROVED) + .isPresent(); } private IModel hasSubmittedPlagiarismAnalysis(IModel projectModel) { return LoadableDetachableModel.of(() -> finalThesisService.findByProject(projectModel.getObject())) - .map(FinalThesis::getTextMatchingDocument) - .isPresent(); + .map(FinalThesis::getTextMatchingDocument) + .isPresent(); } @Override @@ -214,16 +260,20 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { } private class AssessmentForm extends org.apache.wicket.markup.html.form.Form { + public AssessmentForm(String id, IModel gradingReport) { super(id, gradingReport); - add(new FencedFeedbackPanel("feedback", this)); add(new CriteriaPanel("criteria", gradingReport)); - add(new TemplatePanel("points_to_grade_conversion", gradingReport.map(SupervisorGradingReport::getProject))); + add( + new TemplatePanel("points_to_grade_conversion", gradingReport.map(SupervisorGradingReport::getProject)) + ); - GradeCalculator supervisorCalculator = gradeCalculatorService.getSupervisorCalculator(gradingReport.getObject().getProject()); + GradeCalculator supervisorCalculator = gradeCalculatorService.getSupervisorCalculator( + gradingReport.getObject().getProject() + ); add(new GradingReportPointsPanel("points", gradingReport, supervisorCalculator)); WebMarkupContainer save = new WebMarkupContainer("save") { @@ -250,6 +300,5 @@ public class IndividualAuthorAssessmentPanel extends GenericPanel { LocalTime now = LocalTime.now().truncatedTo(ChronoUnit.SECONDS); success(getString("individual_assessment_updated", Model.of(now))); } - } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/OppositionReportPdfResource.java b/view/src/main/java/se/su/dsv/scipro/grading/OppositionReportPdfResource.java index 74ebcdee49..6be2def781 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/OppositionReportPdfResource.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/OppositionReportPdfResource.java @@ -4,6 +4,7 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.report.OppositionReport; public class OppositionReportPdfResource extends ReportPdfResource { + private IModel oppositionReportModel; public OppositionReportPdfResource(IModel reportIModel) { @@ -19,6 +20,13 @@ public class OppositionReportPdfResource extends ReportPdfResource { @Override public String getFileName() { OppositionReport report = oppositionReportModel.getObject(); - return "opposition_report_" + report.getOpponentFirstName() + "_" + report.getOpponentLastName() + "." + getExtension(); + return ( + "opposition_report_" + + report.getOpponentFirstName() + + "_" + + report.getOpponentLastName() + + "." + + getExtension() + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataFormComponentPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataFormComponentPanel.java index aea827cb11..2f15edd4ba 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataFormComponentPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataFormComponentPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.LambdaChoiceRenderer; import org.apache.wicket.markup.html.form.TextArea; @@ -10,39 +12,73 @@ import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.LoadableDetachableModel; import se.su.dsv.scipro.system.Language; -import jakarta.inject.Inject; -import java.util.List; - public class PublicationMetadataFormComponentPanel extends GenericPanel { + @Inject NationalSubjectCategoryService nationalSubjectCategoryService; public PublicationMetadataFormComponentPanel(String id, IModel metadataModel) { super(id, metadataModel); - - add(new TextArea<>("abstract_en", LambdaModel.of(metadataModel, PublicationMetadata::getAbstractEnglish, PublicationMetadata::setAbstractEnglish))); - TextArea abstractSwedish = new TextArea<>("abstract_sv", LambdaModel.of(metadataModel, PublicationMetadata::getAbstractSwedish, PublicationMetadata::setAbstractSwedish)); + add( + new TextArea<>( + "abstract_en", + LambdaModel.of( + metadataModel, + PublicationMetadata::getAbstractEnglish, + PublicationMetadata::setAbstractEnglish + ) + ) + ); + TextArea abstractSwedish = new TextArea<>( + "abstract_sv", + LambdaModel.of( + metadataModel, + PublicationMetadata::getAbstractSwedish, + PublicationMetadata::setAbstractSwedish + ) + ); abstractSwedish.setVisible(inSwedish()); add(abstractSwedish); - add(new TextField<>("keywords_en", LambdaModel.of(metadataModel, PublicationMetadata::getKeywordsEnglish, PublicationMetadata::setKeywordsEnglish))); - TextField keywordsSwedish = new TextField<>("keywords_sv", LambdaModel.of(metadataModel, PublicationMetadata::getKeywordsSwedish, PublicationMetadata::setKeywordsSwedish)); + add( + new TextField<>( + "keywords_en", + LambdaModel.of( + metadataModel, + PublicationMetadata::getKeywordsEnglish, + PublicationMetadata::setKeywordsEnglish + ) + ) + ); + TextField keywordsSwedish = new TextField<>( + "keywords_sv", + LambdaModel.of( + metadataModel, + PublicationMetadata::getKeywordsSwedish, + PublicationMetadata::setKeywordsSwedish + ) + ); keywordsSwedish.setVisible(inSwedish()); add(keywordsSwedish); - IModel> availableCategories = LoadableDetachableModel.of(nationalSubjectCategoryService::listCategories); + IModel> availableCategories = LoadableDetachableModel.of( + nationalSubjectCategoryService::listCategories + ); DropDownChoice nationalSubjectCategoryChoice = new DropDownChoice<>( - "national_subject_category", - LambdaModel.of( - metadataModel, - PublicationMetadata::getNationalSubjectCategory, - PublicationMetadata::setNationalSubjectCategory), - availableCategories, - new LambdaChoiceRenderer<>(NationalSubjectCategory::getEnglishName, NationalSubjectCategory::getId)); + "national_subject_category", + LambdaModel.of( + metadataModel, + PublicationMetadata::getNationalSubjectCategory, + PublicationMetadata::setNationalSubjectCategory + ), + availableCategories, + new LambdaChoiceRenderer<>(NationalSubjectCategory::getEnglishName, NationalSubjectCategory::getId) + ); if (metadataModel.getObject().getNationalSubjectCategory() == null) { - availableCategories.getObject() - .stream() - .filter(NationalSubjectCategory::isPreselected) - .findAny() - .ifPresent(nationalSubjectCategoryChoice::setDefaultModelObject); + availableCategories + .getObject() + .stream() + .filter(NationalSubjectCategory::isPreselected) + .findAny() + .ifPresent(nationalSubjectCategoryChoice::setDefaultModelObject); } nationalSubjectCategoryChoice.setNullValid(true); nationalSubjectCategoryChoice.setVisible(!availableCategories.getObject().isEmpty()); diff --git a/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataPanel.java index 04ccf601d0..366fea8ac2 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/PublicationMetadataPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.Form; @@ -13,38 +14,40 @@ import se.su.dsv.scipro.finalthesis.FinalThesis; import se.su.dsv.scipro.finalthesis.FinalThesisService; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; - public class PublicationMetadataPanel extends GenericPanel { + @Inject PublicationMetadataService publicationMetadataService; + @Inject private FinalThesisService finalThesisService; public PublicationMetadataPanel(String id, IModel projectModel) { super(id, projectModel); - IModel metadataModel = LoadableDetachableModel.of(() -> - publicationMetadataService.getByProject(getModelObject())); + publicationMetadataService.getByProject(getModelObject()) + ); Form form = new PublicationMetadataForm("form", metadataModel); add(form); } private class PublicationMetadataForm extends Form { + public PublicationMetadataForm(String id, IModel metadataModel) { super(id, metadataModel); - add(new FencedFeedbackPanel("feedback", this)); add(new PublicationMetadataFormComponentPanel("components", metadataModel)); - add(new WebMarkupContainer("save") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(isEnabledInHierarchy()); + add( + new WebMarkupContainer("save") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(isEnabledInHierarchy()); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/grading/ReflectionModalBodyPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/ReflectionModalBodyPanel.java index 895e65018f..986d509685 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/ReflectionModalBodyPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/ReflectionModalBodyPanel.java @@ -21,13 +21,18 @@ import se.su.dsv.scipro.system.User; * author's reflection as they're doing their final individual assessment. */ class ReflectionModalBodyPanel extends Panel { + @Inject private ReflectionService reflectionService; private final IModel projectModel; private final IModel authorModel; - private enum State { VIEWING, REQUESTING_IMPROVEMENTS, EDITING } + private enum State { + VIEWING, + REQUESTING_IMPROVEMENTS, + EDITING, + } private State state = State.VIEWING; @@ -40,58 +45,71 @@ class ReflectionModalBodyPanel extends Panel { IModel reflectionModel = projectModel.combineWith(authorModel, reflectionService::getReflection); - add(new MultiLineLabel("reflection_text", reflectionModel.map(this::getReflectionText)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(state != State.EDITING); + add( + new MultiLineLabel("reflection_text", reflectionModel.map(this::getReflectionText)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(state != State.EDITING); + } } - }); + ); - add(new MultiLineLabel("improvements_needed_supervisor_feedback", reflectionModel - .as(Reflection.ImprovementsNeeded.class) - .map(Reflection.ImprovementsNeeded::commentBySupervisor)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isBlank()); + add( + new MultiLineLabel( + "improvements_needed_supervisor_feedback", + reflectionModel + .as(Reflection.ImprovementsNeeded.class) + .map(Reflection.ImprovementsNeeded::commentBySupervisor) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); add(new RequestImprovementsForm("request_improvements_form", reflectionModel)); add(new SupervisorEditReflectionForm("edit_reflection_form", reflectionModel)); - add(new AjaxLink<>("show_request_improvements_form", reflectionModel) { - @Override - public void onClick(AjaxRequestTarget target) { - ReflectionModalBodyPanel.this.state = State.REQUESTING_IMPROVEMENTS; - target.add(ReflectionModalBodyPanel.this); - } + add( + new AjaxLink<>("show_request_improvements_form", reflectionModel) { + @Override + public void onClick(AjaxRequestTarget target) { + ReflectionModalBodyPanel.this.state = State.REQUESTING_IMPROVEMENTS; + target.add(ReflectionModalBodyPanel.this); + } - @Override - protected void onConfigure() { - super.onConfigure(); - Reflection reflection = getModelObject(); - boolean canRequestImprovements = reflection instanceof Reflection.Submitted; - setVisible(state == State.VIEWING && canRequestImprovements && isEnabledInHierarchy()); + @Override + protected void onConfigure() { + super.onConfigure(); + Reflection reflection = getModelObject(); + boolean canRequestImprovements = reflection instanceof Reflection.Submitted; + setVisible(state == State.VIEWING && canRequestImprovements && isEnabledInHierarchy()); + } } - }); + ); - add(new AjaxLink<>("show_edit_reflection_form", reflectionModel) { - @Override - public void onClick(AjaxRequestTarget target) { - ReflectionModalBodyPanel.this.state = State.EDITING; - target.add(ReflectionModalBodyPanel.this); - } + add( + new AjaxLink<>("show_edit_reflection_form", reflectionModel) { + @Override + public void onClick(AjaxRequestTarget target) { + ReflectionModalBodyPanel.this.state = State.EDITING; + target.add(ReflectionModalBodyPanel.this); + } - @Override - protected void onConfigure() { - super.onConfigure(); - Reflection reflection = getModelObject(); - boolean canEditReflection = reflection instanceof Reflection.Submitted || reflection instanceof Reflection.ImprovementsNeeded; - setVisible(state == State.VIEWING && canEditReflection && isEnabledInHierarchy()); + @Override + protected void onConfigure() { + super.onConfigure(); + Reflection reflection = getModelObject(); + boolean canEditReflection = + reflection instanceof Reflection.Submitted || + reflection instanceof Reflection.ImprovementsNeeded; + setVisible(state == State.VIEWING && canEditReflection && isEnabledInHierarchy()); + } } - }); + ); } private String getReflectionText(Reflection reflection) { @@ -112,36 +130,41 @@ class ReflectionModalBodyPanel extends Panel { } private class RequestImprovementsForm extends Form { + public RequestImprovementsForm(String id, IModel reflectionModel) { super(id, reflectionModel); - IModel commentModel = new Model<>(); TextArea comment = new TextArea<>("comment", commentModel); comment.setRequired(true); add(comment); - add(new AjaxSubmitLink("submit") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - super.onSubmit(target); + add( + new AjaxSubmitLink("submit") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + super.onSubmit(target); - reflectionService.requestNewReflection( + reflectionService.requestNewReflection( projectModel.getObject(), authorModel.getObject(), - commentModel.getObject()); + commentModel.getObject() + ); - ReflectionModalBodyPanel.this.state = State.VIEWING; - target.add(ReflectionModalBodyPanel.this); + ReflectionModalBodyPanel.this.state = State.VIEWING; + target.add(ReflectionModalBodyPanel.this); + } } - }); - add(new AjaxLink<>("cancel") { - @Override - public void onClick(AjaxRequestTarget target) { - ReflectionModalBodyPanel.this.state = State.VIEWING; - target.add(ReflectionModalBodyPanel.this); + ); + add( + new AjaxLink<>("cancel") { + @Override + public void onClick(AjaxRequestTarget target) { + ReflectionModalBodyPanel.this.state = State.VIEWING; + target.add(ReflectionModalBodyPanel.this); + } } - }); + ); } @Override @@ -152,34 +175,39 @@ class ReflectionModalBodyPanel extends Panel { } private class SupervisorEditReflectionForm extends Form { + public SupervisorEditReflectionForm(String id, IModel reflectionModel) { super(id, reflectionModel); - IModel reflectionTextModel = new Model<>(getReflectionText(reflectionModel.getObject())); TextArea reflectionTextArea = new TextArea<>("reflection", reflectionTextModel); reflectionTextArea.setRequired(true); add(reflectionTextArea); - add(new AjaxSubmitLink("submit") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - reflectionService.submitReflection( + add( + new AjaxSubmitLink("submit") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + reflectionService.submitReflection( projectModel.getObject(), authorModel.getObject(), - reflectionTextModel.getObject()); + reflectionTextModel.getObject() + ); - ReflectionModalBodyPanel.this.state = State.VIEWING; - target.add(ReflectionModalBodyPanel.this); + ReflectionModalBodyPanel.this.state = State.VIEWING; + target.add(ReflectionModalBodyPanel.this); + } } - }); - add(new AjaxLink<>("cancel") { - @Override - public void onClick(AjaxRequestTarget target) { - ReflectionModalBodyPanel.this.state = State.VIEWING; - target.add(ReflectionModalBodyPanel.this); + ); + add( + new AjaxLink<>("cancel") { + @Override + public void onClick(AjaxRequestTarget target) { + ReflectionModalBodyPanel.this.state = State.VIEWING; + target.add(ReflectionModalBodyPanel.this); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/grading/ReportPdfResource.java b/view/src/main/java/se/su/dsv/scipro/grading/ReportPdfResource.java index 7e19fd723e..193ba7c0d9 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/ReportPdfResource.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/ReportPdfResource.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.grading; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; @@ -10,10 +13,6 @@ import org.wicketstuff.jasperreports.JRConcreteResource; import org.wicketstuff.jasperreports.handlers.PdfResourceHandler; import se.su.dsv.scipro.report.Report; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - public abstract class ReportPdfResource extends JRConcreteResource { private IModel reportIModel; @@ -37,7 +36,9 @@ public abstract class ReportPdfResource extends JRConcreteResource { + @Inject GradingService gradingService; + @Inject FinalThesisService finalThesisService; + @Inject GradingReportService gradingReportService; + @Inject GradeCalculatorService gradeCalculatorService; + @Inject DaisyAPI daisyAPI; + @Inject FileService fileService; + @Inject ReflectionService reflectionService; + @Inject RoughDraftApprovalService roughDraftApprovalService; + @Inject FinalSeminarService finalSeminarService; + @Inject PublicationMetadataService publicationMetadataService; private IModel needsSending; - public SendToExaminer(String id, IModel projectModel, IModel authorModel, - IModel confirmationMessage) { + public SendToExaminer( + String id, + IModel projectModel, + IModel authorModel, + IModel confirmationMessage + ) { super(id, projectModel); - needsSending = LoadableDetachableModel.of(() -> hasGradedExaminationWithoutSuggestion(authorModel.getObject())); IModel examinationDate = new Model<>(); @@ -103,32 +115,47 @@ public class SendToExaminer extends GenericPanel { sendButton.add(new JavascriptEventConfirmation("click", confirmationMessage)); form.add(sendButton); - TextField examinationDateField = new TextField<>("examinationDate", examinationDate, LocalDate.class); + TextField examinationDateField = new TextField<>( + "examinationDate", + examinationDate, + LocalDate.class + ); examinationDateField.setRequired(true); examinationDateField.add(new BootstrapDatePicker()); form.add(examinationDateField); - add(new WebMarkupContainer("already_sent") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!needsSending.getObject()); + add( + new WebMarkupContainer("already_sent") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!needsSending.getObject()); + } } - }); + ); add(new FencedFeedbackPanel("feedback")); } private boolean hasGradedExaminationWithoutSuggestion(User author) { String token = getSession().getMetaData(OAuth.TOKEN); Project project = getModelObject(); - List examinations = gradingService.getExaminations(token, project.getIdentifier(), author.getIdentifier()); + List examinations = gradingService.getExaminations( + token, + project.getIdentifier(), + author.getIdentifier() + ); if (examinations == null) { // if we can't tell assume it is not sent return true; } for (Examination examination : examinations) { if (examination.hasManyPassingGrades()) { - Either> result = gradingService.getResult(token, project.getIdentifier(), author.getIdentifier(), examination.id()); + Either> result = gradingService.getResult( + token, + project.getIdentifier(), + author.getIdentifier(), + examination.id() + ); if (result.isRight() && result.right().isEmpty()) { return true; } @@ -149,17 +176,23 @@ public class SendToExaminer extends GenericPanel { // some individual steps have not been completed return; } - List examinations = gradingService.getExaminations(token, project.getIdentifier(), author.getIdentifier()); + List examinations = gradingService.getExaminations( + token, + project.getIdentifier(), + author.getIdentifier() + ); if (examinations == null) { getSession().error("Failed to get the examination setup for " + author.getFullName()); return; } - List gradedExaminations = examinations - .stream() - .filter(Examination::hasManyPassingGrades) - .toList(); + List gradedExaminations = examinations.stream().filter(Examination::hasManyPassingGrades).toList(); if (!arePassFailReported(token, project, author, examinations)) { - getSession().info("You have to report the pass/fail criteria for " + author.getFullName() + " since it was not reported when the student passed phase two review."); + getSession() + .info( + "You have to report the pass/fail criteria for " + + author.getFullName() + + " since it was not reported when the student passed phase two review." + ); setResponsePage(SupervisorGradingPage.class, SupervisorGradingPage.getPageParameters(project)); } else if (gradedExaminations.size() > 1) { getSession().info(author.getFullName() + " has a complex examination setup, manual reporting is necessary"); @@ -173,11 +206,17 @@ public class SendToExaminer extends GenericPanel { } private boolean arePassFailReported(String token, Project project, User author, List examinations) { - List passFail = examinations.stream() - .filter(Predicate.not(Examination::hasManyPassingGrades)) - .toList(); + List passFail = examinations + .stream() + .filter(Predicate.not(Examination::hasManyPassingGrades)) + .toList(); for (Examination examination : passFail) { - Either> result = gradingService.getResult(token, project.getIdentifier(), author.getIdentifier(), examination.id()); + Either> result = gradingService.getResult( + token, + project.getIdentifier(), + author.getIdentifier(), + examination.id() + ); if (!result.isRight() || result.right().isEmpty()) { return false; } @@ -197,7 +236,10 @@ public class SendToExaminer extends GenericPanel { private boolean checkStepsMissingFor(User author) { boolean missing = false; - SupervisorGradingReport supervisorGradingReport = gradingReportService.getSupervisorGradingReport(getModelObject(), author); + SupervisorGradingReport supervisorGradingReport = gradingReportService.getSupervisorGradingReport( + getModelObject(), + author + ); if (!supervisorGradingReport.isFinished()) { getSession().error("You must finish the grading basis for " + author.getFullName()); missing = true; @@ -208,8 +250,12 @@ public class SendToExaminer extends GenericPanel { private void sendSuggestion(Project project, User author, Examination examination, LocalDate examinationDate) { String token = getSession().getMetaData(OAuth.TOKEN); - Either> currentResult - = gradingService.getResult(token, project.getIdentifier(), author.getIdentifier(), examination.id()); + Either> currentResult = gradingService.getResult( + token, + project.getIdentifier(), + author.getIdentifier(), + examination.id() + ); if (currentResult.isRight() && currentResult.right().isPresent()) { // already sent for examining return; @@ -224,16 +270,19 @@ public class SendToExaminer extends GenericPanel { } GradeCalculator gradeCalculator = gradeCalculatorService.getSupervisorCalculator(project); - SupervisorGradingReport supervisorGradingReport = gradingReportService.getSupervisorGradingReport(getModelObject(), author); + SupervisorGradingReport supervisorGradingReport = gradingReportService.getSupervisorGradingReport( + getModelObject(), + author + ); GradingReport.Grade grade = gradeCalculator.getGrade(supervisorGradingReport); - Either reported = - gradingService.reportGrade( - token, - project.getIdentifier(), - author.getIdentifier(), - examination.id(), - grade.name(), - examinationDate); + Either reported = gradingService.reportGrade( + token, + project.getIdentifier(), + author.getIdentifier(), + examination.id(), + grade.name(), + examinationDate + ); if (!reported.isRight()) { getSession().error("Failed to send " + author.getFullName() + " for examining"); @@ -242,25 +291,27 @@ public class SendToExaminer extends GenericPanel { if (!sendProtocol(token, project, author, examination)) { getSession().error("Failed to send the grading basis for " + author.getFullName()); - } - else { + } else { gradingReportService.submitReport(supervisorGradingReport); getSession().success("Successfully sent " + author.getFullName() + " for examining"); } } private LocalDate getExaminationDate(User author, Project project, FinalThesis finalThesis) { - var oppositions = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(project.getProjectType(), author); + var oppositions = finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType( + project.getProjectType(), + author + ); var participations = finalSeminarService.findUserParticipating(project, author); Optional seminarDate = Stream.concat(oppositions.stream(), participations.stream()) - .filter(FinalSeminarParticipation::isApproved) - .map(FinalSeminarParticipation::getFinalSeminar) - .map(FinalSeminar::getDateCreated) - .max(Comparator.naturalOrder()) - .map(Date::toInstant) - .map(instant -> instant.atZone(ZoneId.systemDefault())) - .map(ZonedDateTime::toLocalDate); + .filter(FinalSeminarParticipation::isApproved) + .map(FinalSeminarParticipation::getFinalSeminar) + .map(FinalSeminar::getDateCreated) + .max(Comparator.naturalOrder()) + .map(Date::toInstant) + .map(instant -> instant.atZone(ZoneId.systemDefault())) + .map(ZonedDateTime::toLocalDate); boolean hasFinalThesis = finalThesis != null; boolean hasSeminarDate = seminarDate.isPresent(); @@ -295,39 +346,41 @@ public class SendToExaminer extends GenericPanel { } private void sendTitlesToDaisy(final Project project, final FinalThesis finalThesis) { - daisyAPI.getThesis(project.getIdentifier()).ifPresent(thesis -> { - final ThesisToBeUpdated thesisToBeUpdated = new ThesisToBeUpdated(); - thesisToBeUpdated.setStartDate(thesis.getStartDate()); - thesisToBeUpdated.setAborted(thesis.isAborted()); - thesisToBeUpdated.setEndDate(thesis.getEndDate()); + daisyAPI + .getThesis(project.getIdentifier()) + .ifPresent(thesis -> { + final ThesisToBeUpdated thesisToBeUpdated = new ThesisToBeUpdated(); + thesisToBeUpdated.setStartDate(thesis.getStartDate()); + thesisToBeUpdated.setAborted(thesis.isAborted()); + thesisToBeUpdated.setEndDate(thesis.getEndDate()); - final UnitWithID unitWithID = new UnitWithID(); - unitWithID.setId(thesis.getUnit().getId()); - thesisToBeUpdated.setUnit(unitWithID); + final UnitWithID unitWithID = new UnitWithID(); + unitWithID.setId(thesis.getUnit().getId()); + thesisToBeUpdated.setUnit(unitWithID); - final ResearchAreas researchAreas = new ResearchAreas(); - thesis.getResearchAreas().getResearchAreas().forEach(researchArea -> { - final ResearchAreaWithID researchArea2 = new ResearchAreaWithID(); - researchArea2.setId(researchArea.getId()); - researchAreas.getResearchAreas().add(researchArea2); + final ResearchAreas researchAreas = new ResearchAreas(); + thesis + .getResearchAreas() + .getResearchAreas() + .forEach(researchArea -> { + final ResearchAreaWithID researchArea2 = new ResearchAreaWithID(); + researchArea2.setId(researchArea.getId()); + researchAreas.getResearchAreas().add(researchArea2); + }); + thesisToBeUpdated.setResearchAreas(researchAreas); + + if (finalThesis.getSwedishTitle() != null) { + thesisToBeUpdated.setTitle(finalThesis.getSwedishTitle()); + } else { + thesisToBeUpdated.setTitle(finalThesis.getEnglishTitle()); + } + thesisToBeUpdated.setTitleEn(finalThesis.getEnglishTitle()); + daisyAPI.updateThesis(project.getIdentifier(), thesisToBeUpdated); }); - thesisToBeUpdated.setResearchAreas(researchAreas); - - if (finalThesis.getSwedishTitle() != null) { - thesisToBeUpdated.setTitle(finalThesis.getSwedishTitle()); - } - else { - thesisToBeUpdated.setTitle(finalThesis.getEnglishTitle()); - } - thesisToBeUpdated.setTitleEn(finalThesis.getEnglishTitle()); - daisyAPI.updateThesis(project.getIdentifier(), thesisToBeUpdated); - }); } private boolean sendPublicationToDaisy(final Project project, final FinalThesis finalThesis) { - final ThesisPublication old = daisyAPI - .getPublication(project.getIdentifier()) - .orElse(null); + final ThesisPublication old = daisyAPI.getPublication(project.getIdentifier()).orElse(null); if (old == null || old.getFile() == null) { final ThesisPublication thesisPublication = createThesisPublication(project, finalThesis); final boolean sentPublication = daisyAPI.sendPublication(project.getIdentifier(), thesisPublication); @@ -337,14 +390,14 @@ public class SendToExaminer extends GenericPanel { try { return daisyAPI.sendPublicationFile( - project.getIdentifier(), - finalThesisDocument.getName(), - fileService.getData(finalThesisDocument)); + project.getIdentifier(), + finalThesisDocument.getName(), + fileService.getData(finalThesisDocument) + ); } catch (RuntimeException e) { return false; } - } - else { + } else { return false; } } @@ -369,24 +422,27 @@ public class SendToExaminer extends GenericPanel { thesisPublication.setSwedishKeywords(publicationMetadata.getKeywordsSwedish()); thesisPublication.setEnglishKeywords(publicationMetadata.getKeywordsEnglish()); if (publicationMetadata.getNationalSubjectCategory() != null) { - thesisPublication.setNationalSubjectCategoryExternalID(publicationMetadata.getNationalSubjectCategory().getExternalId()); + thesisPublication.setNationalSubjectCategoryExternalID( + publicationMetadata.getNationalSubjectCategory().getExternalId() + ); } return thesisPublication; } private boolean sendTextMatchingDocument(final String token, final Project project, final FinalThesis finalThesis) { - final boolean hasTextMatchingDocument = - gradingService.hasTextMatchingDocument( - getSession().getMetaData(OAuth.TOKEN), - project.getIdentifier()); + final boolean hasTextMatchingDocument = gradingService.hasTextMatchingDocument( + getSession().getMetaData(OAuth.TOKEN), + project.getIdentifier() + ); if (!hasTextMatchingDocument) { try { - final Either sendTextMatchingDocument - = gradingService.sendTextMatchingDocument( + final Either sendTextMatchingDocument = + gradingService.sendTextMatchingDocument( token, project.getIdentifier(), fileService.getData(finalThesis.getTextMatchingDocument().getFileDescription()), - finalThesis.getTextMatchingDocument().getFileDescription().getMimeType()); + finalThesis.getTextMatchingDocument().getFileDescription().getMimeType() + ); return sendTextMatchingDocument.isRight(); } catch (RuntimeException e) { return false; @@ -395,29 +451,36 @@ public class SendToExaminer extends GenericPanel { return true; } - private boolean sendProtocol(final String token, final Project project, final User user, final Examination examination) { - IModel supervisorGradingReport = - LoadableDetachableModel.of(() -> gradingReportService.getSupervisorGradingReport(project, user)); - IModel reflection = - LoadableDetachableModel.of(() -> reflectionService.getSubmittedReflection(project, user)); - IModel roughDraftApproval = - LoadableDetachableModel.of(() -> roughDraftApprovalService.findBy(project)) - .map(o -> o.orElse(null)); - IModel finalThesis = - LoadableDetachableModel.of(() -> finalThesisService.findByProject(project)); - final DataExposedGradingReportPdf pdf = - new DataExposedGradingReportPdf( - supervisorGradingReport, - reflection, - roughDraftApproval, - finalThesis); + private boolean sendProtocol( + final String token, + final Project project, + final User user, + final Examination examination + ) { + IModel supervisorGradingReport = LoadableDetachableModel.of(() -> + gradingReportService.getSupervisorGradingReport(project, user) + ); + IModel reflection = LoadableDetachableModel.of(() -> + reflectionService.getSubmittedReflection(project, user) + ); + IModel roughDraftApproval = LoadableDetachableModel.of(() -> + roughDraftApprovalService.findBy(project) + ).map(o -> o.orElse(null)); + IModel finalThesis = LoadableDetachableModel.of(() -> finalThesisService.findByProject(project)); + final DataExposedGradingReportPdf pdf = new DataExposedGradingReportPdf( + supervisorGradingReport, + reflection, + roughDraftApproval, + finalThesis + ); final Either sendProtocol = gradingService.sendProtocol( - token, - project.getIdentifier(), - user.getIdentifier(), - examination.id(), - pdf.getData(), - pdf.getContentType()); + token, + project.getIdentifier(), + user.getIdentifier(), + examination.id(), + pdf.getData(), + pdf.getContentType() + ); return sendProtocol.isRight(); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingPage.java b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingPage.java index 695354d4c9..84dfa11a0f 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -24,49 +30,53 @@ import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.*; - -public class SupervisorGradingPage extends AbstractSupervisorProjectDetailsPage - implements MenuHighlightSupervisorGradingReport -{ +public class SupervisorGradingPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorGradingReport { @Inject private OAuthService oAuthService; + @Inject private GradingService gradingService; + @Inject private RoughDraftApprovalService roughDraftApprovalService; public SupervisorGradingPage(final PageParameters pp) { super(pp); - add(new FeedbackPanel("feedback")); - final IModel> authors = new ListAdapterModel<>(LambdaModel.of(projectModel, Project::getProjectParticipants, Project::setProjectParticipants)); - add(new ListView<>("authors", authors) { - { - setReuseItems(true); - } + final IModel> authors = new ListAdapterModel<>( + LambdaModel.of(projectModel, Project::getProjectParticipants, Project::setProjectParticipants) + ); + add( + new ListView<>("authors", authors) { + { + setReuseItems(true); + } - @Override - protected void populateItem(final ListItem item) { - item.add(new UserLabel("authorName", item.getModel())); - final IModel> examinations = SupervisorGradingPage.this.getExaminations(item.getModel()) - .orElseGet(Collections::emptyList); + @Override + protected void populateItem(final ListItem item) { + item.add(new UserLabel("authorName", item.getModel())); + final IModel> examinations = + SupervisorGradingPage.this.getExaminations(item.getModel()).orElseGet(Collections::emptyList); - final IModel> nonGradedExaminations = getSpecificExaminations(examinations, false); - item.add(new NonGradedPanel( - "nonGraded", - item.getModel(), - nonGradedExaminations, - Model.of(suggestedDateForNonGradedExaminations()))); + final IModel> nonGradedExaminations = getSpecificExaminations( + examinations, + false + ); + item.add( + new NonGradedPanel( + "nonGraded", + item.getModel(), + nonGradedExaminations, + Model.of(suggestedDateForNonGradedExaminations()) + ) + ); + } } - }); + ); } /** @@ -74,16 +84,20 @@ public class SupervisorGradingPage extends AbstractSupervisorProjectDetailsPage * The suggested date for non-graded examinations is the date the rough draft approval was sent in. */ private LocalDate suggestedDateForNonGradedExaminations() { - return roughDraftApprovalService.findBy(projectModel.getObject()) - .map(ReviewerApproval::getCurrentDecision) - .map(Decision::getRequested) - .map(Date::toInstant) - .map(instant -> instant.atZone(ZoneId.systemDefault())) - .map(ZonedDateTime::toLocalDate) - .orElseGet(LocalDate::now); + return roughDraftApprovalService + .findBy(projectModel.getObject()) + .map(ReviewerApproval::getCurrentDecision) + .map(Decision::getRequested) + .map(Date::toInstant) + .map(instant -> instant.atZone(ZoneId.systemDefault())) + .map(ZonedDateTime::toLocalDate) + .orElseGet(LocalDate::now); } - private IModel> getSpecificExaminations(final IModel> examinations, final boolean graded) { + private IModel> getSpecificExaminations( + final IModel> examinations, + final boolean graded + ) { return new FilteredListModel<>(examinations) { @Override protected boolean accept(final Examination examination) { @@ -97,9 +111,10 @@ public class SupervisorGradingPage extends AbstractSupervisorProjectDetailsPage @Override protected List load() { return gradingService.getExaminations( - getSession().getMetaData(OAuth.TOKEN), - projectModel.getObject().getIdentifier(), - model.getObject().getIdentifier()); + getSession().getMetaData(OAuth.TOKEN), + projectModel.getObject().getIdentifier(), + model.getObject().getIdentifier() + ); } }; } @@ -113,50 +128,57 @@ public class SupervisorGradingPage extends AbstractSupervisorProjectDetailsPage final PageParameters pp = SupervisorGradingPage.getPageParameters(projectModel.getObject()); final String returnUrl = "/" + getRequestCycle().mapUrlFor(SupervisorGradingPage.class, pp).canonical(); getSession().setMetaData(OAuth.RETURN_URL, returnUrl); - final String href = oAuthService.authorizeUrl( - null, - Set.of("grade:read", "grade:write")); + final String href = oAuthService.authorizeUrl(null, Set.of("grade:read", "grade:write")); throw new RedirectToUrlException(href); } } private class NonGradedPanel extends AbstractExaminationsPanel { + public NonGradedPanel( - final String id, - final IModel userModel, - final IModel> nonGradedExaminations, - final IModel suggestedReportDate) - { + final String id, + final IModel userModel, + final IModel> nonGradedExaminations, + final IModel suggestedReportDate + ) { super(id, projectModel, userModel, nonGradedExaminations, suggestedReportDate); } @Override - protected void reportGrade(final Project project, final User author, final Examination examination, final String letter, final LocalDate reported) { + protected void reportGrade( + final Project project, + final User author, + final Examination examination, + final String letter, + final LocalDate reported + ) { final Either result = gradingService.reportGrade( - getSession().getMetaData(OAuth.TOKEN), - project.getIdentifier(), - author.getIdentifier(), - examination.id(), - letter, - reported); + getSession().getMetaData(OAuth.TOKEN), + project.getIdentifier(), + author.getIdentifier(), + examination.id(), + letter, + reported + ); final String feedback = result.fold( - error -> getString(Classes.simpleName(error.getDeclaringClass()) + '.' + error.name()), - success -> "Grade " + letter + " reported for " + author.getFullName()); + error -> getString(Classes.simpleName(error.getDeclaringClass()) + '.' + error.name()), + success -> "Grade " + letter + " reported for " + author.getFullName() + ); if (result.isRight()) { success(feedback); - } - else { + } else { error(feedback); } } } private boolean isGraded(final Examination examination) { - final long passingGrades = examination.grades() - .stream() - .map(Grade::type) - .filter(Grade.Type.PASSING::equals) - .count(); + final long passingGrades = examination + .grades() + .stream() + .map(Grade::type) + .filter(Grade.Type.PASSING::equals) + .count(); return passingGrades > 1; } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPage.java b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPage.java index 2f9ac6b1be..9e2a5c6b97 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPage.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.apache.wicket.Component; import org.apache.wicket.extensions.markup.html.tabs.AbstractTab; import org.apache.wicket.extensions.markup.html.tabs.ITab; @@ -37,123 +43,168 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; - @ProjectModuleComponent(ProjectModule.GRADING) public class SupervisorGradingReportPage extends AbstractSupervisorProjectDetailsPage { + @Inject private NationalSubjectCategoryService nationalSubjectCategoryService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; + @Inject private OAuthService oAuthService; + @Inject private UserService userService; + @Inject private GradingReportService gradingReportService; + @Inject private FinalThesisService finalThesisService; + @Inject private PublicationMetadataService publicationMetadataService; + @Inject private GradingService gradingService; public SupervisorGradingReportPage(PageParameters pp) { super(pp); - - IModel hasApprovedFinalThesis = - projectModel.map(finalThesisService::findByProject) - .filter(ft -> ft.getStatus() == FinalThesis.Status.APPROVED) - .isPresent(); + IModel hasApprovedFinalThesis = projectModel + .map(finalThesisService::findByProject) + .filter(ft -> ft.getStatus() == FinalThesis.Status.APPROVED) + .isPresent(); add(newGreenHighlight("step_final_thesis", hasApprovedFinalThesis, new ResourceModel("step_final_thesis"))); - IModel hasCheckedForPlagiarism = - projectModel.map(finalThesisService::findByProject) - .map(FinalThesis::getTextMatchingDocument) - .isPresent(); + IModel hasCheckedForPlagiarism = projectModel + .map(finalThesisService::findByProject) + .map(FinalThesis::getTextMatchingDocument) + .isPresent(); add(newGreenHighlight("step_plagiarism", hasCheckedForPlagiarism, new ResourceModel("step_plagiarism"))); - IModel hasProvidedPublicationMetadata = Model.of(publicationMetadataService.hasSuppliedPublicationMetadata(projectModel.getObject(), nationalSubjectCategoryService.listCategories().isEmpty())); - add(newGreenHighlight("step_publication_metadata", hasProvidedPublicationMetadata, new ResourceModel("step_publication_metadata"))); + IModel hasProvidedPublicationMetadata = Model.of( + publicationMetadataService.hasSuppliedPublicationMetadata( + projectModel.getObject(), + nationalSubjectCategoryService.listCategories().isEmpty() + ) + ); + add( + newGreenHighlight( + "step_publication_metadata", + hasProvidedPublicationMetadata, + new ResourceModel("step_publication_metadata") + ) + ); IModel> gradingReports = LoadableDetachableModel.of(() -> - gradingReportService.getSupervisorGradingReports(projectModel.getObject())); + gradingReportService.getSupervisorGradingReports(projectModel.getObject()) + ); - IModel generalCriteriaDone = gradingReports - .map(reports -> reports.stream().allMatch(this::generalCriteriaDone)); - add(newGreenHighlight("step_general_criteria", generalCriteriaDone, new ResourceModel("step_general_criteria"))); + IModel generalCriteriaDone = gradingReports.map(reports -> + reports.stream().allMatch(this::generalCriteriaDone) + ); + add( + newGreenHighlight("step_general_criteria", generalCriteriaDone, new ResourceModel("step_general_criteria")) + ); - IModel individualCriteriaDone = gradingReports - .map(reports -> reports.stream().allMatch(this::individualCriteriaDone)); - add(newGreenHighlight("step_individual_criteria", individualCriteriaDone, new ResourceModel("step_individual_criteria"))); - add(new ListView<>("step_individual_criteria_author", gradingReports) { - @Override - protected void populateItem(ListItem item) { - IModel individualCriteriaDone = item.getModel().map(SupervisorGradingReportPage.this::individualCriteriaDone); - item.add(newGreenHighlight("author", individualCriteriaDone, item.getModel().map(SupervisorGradingReport::getUser).map(User::getFullName))); + IModel individualCriteriaDone = gradingReports.map(reports -> + reports.stream().allMatch(this::individualCriteriaDone) + ); + add( + newGreenHighlight( + "step_individual_criteria", + individualCriteriaDone, + new ResourceModel("step_individual_criteria") + ) + ); + add( + new ListView<>("step_individual_criteria_author", gradingReports) { + @Override + protected void populateItem(ListItem item) { + IModel individualCriteriaDone = item + .getModel() + .map(SupervisorGradingReportPage.this::individualCriteriaDone); + item.add( + newGreenHighlight( + "author", + individualCriteriaDone, + item.getModel().map(SupervisorGradingReport::getUser).map(User::getFullName) + ) + ); + } } - }); + ); - IModel sentToExaminer = projectModel - .map(project -> project - .getProjectParticipants() - .stream() - .allMatch(this::sentToExaminer)); + IModel sentToExaminer = projectModel.map(project -> + project.getProjectParticipants().stream().allMatch(this::sentToExaminer) + ); add(newGreenHighlight("step_sent_to_examiner", sentToExaminer, new ResourceModel("step_send_to_examiner"))); - add(new ListView<>("step_sent_to_examiner_author", new ListAdapterModel<>(projectModel.map(Project::getProjectParticipants))) { - @Override - protected void populateItem(ListItem item) { - IModel sentToExaminer = item.getModel().map(SupervisorGradingReportPage.this::sentToExaminer); - item.add(newGreenHighlight("author", sentToExaminer, item.getModel().map(User::getFullName))); + add( + new ListView<>( + "step_sent_to_examiner_author", + new ListAdapterModel<>(projectModel.map(Project::getProjectParticipants)) + ) { + @Override + protected void populateItem(ListItem item) { + IModel sentToExaminer = item + .getModel() + .map(SupervisorGradingReportPage.this::sentToExaminer); + item.add(newGreenHighlight("author", sentToExaminer, item.getModel().map(User::getFullName))); + } } - }); + ); List tabs = new ArrayList<>(); - tabs.add(createTab(Model.of("Final thesis"), - panelId -> new ApproveFinalThesisPanel(panelId, projectModel))); - tabs.add(createTab(Model.of("Plagiarism"), - panelId -> new UploadTextMatchingPanel(panelId, projectModel))); - tabs.add(createTab(Model.of("Publication metadata"), - panelId -> new PublicationMetadataPanel(panelId, projectModel))); - tabs.add(createTab(Model.of("General criteria"), - panelId -> new GradingBasisPanel(panelId, projectModel))); + tabs.add(createTab(Model.of("Final thesis"), panelId -> new ApproveFinalThesisPanel(panelId, projectModel))); + tabs.add(createTab(Model.of("Plagiarism"), panelId -> new UploadTextMatchingPanel(panelId, projectModel))); + tabs.add( + createTab(Model.of("Publication metadata"), panelId -> new PublicationMetadataPanel(panelId, projectModel)) + ); + tabs.add(createTab(Model.of("General criteria"), panelId -> new GradingBasisPanel(panelId, projectModel))); - List authorTabs = projectModel.getObject() - .getProjectParticipants() - .stream() - .map(author -> new DetachableServiceModel<>(userService, author)) - .map(authorModel -> createTab( - authorModel.map(User::getFullName), - panelId -> new IndividualAuthorAssessmentPanel(panelId, projectModel, authorModel))) - .toList(); + List authorTabs = projectModel + .getObject() + .getProjectParticipants() + .stream() + .map(author -> new DetachableServiceModel<>(userService, author)) + .map(authorModel -> + createTab(authorModel.map(User::getFullName), panelId -> + new IndividualAuthorAssessmentPanel(panelId, projectModel, authorModel) + ) + ) + .toList(); tabs.addAll(authorTabs); TabbedPanel tabbedPanel = new BootstrapCardTabbedPanel<>("tabs", tabs); add(tabbedPanel); List interactTabs = new ArrayList<>(); - interactTabs.add(createTab(Model.of("Interact with reviewer"), - panelId -> new TimelinePanel(panelId, projectModel))); - interactTabs.add(createTab(Model.of("Interactions with examiner"), - panelId -> new ExaminerTimelinePanel(panelId, projectModel))); + interactTabs.add( + createTab(Model.of("Interact with reviewer"), panelId -> new TimelinePanel(panelId, projectModel)) + ); + interactTabs.add( + createTab(Model.of("Interactions with examiner"), panelId -> + new ExaminerTimelinePanel(panelId, projectModel) + ) + ); TabbedPanel tabbedPanelInteract = new BootstrapCardTabbedPanel<>("interact", interactTabs); add(tabbedPanelInteract); - final String externalGradingURL = generalSystemSettingsService.getGeneralSystemSettingsInstance().getExternalGradingURL(); - add(new ExternalLink("moreInformation", externalGradingURL) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null); + final String externalGradingURL = generalSystemSettingsService + .getGeneralSystemSettingsInstance() + .getExternalGradingURL(); + add( + new ExternalLink("moreInformation", externalGradingURL) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getDefaultModelObject() != null); + } } - }); - + ); } private Component newGreenHighlight(String id, IModel completed, IModel text) { @@ -161,29 +212,44 @@ public class SupervisorGradingReportPage extends AbstractSupervisorProjectDetail } private boolean generalCriteriaDone(SupervisorGradingReport supervisorGradingReport) { - boolean criteriaMet = supervisorGradingReport.getProjectCriteria() - .stream() - .allMatch(GradingCriterion::meetsMinimumPointRequirement); - return criteriaMet && supervisorGradingReport.hasProvidedRejectionFeedback() && supervisorGradingReport.hasProvidedOverallMotivation(); + boolean criteriaMet = supervisorGradingReport + .getProjectCriteria() + .stream() + .allMatch(GradingCriterion::meetsMinimumPointRequirement); + return ( + criteriaMet && + supervisorGradingReport.hasProvidedRejectionFeedback() && + supervisorGradingReport.hasProvidedOverallMotivation() + ); } private boolean individualCriteriaDone(SupervisorGradingReport supervisorGradingReport) { - return supervisorGradingReport.getIndividualCriteria() - .stream() - .allMatch(GradingCriterion::meetsMinimumPointRequirement); + return supervisorGradingReport + .getIndividualCriteria() + .stream() + .allMatch(GradingCriterion::meetsMinimumPointRequirement); } private boolean sentToExaminer(User author) { String token = getSession().getMetaData(OAuth.TOKEN); Project project = projectModel.getObject(); - List examinations = gradingService.getExaminations(token, project.getIdentifier(), author.getIdentifier()); + List examinations = gradingService.getExaminations( + token, + project.getIdentifier(), + author.getIdentifier() + ); if (examinations == null) { // if grading service is down, assume not sent return false; } for (Examination examination : examinations) { if (examination.hasManyPassingGrades()) { - Either> result = gradingService.getResult(token, project.getIdentifier(), author.getIdentifier(), examination.id()); + Either> result = gradingService.getResult( + token, + project.getIdentifier(), + author.getIdentifier(), + examination.id() + ); if (result.isRight() && result.right().isEmpty()) { return false; } @@ -208,11 +274,10 @@ public class SupervisorGradingReportPage extends AbstractSupervisorProjectDetail final boolean validToken = expiration != null && expiration.isAfter(Instant.now()); if (!validToken) { final PageParameters pp = SupervisorGradingPage.getPageParameters(projectModel.getObject()); - final String returnUrl = "/" + getRequestCycle().mapUrlFor(SupervisorGradingReportPage.class, pp).canonical(); + final String returnUrl = + "/" + getRequestCycle().mapUrlFor(SupervisorGradingReportPage.class, pp).canonical(); getSession().setMetaData(OAuth.RETURN_URL, returnUrl); - final String href = oAuthService.authorizeUrl( - null, - Set.of("grade:read", "grade:write")); + final String href = oAuthService.authorizeUrl(null, Set.of("grade:read", "grade:write")); throw new RedirectToUrlException(href); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPdf.java b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPdf.java index 92ebbd6b23..0b196ef740 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPdf.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/SupervisorGradingReportPdf.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.finalthesis.FinalThesis; import se.su.dsv.scipro.report.GradingCriterion; @@ -10,13 +16,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.User; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - public class SupervisorGradingReportPdf implements GradingReportPdf { private final IModel supervisorGradingReport; @@ -25,11 +24,11 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { private final IModel finalThesis; public SupervisorGradingReportPdf( - IModel supervisorGradingReport, - IModel reflection, - IModel roughDraftApproval, - IModel finalThesis) - { + IModel supervisorGradingReport, + IModel reflection, + IModel roughDraftApproval, + IModel finalThesis + ) { this.supervisorGradingReport = supervisorGradingReport; this.reflection = reflection; this.roughDraftApproval = roughDraftApproval; @@ -51,8 +50,7 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { case MAGISTER -> "Magister"; case MASTER -> "Master"; }; - } - else { + } else { return switch (degreeType) { case NONE -> "Unknown"; case BACHELOR -> "Bachelor"; @@ -64,9 +62,9 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { @Override public boolean isSwedish() { - return supervisorGradingReport.getObject().getReportLanguage() == Language.SWEDISH; + return (supervisorGradingReport.getObject().getReportLanguage() == Language.SWEDISH); } - + @Override public String getAuthorName() { return supervisorGradingReport.getObject().getUser().getFullName(); @@ -74,11 +72,13 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { @Override public String getAuthorNames() { - return supervisorGradingReport.getObject().getProject() - .getProjectParticipants() - .stream() - .map(User::getFullName) - .collect(Collectors.joining(", ")); + return supervisorGradingReport + .getObject() + .getProject() + .getProjectParticipants() + .stream() + .map(User::getFullName) + .collect(Collectors.joining(", ")); } @Override @@ -132,10 +132,11 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { StringBuilder decisions = new StringBuilder(); if (history != null) { for (Decision decision : history) { - decisions.append(new SimpleDateFormat("yyyy-MM-dd").format(decision.getDecisionDate())) - .append("\n") - .append(decision.getReason()) - .append("\n\n"); + decisions + .append(new SimpleDateFormat("yyyy-MM-dd").format(decision.getDecisionDate())) + .append("\n") + .append(decision.getReason()) + .append("\n\n"); } } return decisions.toString(); @@ -148,10 +149,13 @@ public class SupervisorGradingReportPdf implements GradingReportPdf { @Override public int getPointTotal() { - return supervisorGradingReport.getObject().getGradingCriteria().stream() - .map(GradingCriterion::getPoints) - .filter(Objects::nonNull) - .mapToInt(points -> points) - .sum(); + return supervisorGradingReport + .getObject() + .getGradingCriteria() + .stream() + .map(GradingCriterion::getPoints) + .filter(Objects::nonNull) + .mapToInt(points -> points) + .sum(); } } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/TemplatePanel.java b/view/src/main/java/se/su/dsv/scipro/grading/TemplatePanel.java index 9ae19041bd..d314162b13 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/TemplatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/TemplatePanel.java @@ -37,31 +37,36 @@ public class TemplatePanel extends Panel { } private void addTemplates(final DegreeType degreeType, final WebMarkupContainer container) { - container.add(new WebMarkupContainer(BACHELOR_CONTAINER) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(degreeType == DegreeType.BACHELOR); + container.add( + new WebMarkupContainer(BACHELOR_CONTAINER) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(degreeType == DegreeType.BACHELOR); + } } - }); - container.add(new WebMarkupContainer(MASTER_15_CONTAINER) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(degreeType == DegreeType.MAGISTER); + ); + container.add( + new WebMarkupContainer(MASTER_15_CONTAINER) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(degreeType == DegreeType.MAGISTER); + } } - }); - container.add(new WebMarkupContainer(MASTER_30_CONTAINER) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(degreeType == DegreeType.MASTER); + ); + container.add( + new WebMarkupContainer(MASTER_30_CONTAINER) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(degreeType == DegreeType.MASTER); + } } - }); + ); } private int getYear(final Project project) { return project.getStartDate().getYear(); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedPanel.java index 28abad67a2..f8c1e9f4e2 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/ThesisApprovedPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; @@ -14,13 +15,13 @@ import se.su.dsv.scipro.report.GradingReportService; import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; - public class ThesisApprovedPanel extends GenericPanel { + private static final String FILE_PANEL = "filePanel"; @Inject private FinalThesisService finalThesisService; + @Inject private GradingReportService gradingReportService; @@ -29,22 +30,24 @@ public class ThesisApprovedPanel extends GenericPanel { final IModel thesisDocument = getFileDescription(); add(new ViewAttachmentPanel(FILE_PANEL, thesisDocument, DateStyle.DATETIME)); add(new UrkundSubmissionPanel("plagiarismReport", thesisDocument)); - add(new Link<>("reject", project) { - { - add(new JavascriptEventConfirmation("click", new ResourceModel("remove.approved"))); - } + add( + new Link<>("reject", project) { + { + add(new JavascriptEventConfirmation("click", new ResourceModel("remove.approved"))); + } - @Override - public void onClick() { - finalThesisService.removeApproval(getModelObject()); - } + @Override + public void onClick() { + finalThesisService.removeApproval(getModelObject()); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(finalThesisService.canReject(getModelObject())); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(finalThesisService.canReject(getModelObject())); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingPanel.java b/view/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingPanel.java index 761c7094ea..9b6d646b3b 100644 --- a/view/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/grading/UploadTextMatchingPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.grading; +import jakarta.inject.Inject; +import java.util.HashSet; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.feedback.FencedFeedbackPanel; @@ -32,21 +34,19 @@ import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.Ajax; -import jakarta.inject.Inject; -import java.util.HashSet; - public class UploadTextMatchingPanel extends GenericPanel { @Inject private FinalThesisService finalThesisService; + @Inject private FileService fileDescriptionService; + @Inject private ProjectForumService projectForumService; public UploadTextMatchingPanel(final String id, final IModel projectModel) { super(id, projectModel); - final IModel finalThesisModel = new LoadableDetachableModel<>() { @Override protected FinalThesis load() { @@ -59,35 +59,41 @@ public class UploadTextMatchingPanel extends GenericPanel { add(new UploadPlagiarismAnalysisForm("form", finalThesisModel)); IModel textMatchingDocument = finalThesisModel.map(FinalThesis::getTextMatchingDocument); - add(new ViewAttachmentPanel( - "textMatchingDocument", - textMatchingDocument.map(FileReference::getFileDescription))); + add( + new ViewAttachmentPanel("textMatchingDocument", textMatchingDocument.map(FileReference::getFileDescription)) + ); add(new Label("text_matching_analysis", finalThesisModel.map(FinalThesis::getTextMatchingAnalysis))); - add(new Link<>("remove", finalThesisModel) { - @Override - public void onClick() { - finalThesisService.removePlagiarismAnalysis(getModelObject()); - success(getString("plagiarism_analysis_removed")); - } + add( + new Link<>("remove", finalThesisModel) { + @Override + public void onClick() { + finalThesisService.removePlagiarismAnalysis(getModelObject()); + success(getString("plagiarism_analysis_removed")); + } - @Override - protected void onConfigure() { - super.onConfigure(); - boolean canRemovePlagiarismAnalysis = finalThesisService.canRemovePlagiarismAnalysis(getModelObject()); - setVisibilityAllowed(canRemovePlagiarismAnalysis); - setVisible(textMatchingDocument.isPresent().getObject()); + @Override + protected void onConfigure() { + super.onConfigure(); + boolean canRemovePlagiarismAnalysis = finalThesisService.canRemovePlagiarismAnalysis( + getModelObject() + ); + setVisibilityAllowed(canRemovePlagiarismAnalysis); + setVisible(textMatchingDocument.isPresent().getObject()); + } } - }); + ); - add(new WebMarkupContainer("help") { - @Override - protected void onConfigure() { - super.onConfigure(); - FinalThesis finalThesis = finalThesisModel.getObject(); - setVisible(finalThesis == null || finalThesis.getTextMatchingDocument() == null); + add( + new WebMarkupContainer("help") { + @Override + protected void onConfigure() { + super.onConfigure(); + FinalThesis finalThesis = finalThesisModel.getObject(); + setVisible(finalThesis == null || finalThesis.getTextMatchingDocument() == null); + } } - }); + ); } private class UploadPlagiarismAnalysisForm extends StatelessForm { @@ -98,8 +104,9 @@ public class UploadTextMatchingPanel extends GenericPanel { public UploadPlagiarismAnalysisForm(String id, IModel finalThesisModel) { super(id, finalThesisModel); - - IModel finalThesisDocument = finalThesisModel.map(FinalThesis::getDocument).map(FileReference::getFileDescription); + IModel finalThesisDocument = finalThesisModel + .map(FinalThesis::getDocument) + .map(FileReference::getFileDescription); add(new ViewAttachmentPanel("final_thesis_document", finalThesisDocument)); add(new UrkundSubmissionPanel("text_matching_report", finalThesisDocument)); @@ -123,41 +130,51 @@ public class UploadTextMatchingPanel extends GenericPanel { plagiarismDetected.setOutputMarkupPlaceholderTag(true); add(plagiarismDetected); - buttons.add(new ClientValidatingSubmitLink("no_plagiarism") { - @Override - public void onSubmit() { - noPlagiarismDetected(); + buttons.add( + new ClientValidatingSubmitLink("no_plagiarism") { + @Override + public void onSubmit() { + noPlagiarismDetected(); + } } - }); + ); - buttons.add(new AjaxLink<>("plagiarism_detected") { - @Override - public void onClick(AjaxRequestTarget target) { - target.add(buttons); - buttons.setVisible(false); - Ajax.show(plagiarismDetected, target); + buttons.add( + new AjaxLink<>("plagiarism_detected") { + @Override + public void onClick(AjaxRequestTarget target) { + target.add(buttons); + buttons.setVisible(false); + Ajax.show(plagiarismDetected, target); + } } - }); + ); includeTextMatchingDocumentInStudentFeedback = new CheckBox( - "include_text_matching_document_in_student_feedback", Model.of(false)); + "include_text_matching_document_in_student_feedback", + Model.of(false) + ); plagiarismDetected.add(includeTextMatchingDocumentInStudentFeedback); - plagiarismDetected.add(new ClientValidatingSubmitLink("send_feedback_to_students") { - @Override - public void onSubmit() { - minorPlagiarismDetected(); + plagiarismDetected.add( + new ClientValidatingSubmitLink("send_feedback_to_students") { + @Override + public void onSubmit() { + minorPlagiarismDetected(); + } } - }); + ); - plagiarismDetected.add(new AjaxLink<>("cancel") { - @Override - public void onClick(AjaxRequestTarget target) { - target.add(plagiarismDetected); - plagiarismDetected.setVisible(false); - Ajax.show(buttons, target); + plagiarismDetected.add( + new AjaxLink<>("cancel") { + @Override + public void onClick(AjaxRequestTarget target) { + target.add(plagiarismDetected); + plagiarismDetected.setVisible(false); + Ajax.show(buttons, target); + } } - }); + ); } @Override @@ -171,10 +188,10 @@ public class UploadTextMatchingPanel extends GenericPanel { private void noPlagiarismDetected() { final String comment = commentField.getModelObject(); - final FileUpload fileUpload = - textMatchingDocumentField.getFileUpload(); - final FileReference textMatchingDocument = - fileDescriptionService.storeFile(new WicketFileUpload(fileUpload)); + final FileUpload fileUpload = textMatchingDocumentField.getFileUpload(); + final FileReference textMatchingDocument = fileDescriptionService.storeFile( + new WicketFileUpload(fileUpload) + ); final FinalThesis finalThesis = getModelObject(); finalThesis.setTextMatchingDocument(textMatchingDocument); finalThesis.setTextMatchingAnalysis(comment); diff --git a/view/src/main/java/se/su/dsv/scipro/group/AbstractAuthorGroupPage.java b/view/src/main/java/se/su/dsv/scipro/group/AbstractAuthorGroupPage.java index 7e03b022ec..1fea8c9e54 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/AbstractAuthorGroupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/group/AbstractAuthorGroupPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import jakarta.servlet.http.Cookie; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.http.WebResponse; @@ -17,9 +19,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import jakarta.servlet.http.Cookie; - @SystemModuleComponent(SystemModule.GROUP) public abstract class AbstractAuthorGroupPage extends ProjectPage implements MenuHighlightAuthorMyGroups { @@ -48,7 +47,7 @@ public abstract class AbstractAuthorGroupPage extends ProjectPage implements Men private void initializeGroup(PageParameters pp) { StringValue value = pp.get(PageParameterKeys.MAP.get(Group.class)); Long groupId = null; - if(!value.isNull()) { + if (!value.isNull()) { groupId = value.toLongObject(); } if (groupId == null) { @@ -61,8 +60,8 @@ public abstract class AbstractAuthorGroupPage extends ProjectPage implements Men } else { /* * Cookie is set when the link to visit this details page is clicked but for it to work - * if a URL is entered directly we set it here too - */ + * if a URL is entered directly we set it here too + */ Cookie c = new Cookie(COOKIE_KEY, groupId.toString()); c.setMaxAge(MAX_AGE); c.setPath("/"); diff --git a/view/src/main/java/se/su/dsv/scipro/group/AuthorGroupPage.java b/view/src/main/java/se/su/dsv/scipro/group/AuthorGroupPage.java index d676271296..cfcac3c98d 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/AuthorGroupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/group/AuthorGroupPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -12,11 +16,6 @@ import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.panels.threaded.ThreadsOverviewPanel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - public class AuthorGroupPage extends AbstractAuthorGroupPage implements MenuHighlightAuthorMyGroups { @Inject @@ -26,12 +25,15 @@ public class AuthorGroupPage extends AbstractAuthorGroupPage implements MenuHigh super(pp); add(new FeedbackPanel("feedback")); add(new BookmarkablePageLink("createThread", CreateThreadPage.class, pp)); - add(new ThreadsOverviewPanel<>("threads", getThreads(), new GroupThreadDiscussable(), - (id, thread) -> { - PageParameters parameters = new PageParameters(pp) - .set(PageParameterKeys.MAP.get(ForumThread.class), thread.getObject().getId()); - return new BookmarkablePageLink<>(id, ViewThreadPage.class, parameters); - })); + add( + new ThreadsOverviewPanel<>("threads", getThreads(), new GroupThreadDiscussable(), (id, thread) -> { + PageParameters parameters = new PageParameters(pp).set( + PageParameterKeys.MAP.get(ForumThread.class), + thread.getObject().getId() + ); + return new BookmarkablePageLink<>(id, ViewThreadPage.class, parameters); + }) + ); } private IModel> getThreads() { diff --git a/view/src/main/java/se/su/dsv/scipro/group/AuthorMyGroupsPage.java b/view/src/main/java/se/su/dsv/scipro/group/AuthorMyGroupsPage.java index 2bb8a2aa46..9b7839e491 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/AuthorMyGroupsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/group/AuthorMyGroupsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; @@ -22,10 +25,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - @SystemModuleComponent(SystemModule.GROUP) public class AuthorMyGroupsPage extends ProjectPage implements MenuHighlightAuthorMyGroups { @@ -34,13 +33,12 @@ public class AuthorMyGroupsPage extends ProjectPage implements MenuHighlightAuth public AuthorMyGroupsPage(PageParameters pp) { super(pp); - GroupService.Filter forwardFilter = new GroupService.Filter(); forwardFilter.setAuthor(loggedInUser()); forwardFilter.setActive(true); List groups = groupService.findAll(forwardFilter); - if (groups.size() == 1){ + if (groups.size() == 1) { PageParameters forwardPP = new PageParameters(); forwardPP.add(PageParameterKeys.MAP.get(Group.class), groups.get(0).getId()); setResponsePage(AuthorGroupPage.class, forwardPP); @@ -58,19 +56,31 @@ public class AuthorMyGroupsPage extends ProjectPage implements MenuHighlightAuth columns.add(new DateColumn<>(Model.of("Date created"), Group::getDateCreated, "dateCreated", DateStyle.DATE)); - columns.add(new AbstractColumn<>(Model.of("Title"), "title") { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new AjaxLinkPanel<>(componentId, rowModel, LambdaModel.of(rowModel, Group::getTitle, Group::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Group.class), model.getObject().getId()); - setResponsePage(AuthorGroupPage.class, pp); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Title"), "title") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new AjaxLinkPanel<>( + componentId, + rowModel, + LambdaModel.of(rowModel, Group::getTitle, Group::setTitle) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Group.class), model.getObject().getId()); + setResponsePage(AuthorGroupPage.class, pp); + } + } + ); + } } - }); + ); return columns; } diff --git a/view/src/main/java/se/su/dsv/scipro/group/CreateThreadPage.java b/view/src/main/java/se/su/dsv/scipro/group/CreateThreadPage.java index 1acdcfcb6d..ade7642cc5 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/CreateThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/group/CreateThreadPage.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorMyGroups; import se.su.dsv.scipro.forum.GroupForumService; -import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.panels.threaded.SubmitForumThreadPanel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class CreateThreadPage extends AbstractAuthorGroupPage implements MenuHighlightAuthorMyGroups { @Inject @@ -17,13 +16,17 @@ public class CreateThreadPage extends AbstractAuthorGroupPage implements MenuHig public CreateThreadPage(final PageParameters parameters) { super(parameters); - add(new SubmitForumThreadPanel<>("form", new GroupForum(groupForumService, getGroup())) { - @Override - public void onThreadCreated(final GroupThread thread) { - PageParameters pp = new PageParameters(parameters) - .set(PageParameterKeys.MAP.get(ForumThread.class), thread.getId()); - setResponsePage(ViewThreadPage.class, pp); + add( + new SubmitForumThreadPanel<>("form", new GroupForum(groupForumService, getGroup())) { + @Override + public void onThreadCreated(final GroupThread thread) { + PageParameters pp = new PageParameters(parameters).set( + PageParameterKeys.MAP.get(ForumThread.class), + thread.getId() + ); + setResponsePage(ViewThreadPage.class, pp); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/group/EditGroupPanel.java b/view/src/main/java/se/su/dsv/scipro/group/EditGroupPanel.java index 4b13a106ae..853cedc848 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/EditGroupPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/group/EditGroupPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -27,15 +29,14 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class EditGroupPanel extends Panel { @Inject private ProjectService projectService; + @Inject private GroupService groupService; + @Inject private ProjectTypeService projectTypeService; @@ -53,7 +54,6 @@ public class EditGroupPanel extends Panel { public GroupForm(String form, final IModel model) { super(form, model); - final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback"); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); @@ -62,7 +62,9 @@ public class EditGroupPanel extends Panel { add(new RequiredTextField<>("title", LambdaModel.of(model, Group::getTitle, Group::setTitle))); add(new TextArea<>("description", LambdaModel.of(model, Group::getDescription, Group::setDescription))); - add(new CheckBox("active", LambdaModel.of(model, Group::isActive, Group::setActive)).setOutputMarkupId(true)); + add( + new CheckBox("active", LambdaModel.of(model, Group::isActive, Group::setActive)).setOutputMarkupId(true) + ); final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); @@ -70,7 +72,12 @@ public class EditGroupPanel extends Panel { projectTypes = projectTypeSelection(wmc); wmc.add(projectTypes); - addProjects = new AjaxDropDownChoice<>("addProjects", new Model<>(), getSelectableProjects(currentProjects), new LambdaChoiceRenderer<>(Project::getTitle, Project::getId)) { + addProjects = new AjaxDropDownChoice<>( + "addProjects", + new Model<>(), + getSelectableProjects(currentProjects), + new LambdaChoiceRenderer<>(Project::getTitle, Project::getId) + ) { @Override public void onNewSelection(AjaxRequestTarget target, Project objectSelected) { if (objectSelected != null && !currentProjects.contains(objectSelected)) { @@ -90,40 +97,53 @@ public class EditGroupPanel extends Panel { protected void populateItem(final ListItem item) { item.add(new Label("type", item.getModel().map(Project::getProjectTypeName))); item.add(new Label("title", item.getModel().map(Project::getTitle))); - item.add(new ListView<>("authors", new ListAdapterModel<>(getLoaded(item.getModelObject()).map(Project::getProjectParticipants))) { - @Override - public void populateItem(ListItem item) { - item.add(new UserLinkPanel("author", item.getModel())); + item.add( + new ListView<>( + "authors", + new ListAdapterModel<>( + getLoaded(item.getModelObject()).map(Project::getProjectParticipants) + ) + ) { + @Override + public void populateItem(ListItem item) { + item.add(new UserLinkPanel("author", item.getModel())); + } } - }); - item.add(new AjaxLink<>("remove", item.getModel()) { - @Override - public void onClick(AjaxRequestTarget target) { - currentProjects.remove(item.getModelObject()); - projects.setList(currentProjects); - addProjects.setChoices(getSelectableProjects(currentProjects)); - target.add(wmc); + ); + item.add( + new AjaxLink<>("remove", item.getModel()) { + @Override + public void onClick(AjaxRequestTarget target) { + currentProjects.remove(item.getModelObject()); + projects.setList(currentProjects); + addProjects.setChoices(getSelectableProjects(currentProjects)); + target.add(wmc); + } } - }); + ); } }; wmc.add(projects); - wmc.add(new Label("noProjects", "None"){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(currentProjects.isEmpty()); + wmc.add( + new Label("noProjects", "None") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(currentProjects.isEmpty()); + } } - }); + ); add(wmc); - } private AjaxCheckBoxMultipleChoice projectTypeSelection(final WebMarkupContainer wmc) { - return new AjaxCheckBoxMultipleChoice<>("projectTypes", projectTypeService.findAllActive(), - projectTypeService.findAllActive(), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + return new AjaxCheckBoxMultipleChoice<>( + "projectTypes", + projectTypeService.findAllActive(), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) ) { @Override public void onUpdate(AjaxRequestTarget target) { @@ -141,7 +161,7 @@ public class EditGroupPanel extends Panel { info(getString("saved")); } - private ListModel getSelectableProjects(List currentProjects){ + private ListModel getSelectableProjects(List currentProjects) { final ProjectService.Filter filter = new ProjectService.Filter(); filter.setSupervisor(SciProSession.get().getUser()); filter.setRoles(Collections.singleton(ProjectTeamMemberRoles.CO_SUPERVISOR)); @@ -153,7 +173,7 @@ public class EditGroupPanel extends Panel { return new ListModel<>(all); } - private LoadableDetachableModel getLoaded(final Project project){ + private LoadableDetachableModel getLoaded(final Project project) { return new LoadableDetachableModel<>() { @Override protected Project load() { @@ -163,4 +183,3 @@ public class EditGroupPanel extends Panel { } } } - diff --git a/view/src/main/java/se/su/dsv/scipro/group/GroupDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/group/GroupDetailsPanel.java index 717887533c..c24e55f294 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/GroupDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/group/GroupDetailsPanel.java @@ -22,7 +22,6 @@ public class GroupDetailsPanel extends Panel { public GroupDetailsPanel(String id, final IModel model) { super(id, model); - modalWindowPlus = new LargeModalWindow("dialog"); add(modalWindowPlus); @@ -30,25 +29,34 @@ public class GroupDetailsPanel extends Panel { PageParameters pp = new PageParameters(); pp.add(PageParameterKeys.MAP.get(Group.class), String.valueOf(model.getObject().getId())); - add(new BookmarkablePageLink("edit", SupervisorEditGroupPage.class, pp){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(model.getObject().getUser().equals(SciProSession.get().getUser())); + add( + new BookmarkablePageLink("edit", SupervisorEditGroupPage.class, pp) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(model.getObject().getUser().equals(SciProSession.get().getUser())); + } } - }); + ); - add(new DateLabel("created", LambdaModel.of(model, Group::getDateCreated, Group::setDateCreated), DateStyle.DATE)); + add( + new DateLabel( + "created", + LambdaModel.of(model, Group::getDateCreated, Group::setDateCreated), + DateStyle.DATE + ) + ); add(new Label("active", model.getObject().isActive() ? "(Active)" : "(Inactive)")); - add(new AjaxLink<>("viewProjects", model) { - @Override - public void onClick(AjaxRequestTarget target) { - modalWindowPlus.setContent(new ViewGroupProjectsPanel(modalWindowPlus.getContentId(), model)); - modalWindowPlus.setTitle("Group: " + model.getObject().getTitle()); - modalWindowPlus.show(target); + add( + new AjaxLink<>("viewProjects", model) { + @Override + public void onClick(AjaxRequestTarget target) { + modalWindowPlus.setContent(new ViewGroupProjectsPanel(modalWindowPlus.getContentId(), model)); + modalWindowPlus.setTitle("Group: " + model.getObject().getTitle()); + modalWindowPlus.show(target); + } } - }); + ); add(new Label("description", LambdaModel.of(model, Group::getDescription, Group::setDescription))); } } - diff --git a/view/src/main/java/se/su/dsv/scipro/group/GroupForum.java b/view/src/main/java/se/su/dsv/scipro/group/GroupForum.java index 44c153078e..eff7081ab4 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/GroupForum.java +++ b/view/src/main/java/se/su/dsv/scipro/group/GroupForum.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.group; +import java.util.*; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.Forum; @@ -7,9 +8,8 @@ import se.su.dsv.scipro.forum.GroupForumService; import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.system.User; -import java.util.*; - public class GroupForum implements Forum { + private final GroupForumService groupForumService; private final IModel groupModel; @@ -19,15 +19,14 @@ public class GroupForum implements Forum { } @Override - public GroupThread createThread(final User user, final String subject, final String content, final Set attachments) { + public GroupThread createThread( + final User user, + final String subject, + final String content, + final Set attachments + ) { Group group = groupModel.getObject(); - return groupForumService.createThread( - group, - user, - subject, - content, - attachments); + return groupForumService.createThread(group, user, subject, content, attachments); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/group/GroupForumThread.java b/view/src/main/java/se/su/dsv/scipro/group/GroupForumThread.java index b37be08d32..9d50b82678 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/GroupForumThread.java +++ b/view/src/main/java/se/su/dsv/scipro/group/GroupForumThread.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.group; +import java.util.*; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.ForumThread; import se.su.dsv.scipro.forum.GroupForumService; @@ -7,9 +8,8 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.system.User; -import java.util.*; - public class GroupForumThread implements ForumThread { + private final GroupForumService groupForumService; public GroupForumThread(final GroupForumService groupForumService) { @@ -22,7 +22,12 @@ public class GroupForumThread implements ForumThread { } @Override - public ForumPost reply(final GroupThread groupThread, final User poster, final String content, final Set attachments) { + public ForumPost reply( + final GroupThread groupThread, + final User poster, + final String content, + final Set attachments + ) { return groupForumService.createReply(groupThread, poster, content, attachments); } diff --git a/view/src/main/java/se/su/dsv/scipro/group/GroupThreadDiscussable.java b/view/src/main/java/se/su/dsv/scipro/group/GroupThreadDiscussable.java index 469ab5c817..bbc44715b7 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/GroupThreadDiscussable.java +++ b/view/src/main/java/se/su/dsv/scipro/group/GroupThreadDiscussable.java @@ -6,6 +6,7 @@ import se.su.dsv.scipro.forum.Discussable; import se.su.dsv.scipro.forum.dataobjects.*; public class GroupThreadDiscussable implements Discussable { + @Override public IModel discussion(final IModel a) { return LambdaModel.of(a, GroupThread::getForumThread, GroupThread::setForumThread); diff --git a/view/src/main/java/se/su/dsv/scipro/group/GroupsOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/group/GroupsOverviewPanel.java index 5331e1ac45..d49c5fbad8 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/GroupsOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/group/GroupsOverviewPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import java.io.Serializable; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -12,10 +15,6 @@ import se.su.dsv.scipro.security.auth.SystemModuleComponent; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.io.Serializable; -import java.util.List; - @SystemModuleComponent(SystemModule.GROUP) public class GroupsOverviewPanel extends GenericPanel { @@ -24,17 +23,18 @@ public class GroupsOverviewPanel extends GenericPanel { public GroupsOverviewPanel(String id, IModel model, final GroupLinkSupplier linkSupplier) { super(id, model); - - add(new AutoHidingListView<>("groupList", getGroups()) { - @Override - protected void populateItem(ListItem item) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Group.class), item.getModelObject().getId()); - BookmarkablePageLink link = linkSupplier.newGroupLink("groupLink", pp); - link.setBody(item.getModel().map(Group::getTitle)); - item.add(link); + add( + new AutoHidingListView<>("groupList", getGroups()) { + @Override + protected void populateItem(ListItem item) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Group.class), item.getModelObject().getId()); + BookmarkablePageLink link = linkSupplier.newGroupLink("groupLink", pp); + link.setBody(item.getModel().map(Group::getTitle)); + item.add(link); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/group/ViewGroupProjectsPanel.java b/view/src/main/java/se/su/dsv/scipro/group/ViewGroupProjectsPanel.java index dc32ef6c2a..75b36465cb 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/ViewGroupProjectsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/group/ViewGroupProjectsPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; +import java.util.Optional; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -22,57 +24,78 @@ import se.su.dsv.scipro.supervisor.pages.SupervisorProjectDetailsPage; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Optional; - public class ViewGroupProjectsPanel extends GenericPanel { @Inject ReceiverConfigurationService receiverConfigurationService; + @Inject DeliveryConfigurationService deliveryConfigurationService; public ViewGroupProjectsPanel(String id, final IModel model) { super(id, model); - add(new Label("authorReceiving", mark(isReceiving(Member.Type.AUTHOR)))); add(new Label("headSupervisorReceiving", mark(isReceiving(Member.Type.SUPERVISOR)))); add(new Label("coSupervisorReceiving", mark(isReceiving(Member.Type.CO_SUPERVISOR)))); - add(new ListView<>("projects", new ListAdapterModel<>(LambdaModel.of(model, Group::getProjects, Group::setProjects))) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label("type", item.getModel().map(Project::getProjectTypeName))); - item.add(projectLink(item.getModel())); - item.add(new ListView<>("authors", new ListAdapterModel<>(item.getModel().map(Project::getProjectParticipants))) { - @Override - public void populateItem(ListItem item) { - item.add(new UserLinkPanel("author", item.getModel())); - } - }); - item.add(new UserLinkPanel("headSupervisor", item.getModel().map(Project::getHeadSupervisor))); - item.add(new ListView<>("coSupervisors", new ListAdapterModel<>(item.getModel().map(Project::getCoSupervisors))) { - @Override - public void populateItem(ListItem item) { - item.add(new UserLinkPanel("coSupervisor", item.getModel())); - } - }); + add( + new ListView<>( + "projects", + new ListAdapterModel<>(LambdaModel.of(model, Group::getProjects, Group::setProjects)) + ) { + @Override + protected void populateItem(final ListItem item) { + item.add(new Label("type", item.getModel().map(Project::getProjectTypeName))); + item.add(projectLink(item.getModel())); + item.add( + new ListView<>( + "authors", + new ListAdapterModel<>(item.getModel().map(Project::getProjectParticipants)) + ) { + @Override + public void populateItem(ListItem item) { + item.add(new UserLinkPanel("author", item.getModel())); + } + } + ); + item.add(new UserLinkPanel("headSupervisor", item.getModel().map(Project::getHeadSupervisor))); + item.add( + new ListView<>( + "coSupervisors", + new ListAdapterModel<>(item.getModel().map(Project::getCoSupervisors)) + ) { + @Override + public void populateItem(ListItem item) { + item.add(new UserLinkPanel("coSupervisor", item.getModel())); + } + } + ); + } } - }); + ); - add(new Label("noProjects", "None") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(ViewGroupProjectsPanel.this.getModelObject().getProjects() == null || ViewGroupProjectsPanel.this.getModelObject().getProjects().isEmpty()); + add( + new Label("noProjects", "None") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + ViewGroupProjectsPanel.this.getModelObject().getProjects() == null || + ViewGroupProjectsPanel.this.getModelObject().getProjects().isEmpty() + ); + } } - }); + ); } private BookmarkablePageLink projectLink(IModel model) { PageParameters pp = new PageParameters(); pp.add(PageParameterKeys.MAP.get(Project.class), model.getObject().getId()); - BookmarkablePageLink link = new BookmarkablePageLink<>("titleLink", SupervisorProjectDetailsPage.class, pp); + BookmarkablePageLink link = new BookmarkablePageLink<>( + "titleLink", + SupervisorProjectDetailsPage.class, + pp + ); link.setEnabled(allowedAccess(model)); link.add(new Label("title", LambdaModel.of(model, Project::getTitle, Project::setTitle))); return link; @@ -81,19 +104,37 @@ public class ViewGroupProjectsPanel extends GenericPanel { private boolean allowedAccess(IModel model) { Project project = model.getObject(); User loggedIn = SciProSession.get().getUser(); - return project.isSupervisor(loggedIn) - || project.isCoSupervisor(loggedIn); + return (project.isSupervisor(loggedIn) || project.isCoSupervisor(loggedIn)); } - private boolean isReceiving(final Member.Type member){ - return deliveryConfigurationService.isDelivery(Notification.Type.GROUP, GroupEvent.Event.MESSAGE_THREAD_CREATED, DeliveryMethod.WEB, Optional.empty()) && - deliveryConfigurationService.isDelivery(Notification.Type.GROUP, GroupEvent.Event.MESSAGE_THREAD_REPLY, DeliveryMethod.WEB, Optional.empty()) && - receiverConfigurationService.isReceiving(Notification.Type.GROUP, GroupEvent.Event.MESSAGE_THREAD_CREATED, member) && - receiverConfigurationService.isReceiving(Notification.Type.GROUP, GroupEvent.Event.MESSAGE_THREAD_REPLY, member); + private boolean isReceiving(final Member.Type member) { + return ( + deliveryConfigurationService.isDelivery( + Notification.Type.GROUP, + GroupEvent.Event.MESSAGE_THREAD_CREATED, + DeliveryMethod.WEB, + Optional.empty() + ) && + deliveryConfigurationService.isDelivery( + Notification.Type.GROUP, + GroupEvent.Event.MESSAGE_THREAD_REPLY, + DeliveryMethod.WEB, + Optional.empty() + ) && + receiverConfigurationService.isReceiving( + Notification.Type.GROUP, + GroupEvent.Event.MESSAGE_THREAD_CREATED, + member + ) && + receiverConfigurationService.isReceiving( + Notification.Type.GROUP, + GroupEvent.Event.MESSAGE_THREAD_REPLY, + member + ) + ); } - private String mark(final boolean boo){ + private String mark(final boolean boo) { return boo ? "*" : ""; } } - diff --git a/view/src/main/java/se/su/dsv/scipro/group/ViewThreadPage.java b/view/src/main/java/se/su/dsv/scipro/group/ViewThreadPage.java index fdaaefc9d2..088190a2fe 100644 --- a/view/src/main/java/se/su/dsv/scipro/group/ViewThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/group/ViewThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.group; +import jakarta.inject.Inject; import org.apache.wicket.Component; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -11,25 +12,24 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorMyGroups; import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.forum.BasicForumService; import se.su.dsv.scipro.forum.GroupForumService; -import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.panels.threaded.ViewForumThreadPanel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class ViewThreadPage extends AbstractAuthorGroupPage implements MenuHighlightAuthorMyGroups { @Inject private GroupForumService groupForumService; + @Inject private BasicForumService basicForumService; + @Inject private FileService fileDescriptionService; public ViewThreadPage(final PageParameters parameters) { super(parameters); - final long threadId = parameters.get(PageParameterKeys.MAP.get(ForumThread.class)).toLong(0L); final IModel groupThreadModel = new LoadableDetachableModel<>() { @Override @@ -47,13 +47,16 @@ public class ViewThreadPage extends AbstractAuthorGroupPage implements MenuHighl basicForumService.setThreadRead(loggedInUser(), groupThread.getForumThread(), true); - add(new ViewForumThreadPanel<>("thread", groupThreadModel, new GroupForumThread(groupForumService)) { - @Override - protected Component newBackLink(final String id) { - PageParameters pageParameters = new PageParameters(parameters) - .remove(PageParameterKeys.MAP.get(ForumThread.class)); - return new BookmarkablePageLink(id, AuthorGroupPage.class, pageParameters); + add( + new ViewForumThreadPanel<>("thread", groupThreadModel, new GroupForumThread(groupForumService)) { + @Override + protected Component newBackLink(final String id) { + PageParameters pageParameters = new PageParameters(parameters).remove( + PageParameterKeys.MAP.get(ForumThread.class) + ); + return new BookmarkablePageLink(id, AuthorGroupPage.class, pageParameters); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/icons/ImageObject.java b/view/src/main/java/se/su/dsv/scipro/icons/ImageObject.java index 9cfaf6940b..e8a5c669ce 100755 --- a/view/src/main/java/se/su/dsv/scipro/icons/ImageObject.java +++ b/view/src/main/java/se/su/dsv/scipro/icons/ImageObject.java @@ -12,6 +12,7 @@ import org.apache.wicket.markup.html.image.ContextImage; * 3. Allows for easy swapping between images of different sizes in the code. */ public class ImageObject extends ContextImage { + /** * Path to icon folder in webapp */ diff --git a/view/src/main/java/se/su/dsv/scipro/io/ExcelExporter.java b/view/src/main/java/se/su/dsv/scipro/io/ExcelExporter.java index 5ae3f05dfe..14946fc9a4 100644 --- a/view/src/main/java/se/su/dsv/scipro/io/ExcelExporter.java +++ b/view/src/main/java/se/su/dsv/scipro/io/ExcelExporter.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.io; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; @@ -11,11 +15,6 @@ import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.List; - /** * Using IDataExporter does not currently work as {@link org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn#getHeader(String)} * does not handle {@link org.apache.wicket.model.IComponentAssignedModel} @@ -34,7 +33,11 @@ public class ExcelExporter extends AbstractDataExporter { } @Override - public void exportData(IDataProvider dataProvider, List> columns, OutputStream outputStream) throws IOException { + public void exportData( + IDataProvider dataProvider, + List> columns, + OutputStream outputStream + ) throws IOException { try (Workbook workbook = new XSSFWorkbook()) { Sheet sheet = workbook.createSheet(); addHeaders(sheet, columns); diff --git a/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEvent.java b/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEvent.java index 4b22600083..c51c18116b 100644 --- a/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEvent.java +++ b/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEvent.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.latestevents; -import se.su.dsv.scipro.system.User; - import java.io.Serializable; import java.util.Date; +import se.su.dsv.scipro.system.User; public class LatestEvent implements Serializable { public enum LatestEventType { - FILES, FORUM + FILES, + FORUM, } private Date date; diff --git a/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEventsPanel.java b/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEventsPanel.java index 5a89962c70..66cbc6da08 100644 --- a/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEventsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/latestevents/LatestEventsPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.latestevents; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; @@ -30,9 +32,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import java.util.*; - public class LatestEventsPanel extends Panel { public static final String LATEST_EVENT_CONTAINER = "latestEventsContainer"; @@ -47,6 +46,7 @@ public class LatestEventsPanel extends Panel { @Inject private ProjectFileService projectFileService; + @Inject private ProjectForumService projectForumService; @@ -77,7 +77,6 @@ public class LatestEventsPanel extends Panel { private ListView createLatestEventsListView() { return new ListView<>(LATEST_EVENTS, latestEventModel) { - @Override protected void populateItem(ListItem item) { item.add(new EnumLabel<>(EVENT_TYPE, item.getModel().map(LatestEvent::getType))); @@ -96,7 +95,9 @@ public class LatestEventsPanel extends Panel { } private Component getFileLinkComponent(IModel latestEvent) { - IModel model = latestEvent.map(le -> (ProjectFile) le.getDomainObject()).map(ProjectFile::getFileDescription); + IModel model = latestEvent + .map(le -> (ProjectFile) le.getDomainObject()) + .map(ProjectFile::getFileDescription); FileDownloadLink fileDownloadLink = new FileDownloadLink<>(EVENT_LINK, model); fileDownloadLink.add(new Label(EVENT_TITLE, (latestEvent.map(LatestEvent::getTitle)))); @@ -133,13 +134,29 @@ public class LatestEventsPanel extends Panel { List latestEvents = new ArrayList<>(); if (projectFiles != null) { for (ProjectFile pf : projectFiles) { - latestEvents.add(new LatestEvent(pf.getDateCreated(), LatestEvent.LatestEventType.FILES, pf.getFileDescription().getUploader(), pf.getFileDescription().getName(), pf)); + latestEvents.add( + new LatestEvent( + pf.getDateCreated(), + LatestEvent.LatestEventType.FILES, + pf.getFileDescription().getUploader(), + pf.getFileDescription().getName(), + pf + ) + ); } } if (forumPosts != null) { for (Pair pair : forumPosts) { final ForumPost fp = pair.getTail(); - latestEvents.add(new LatestEvent(fp.getDateCreated(), LatestEvent.LatestEventType.FORUM, fp.getPostedBy(), fp.getSubject(), pair.getHead())); + latestEvents.add( + new LatestEvent( + fp.getDateCreated(), + LatestEvent.LatestEventType.FORUM, + fp.getPostedBy(), + fp.getSubject(), + pair.getHead() + ) + ); } } @@ -158,15 +175,14 @@ public class LatestEventsPanel extends Panel { } private void addNoEvent() { - add(new WebMarkupContainer(NO_EVENT) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(latestEventModel.getObject().isEmpty()); + add( + new WebMarkupContainer(NO_EVENT) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(latestEventModel.getObject().isEmpty()); + } } - }); + ); } - } - - diff --git a/view/src/main/java/se/su/dsv/scipro/log4j/JULAppender.java b/view/src/main/java/se/su/dsv/scipro/log4j/JULAppender.java index b69d9f8e72..393669ba78 100644 --- a/view/src/main/java/se/su/dsv/scipro/log4j/JULAppender.java +++ b/view/src/main/java/se/su/dsv/scipro/log4j/JULAppender.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.log4j; +import java.util.logging.Level; +import java.util.logging.Logger; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; @@ -8,11 +10,9 @@ import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; -import java.util.logging.Level; -import java.util.logging.Logger; - @Plugin(name = "JUL", category = "Core", elementType = "appender", printObject = true) public class JULAppender extends AbstractAppender { + private JULAppender(final String name, final Filter filter) { super(name, filter, null); } @@ -27,11 +27,12 @@ public class JULAppender extends AbstractAppender { final Logger logger = Logger.getLogger(event.getLoggerName()); final StackTraceElement source = event.getSource(); logger.logp( - adaptLevel(event.getLevel()), - source.getClassName(), - source.getMethodName(), - event.getThrown(), - event.getMessage()::getFormattedMessage); + adaptLevel(event.getLevel()), + source.getClassName(), + source.getMethodName(), + event.getThrown(), + event.getMessage()::getFormattedMessage + ); } private static Level adaptLevel(final org.apache.logging.log4j.Level level) { diff --git a/view/src/main/java/se/su/dsv/scipro/log4j/LoggerNameLookup.java b/view/src/main/java/se/su/dsv/scipro/log4j/LoggerNameLookup.java index 6b95709f3f..4b9cdfe592 100644 --- a/view/src/main/java/se/su/dsv/scipro/log4j/LoggerNameLookup.java +++ b/view/src/main/java/se/su/dsv/scipro/log4j/LoggerNameLookup.java @@ -10,6 +10,7 @@ import org.apache.logging.log4j.core.lookup.StrLookup; */ @Plugin(name = "logger", category = "Lookup") public class LoggerNameLookup implements StrLookup { + @Override public String lookup(String key) { return null; @@ -20,8 +21,7 @@ public class LoggerNameLookup implements StrLookup { if (key.equals("simple")) { int last = event.getLoggerName().lastIndexOf('.') + 1; return event.getLoggerName().substring(last); - } - else if (key.equals("qualified")) { + } else if (key.equals("qualified")) { return event.getLoggerName(); } return null; diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPage.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPage.java index 713eee86ff..c04a1d9ec1 100644 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPage.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.loginlogout.pages; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.HashSet; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.form.*; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -10,22 +13,19 @@ import se.su.dsv.scipro.basepages.PublicPage; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.HashSet; - public class FirstTimeRegistrationPage extends PublicPage { @Inject private UserService userService; + @Inject private UserNameService usernameService; + @Inject private PasswordRepo passwordRepo; public FirstTimeRegistrationPage() { super(); - if (userService.count() > 0) { throw new RestartResponseException(getApplication().getHomePage()); } @@ -46,7 +46,6 @@ public class FirstTimeRegistrationPage extends PublicPage { public FirstTimeRegistrationForm(final String id) { super(id); - add(new RequiredTextField<>("firstName", firstName)); add(new RequiredTextField<>("lastName", lastName)); add(new RequiredTextField<>("email", email)); diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LocalLogInPage.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LocalLogInPage.java index 8d63103e5b..caa3fc051c 100644 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LocalLogInPage.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LocalLogInPage.java @@ -4,6 +4,7 @@ import se.su.dsv.scipro.basepages.PublicPage; import se.su.dsv.scipro.loginlogout.panels.LoginPanel; public class LocalLogInPage extends PublicPage { + public LocalLogInPage() { add(new LoginPanel("login")); } diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LoginPage.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LoginPage.java index 75d61a2a78..b569468499 100755 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LoginPage.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LoginPage.java @@ -1,24 +1,23 @@ package se.su.dsv.scipro.loginlogout.pages; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import se.su.dsv.scipro.basepages.PublicPage; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - public class LoginPage extends PublicPage { @Inject private UserService userService; + @Inject private GeneralSystemSettingsService systemSettingsService; public LoginPage() { if (userService.count() == 0) { setResponsePage(FirstTimeRegistrationPage.class); - } - else if (!systemSettingsService.getGeneralSystemSettingsInstance().isShowSingleSignOn()) { + } else if (!systemSettingsService.getGeneralSystemSettingsInstance().isShowSingleSignOn()) { setResponsePage(LocalLogInPage.class); } diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LogoutPage.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LogoutPage.java index ba8d668780..6156d115e7 100755 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LogoutPage.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/LogoutPage.java @@ -5,16 +5,15 @@ import org.apache.wicket.markup.html.link.BookmarkablePageLink; import se.su.dsv.scipro.basepages.PublicPage; public class LogoutPage extends PublicPage { - - public LogoutPage(){ - getSession().invalidate(); + public LogoutPage() { + getSession().invalidate(); setResponsePage(SSOPage.class); - - add(new Label("message", "You are now logged out. Log back in ")); - BookmarkablePageLink bml = new BookmarkablePageLink<>("loginLink", LoginPage.class); - bml.add(new Label("linkText", "here")); - add(bml); - } + + add(new Label("message", "You are now logged out. Log back in ")); + BookmarkablePageLink bml = new BookmarkablePageLink<>("loginLink", LoginPage.class); + bml.add(new Label("linkText", "here")); + add(bml); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/SSOPage.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/SSOPage.java index 5ebf9f0f0f..8df12a7cce 100644 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/SSOPage.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/pages/SSOPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.loginlogout.pages; +import jakarta.inject.Inject; +import jakarta.servlet.http.HttpServletRequest; +import java.util.Optional; +import java.util.Set; import se.su.dsv.scipro.basepages.PublicPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.session.SciProSession; @@ -7,11 +11,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserImportService; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import jakarta.servlet.http.HttpServletRequest; -import java.util.Optional; -import java.util.Set; - @Authorization(requiresLoggedInUser = false) public class SSOPage extends PublicPage { diff --git a/view/src/main/java/se/su/dsv/scipro/loginlogout/panels/LoginPanel.java b/view/src/main/java/se/su/dsv/scipro/loginlogout/panels/LoginPanel.java index 6460305ae8..7c82987437 100755 --- a/view/src/main/java/se/su/dsv/scipro/loginlogout/panels/LoginPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/loginlogout/panels/LoginPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.loginlogout.panels; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.StatelessForm; @@ -15,14 +16,13 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - public class LoginPanel extends Panel { private final Logger LOG = LoggerFactory.getLogger(LoginPanel.class); @Inject private AuthenticationService authenticationService; + @Inject private UserService userService; @@ -33,6 +33,7 @@ public class LoginPanel extends Panel { } public final class SignInForm extends StatelessForm { + private IModel usernameModel = new Model<>(); private IModel passwordModel = new Model<>(); @@ -54,10 +55,9 @@ public class LoginPanel extends Panel { SciProSession.get().setUser(user); setResponsePage(getApplication().getHomePage()); continueToOriginalDestination(); - } - else { + } else { error(getString("loginFailed")); } } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanel.java index d775add388..e7f1301dcf 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import org.apache.wicket.Component; import org.apache.wicket.MetaDataKey; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -23,17 +29,9 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static java.util.Arrays.asList; - public abstract class AbstractAdminIdeaPanel extends Panel { - public static final MetaDataKey PRESELECTED_APPLICATION_PERIOD = new MetaDataKey<>() { - }; + public static final MetaDataKey PRESELECTED_APPLICATION_PERIOD = new MetaDataKey<>() {}; public static final String DIALOG = "dialog"; public static final String DATA_TABLE = "dataTable"; @@ -48,10 +46,13 @@ public abstract class AbstractAdminIdeaPanel extends Panel { @Inject private IdeaService ideaService; + @Inject private TargetService targetService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private ProjectTypeService projectTypeService; @@ -85,78 +86,103 @@ public abstract class AbstractAdminIdeaPanel extends Panel { add(dataTable); } - private List> createColumns() { - List> columns = new ArrayList<>(); + private List> createColumns() { + List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of(HEADER_DATE_CREATED), Idea::getDateCreated, "dateCreated")); - columns.add(new LambdaColumn<>(Model.of(HEADER_PROJECT_TYPE), "projectType.name", idea -> idea.getProjectType().getName())); + columns.add( + new LambdaColumn<>(Model.of(HEADER_PROJECT_TYPE), "projectType.name", idea -> + idea.getProjectType().getName() + ) + ); - columns.add(new LambdaColumn<>(Model.of(HEADER_TITLE), Idea::getTitle) { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, model.map(Idea::getTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - openDialog(model, target); - } - }); - } - }); - - columns.add(new AbstractExportableColumn<>(Model.of(HEADER_STATUS), "match.status") { - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(ideaService.getStatusString(rowModel.getObject())); - } - }); - - columns.add(new AbstractExportableColumn<>(Model.of(HEADER_SUPERVISOR)) { - @Override - public void populateItem(Item> item, String id, IModel ideaModel) { - addSupervisorField(item, id, ideaModel); - } - - @Override - public IModel getDataModel(IModel rowModel) { - return rowModel.map(Idea::getMatch).map(Match::getSupervisor).map(User::getFullName); - } - }); - - columns.add(new AbstractExportableColumn<>(Model.of(HEADER_AUTHORS)) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new StudentProfileProgramPanel(componentId, t, true); - } - }); - } - - @Override - public IModel getDataModel(IModel rowModel) { - StringBuilder participants = new StringBuilder(); - Set participantsSet = rowModel.getObject().getIdeaParticipations(); - for (IdeaParticipation participation : participantsSet) { - participants.append(participation.getUser().getFullName()).append("; "); + columns.add( + new LambdaColumn<>(Model.of(HEADER_TITLE), Idea::getTitle) { + @Override + public void populateItem(Item> components, String s, final IModel model) { + components.add( + new AjaxLinkPanel<>(s, model, model.map(Idea::getTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + openDialog(model, target); + } + } + ); } - return Model.of(participants.toString()); } - }); + ); + + columns.add( + new AbstractExportableColumn<>(Model.of(HEADER_STATUS), "match.status") { + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(ideaService.getStatusString(rowModel.getObject())); + } + } + ); + + columns.add( + new AbstractExportableColumn<>(Model.of(HEADER_SUPERVISOR)) { + @Override + public void populateItem(Item> item, String id, IModel ideaModel) { + addSupervisorField(item, id, ideaModel); + } + + @Override + public IModel getDataModel(IModel rowModel) { + return rowModel.map(Idea::getMatch).map(Match::getSupervisor).map(User::getFullName); + } + } + ); + + columns.add( + new AbstractExportableColumn<>(Model.of(HEADER_AUTHORS)) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>( + LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new StudentProfileProgramPanel(componentId, t, true); + } + } + ); + } + + @Override + public IModel getDataModel(IModel rowModel) { + StringBuilder participants = new StringBuilder(); + Set participantsSet = rowModel.getObject().getIdeaParticipations(); + for (IdeaParticipation participation : participantsSet) { + participants.append(participation.getUser().getFullName()).append("; "); + } + return Model.of(participants.toString()); + } + } + ); columns.addAll(addPanelSpecificColumns()); return columns; } private void openDialog(IModel model, AjaxRequestTarget target) { - modalWindowPlus.setContent(new AdminIdeaDetailsPanel(modalWindowPlus.getContentId(), model, dataTable) { - - @Override - public void update(AjaxRequestTarget target) { - target.add(dataTable); - modalWindowPlus.close(target); - target.appendJavaScript("window.scrollTo(0,0);"); + modalWindowPlus.setContent( + new AdminIdeaDetailsPanel(modalWindowPlus.getContentId(), model, dataTable) { + @Override + public void update(AjaxRequestTarget target) { + target.add(dataTable); + modalWindowPlus.close(target); + target.appendJavaScript("window.scrollTo(0,0);"); + } } - - }); + ); modalWindowPlus.setTitle(model.getObject().getTitle()); modalWindowPlus.show(target); } @@ -167,36 +193,46 @@ public abstract class AbstractAdminIdeaPanel extends Panel { item.add(new UserLinkPanel(id, ideaModel.map(Idea::getMatch).map(Match::getSupervisor))); break; case STUDENT: - item.add(new EmployeeAutoCompleteDivPanel(id, LambdaModel.of(ideaModel.map(Idea::getMatch), Match::getSupervisor, Match::setSupervisor)) { - @Override - public void onNewEmployeeSelection(AjaxRequestTarget target, User newSelection) { - Idea idea = ideaModel.getObject(); - if (newSelection == null) { - ideaService.adminUnmatchIdea(idea, SciProSession.get().getUser()); - info("Unmatched idea: " + idea.getTitle()); - } - else { - if (targetService.hasTargetsLeft(idea.getApplicationPeriod(), newSelection, idea.getProjectType())) { - ideaService.changeSupervisor(idea, newSelection, SciProSession.get().getUser()); - info("Supervisor changed"); + item.add( + new EmployeeAutoCompleteDivPanel( + id, + LambdaModel.of(ideaModel.map(Idea::getMatch), Match::getSupervisor, Match::setSupervisor) + ) { + @Override + public void onNewEmployeeSelection(AjaxRequestTarget target, User newSelection) { + Idea idea = ideaModel.getObject(); + if (newSelection == null) { + ideaService.adminUnmatchIdea(idea, SciProSession.get().getUser()); + info("Unmatched idea: " + idea.getTitle()); } else { - error("The supervisor have reached current target numbers"); + if ( + targetService.hasTargetsLeft( + idea.getApplicationPeriod(), + newSelection, + idea.getProjectType() + ) + ) { + ideaService.changeSupervisor(idea, newSelection, SciProSession.get().getUser()); + info("Supervisor changed"); + } else { + error("The supervisor have reached current target numbers"); + } } + target.addListener(new AjaxFeedbackPanelUpdater()); } - target.addListener(new AjaxFeedbackPanelUpdater()); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(ideaModel.getObject().getProject() == null); - } + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(ideaModel.getObject().getProject() == null); + } - @Override - protected boolean allowClear() { - return true; + @Override + protected boolean allowClear() { + return true; + } } - }); + ); break; default: throw new IllegalStateException("idea needs a type"); @@ -211,12 +247,14 @@ public abstract class AbstractAdminIdeaPanel extends Panel { filter.setTypes(new ArrayList<>(asList(Idea.Type.STUDENT, Idea.Type.SUPERVISOR))); filter.setStatuses(new ArrayList<>(asList(Idea.Status.UNMATCHED, Idea.Status.MATCHED))); filter.setLevels(projectTypeService.findWithModule(ProjectModule.MATCH)); - add(new AjaxIdeaFilterPanel("filter", Model.of(filter)) { - @Override - protected void filterChanged(final AjaxRequestTarget target) { - target.add(dataTable); + add( + new AjaxIdeaFilterPanel("filter", Model.of(filter)) { + @Override + protected void filterChanged(final AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); } protected abstract List> addPanelSpecificColumns(); diff --git a/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminMatchPage.java b/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminMatchPage.java index c9870faeb8..30a61db87f 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminMatchPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AbstractAdminMatchPage.java @@ -1,6 +1,7 @@ - package se.su.dsv.scipro.match; +import java.util.ArrayList; +import java.util.List; import se.su.dsv.scipro.admin.pages.AbstractAdminPage; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminApplicationPeriod; @@ -9,31 +10,38 @@ import se.su.dsv.scipro.projectpartner.SinglesPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import java.util.ArrayList; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.SYSADMIN, Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN, Roles.ADMIN }) public abstract class AbstractAdminMatchPage extends AbstractAdminPage { + public AbstractAdminMatchPage() { - add(new AbstractMenuPanel("menuPanel", AbstractAdminMatchPage.class, this.getClass()) { - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("Ideas", AdminManageIdeaPage.class)); - items.add(new MenuItem("Extended ideas", AdminIdeaPopupPage.class, true)); - items.add(new MenuItem("Keywords and research areas", AdminKeywordPage.class)); - items.add(new MenuItem("Units", AdminUnitPage.class)); - items.add(new MenuItem("Programs", AdminProgramPage.class)); - items.add(new MenuItem("Application periods", AdminManageMatchPeriodsPage.class, MenuHighlightAdminApplicationPeriod.class)); - items.add(new MenuItem("Project partner", AdminProjectPartnerPage.class)); - items.add(new MenuItem("Singles", SinglesPage.class)); - items.add(new MenuItem("Manual matching", ManualMatching.class)); - return items; + add( + new AbstractMenuPanel("menuPanel", AbstractAdminMatchPage.class, this.getClass()) { + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("Ideas", AdminManageIdeaPage.class)); + items.add(new MenuItem("Extended ideas", AdminIdeaPopupPage.class, true)); + items.add(new MenuItem("Keywords and research areas", AdminKeywordPage.class)); + items.add(new MenuItem("Units", AdminUnitPage.class)); + items.add(new MenuItem("Programs", AdminProgramPage.class)); + items.add( + new MenuItem( + "Application periods", + AdminManageMatchPeriodsPage.class, + MenuHighlightAdminApplicationPeriod.class + ) + ); + items.add(new MenuItem("Project partner", AdminProjectPartnerPage.class)); + items.add(new MenuItem("Singles", SinglesPage.class)); + items.add(new MenuItem("Manual matching", ManualMatching.class)); + return items; + } + + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; - } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/AbstractIdeaProjectPage.java b/view/src/main/java/se/su/dsv/scipro/match/AbstractIdeaProjectPage.java index cd8cf76bc4..d4fbef4bc1 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AbstractIdeaProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AbstractIdeaProjectPage.java @@ -1,34 +1,35 @@ package se.su.dsv.scipro.match; +import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.HORIZONTAL; + +import java.util.Arrays; +import java.util.List; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightProjectMyIdeas; import se.su.dsv.scipro.project.pages.ProjectPage; import se.su.dsv.scipro.projectpartner.ProjectPartnerPage; -import java.util.Arrays; -import java.util.List; - -import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.HORIZONTAL; - public class AbstractIdeaProjectPage extends ProjectPage { + public AbstractIdeaProjectPage(PageParameters pp) { super(pp); - final Class aClass = getClass(); - add(new AbstractMenuPanel("subMenu", AbstractIdeaProjectPage.class, aClass) { - @Override - protected List getItemList() { - return Arrays.asList( + add( + new AbstractMenuPanel("subMenu", AbstractIdeaProjectPage.class, aClass) { + @Override + protected List getItemList() { + return Arrays.asList( new MenuItem("My ideas", ProjectIdeaStartPage.class, MenuHighlightProjectMyIdeas.class), new MenuItem("Project partner", ProjectPartnerPage.class) - ); - } + ); + } - @Override - protected MenuType getMenuType() { - return HORIZONTAL; + @Override + protected MenuType getMenuType() { + return HORIZONTAL; + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AbstractSupervisorProjectIdeaPage.java b/view/src/main/java/se/su/dsv/scipro/match/AbstractSupervisorProjectIdeaPage.java index c58ad0c2af..68aeeb57e2 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AbstractSupervisorProjectIdeaPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AbstractSupervisorProjectIdeaPage.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyIdeas; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorPage; -import java.util.ArrayList; -import java.util.List; - public abstract class AbstractSupervisorProjectIdeaPage extends AbstractSupervisorPage { public AbstractSupervisorProjectIdeaPage(PageParameters pp) { @@ -16,21 +15,24 @@ public abstract class AbstractSupervisorProjectIdeaPage extends AbstractSupervis } private void addSubMenu() { - add(new AbstractMenuPanel("menuPanel", AbstractSupervisorProjectIdeaPage.class, this.getClass()) { + add( + new AbstractMenuPanel("menuPanel", AbstractSupervisorProjectIdeaPage.class, this.getClass()) { + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add( + new MenuItem("My ideas", SupervisorIdeaStartPage.class, MenuHighlightSupervisorMyIdeas.class) + ); + items.add(new MenuItem("View all supervisor ideas", SupervisorNewAllSupervisorIdeasPage.class)); + items.add(new MenuItem("View all student ideas", SupervisorAllStudentIdeasPage.class)); + return items; + } } - - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("My ideas", SupervisorIdeaStartPage.class, MenuHighlightSupervisorMyIdeas.class)); - items.add(new MenuItem("View all supervisor ideas", SupervisorNewAllSupervisorIdeasPage.class)); - items.add(new MenuItem("View all student ideas", SupervisorAllStudentIdeasPage.class)); - return items; - } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanel.java index d925103f31..0f3e1e9b11 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -23,12 +24,11 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; - public class AcceptIdeaDialogPanel extends Panel { @Inject private IdeaService ideaService; + @Inject private UserService userService; @@ -43,7 +43,6 @@ public class AcceptIdeaDialogPanel extends Panel { add(new AcceptIdeaForm("form", model, feedback)); } - private class AcceptIdeaForm extends Form { private PartnerAdditionPanel coAuthorPanel; @@ -69,7 +68,12 @@ public class AcceptIdeaDialogPanel extends Panel { }; add(program); - programDropDownChoice = new DropDownChoice<>("programDropDown", new Model<>(), new ListAdapterModel<>(userModel.map(User::getPrograms)), new LambdaChoiceRenderer<>(Program::getName, Program::getId)); + programDropDownChoice = new DropDownChoice<>( + "programDropDown", + new Model<>(), + new ListAdapterModel<>(userModel.map(User::getPrograms)), + new LambdaChoiceRenderer<>(Program::getName, Program::getId) + ); programDropDownChoice.setNullValid(true); program.add(programDropDownChoice); @@ -84,16 +88,25 @@ public class AcceptIdeaDialogPanel extends Panel { private void addSelectButton(final IModel model, final FeedbackPanel feedback) { AjaxButton selectLink = new AjaxButton("selectLink") { - @Override public void onSubmit(AjaxRequestTarget target) { - Pair acceptance = ideaService.validateStudentAcceptance(model.getObject(), getCurrentUser(), coAuthorPanel.getCoAuthor(), applicationPeriod.getObject()); + Pair acceptance = ideaService.validateStudentAcceptance( + model.getObject(), + getCurrentUser(), + coAuthorPanel.getCoAuthor(), + applicationPeriod.getObject() + ); if (acceptance.getHead()) { - ideaService.acceptIdea(model.getObject(), getCurrentUser(), programDropDownChoice.getModelObject(), coAuthorPanel.getCoAuthor(), applicationPeriod.getObject()); + ideaService.acceptIdea( + model.getObject(), + getCurrentUser(), + programDropDownChoice.getModelObject(), + coAuthorPanel.getCoAuthor(), + applicationPeriod.getObject() + ); info(acceptance.getTail()); } else { error(acceptance.getTail()); - } target.add(feedback); } @@ -120,7 +133,6 @@ public class AcceptIdeaDialogPanel extends Panel { contract.add(new CheckBoxRequiredValidator()); add(contract); } - } private LoadableDetachableModel getUserModel() { diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanel.java index 0d1e4a5511..0f5d87b5b1 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -29,9 +31,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import java.util.*; - public abstract class AdminIdeaDetailsCrudPanel extends Panel { public static final String PROJECT_TYPE = "projectType"; @@ -39,8 +38,10 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { @Inject private IdeaService ideaService; + @Inject private TargetService targetService; + @Inject private DateService dateService; @@ -53,7 +54,7 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { add(feedback); add(new IdeaDetailsForm("form", model, feedback)); - for (IdeaParticipation ip : model.getObject().getIdeaParticipations()){ + for (IdeaParticipation ip : model.getObject().getIdeaParticipations()) { originalAuthors.add(ip.getUser()); } } @@ -69,19 +70,36 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { Idea idea = model.getObject(); WebMarkupContainer container = new WebMarkupContainer("container"); container.setOutputMarkupId(true); - String periodString = idea.getApplicationPeriod() != null ? idea.getApplicationPeriod().getName() + " " - + idea.getApplicationPeriod().getStartDate() + " - " + idea.getApplicationPeriod().getEndDate() - + " Course start: " + idea.getApplicationPeriod().getCourseStartDate() : "None"; - String meetingString = idea.getFirstMeeting() != null ? format(idea.getFirstMeeting().getFirstMeetingDate(), DateStyle.DATETIME) + ", " + idea.getFirstMeeting().getRoom() : "None"; - String areaString = idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : "No research area selected"; + String periodString = idea.getApplicationPeriod() != null + ? idea.getApplicationPeriod().getName() + + " " + + idea.getApplicationPeriod().getStartDate() + + " - " + + idea.getApplicationPeriod().getEndDate() + + " Course start: " + + idea.getApplicationPeriod().getCourseStartDate() + : "None"; + String meetingString = idea.getFirstMeeting() != null + ? format(idea.getFirstMeeting().getFirstMeetingDate(), DateStyle.DATETIME) + + ", " + + idea.getFirstMeeting().getRoom() + : "None"; + String areaString = idea.getResearchArea() != null + ? idea.getResearchArea().getTitle() + : "No research area selected"; container.add(new Label(PROJECT_TYPE, idea.getProjectType().getName())); - container.add(new ListView<>("languages", new ListAdapterModel<>(LambdaModel.of(model, Idea::getLanguages, Idea::setLanguages))) { - @Override - protected void populateItem(final ListItem item) { - item.add(new EnumLabel<>("name", item.getModel())); + container.add( + new ListView<>( + "languages", + new ListAdapterModel<>(LambdaModel.of(model, Idea::getLanguages, Idea::setLanguages)) + ) { + @Override + protected void populateItem(final ListItem item) { + item.add(new EnumLabel<>("name", item.getModel())); + } } - }); + ); container.add(new Label("status", ideaService.getStatusString(idea))); container.add(new Label("period", periodString)); container.add(new Label("firstMeeting", meetingString)); @@ -95,7 +113,10 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { } private void addDescAndPrereqs(WebMarkupContainer container, Idea idea) { - Label prereqs = new Label("reqs", idea.getPrerequisites() != null ? Model.of(idea.getPrerequisites()) : new ResourceModel(NONE)); + Label prereqs = new Label( + "reqs", + idea.getPrerequisites() != null ? Model.of(idea.getPrerequisites()) : new ResourceModel(NONE) + ); prereqs.setVisible(idea.getType() == Type.SUPERVISOR); @@ -103,43 +124,62 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { enclosureContainer.add(prereqs); enclosureContainer.add(new Label("description", idea.getDescription())); container.add(enclosureContainer); - } private void addKeywords(WebMarkupContainer container, IModel idea) { - container.add(new Label("noKeysLabel", "No keywords available").setVisible(idea.getObject().getKeywords().isEmpty())); + container.add( + new Label("noKeysLabel", "No keywords available").setVisible(idea.getObject().getKeywords().isEmpty()) + ); container.add(new Label("keywords", new KeywordsModel(idea))); } - private void addSupervisorSelection(final WebMarkupContainer container, final IModel ideaModel, final FeedbackPanel feedback) { - container.add(new EmployeeAutoCompleteDivPanel("supervisorSelection", LambdaModel.of(ideaModel.map(Idea::getMatch), Match::getSupervisor, Match::setSupervisor)) { - @Override - public void onNewEmployeeSelection(AjaxRequestTarget target, - User newSelection) { - Idea idea = ideaModel.getObject(); - if (targetService.hasTargetsLeft(idea.getApplicationPeriod(), newSelection, idea.getProjectType())) { - ideaService.changeSupervisor(idea, newSelection, SciProSession.get().getUser()); - info("Supervisor changed to: " + newSelection.getFullName()); - } else { - error("Supervisor target numbers are reached. Unable to change supervisor."); + private void addSupervisorSelection( + final WebMarkupContainer container, + final IModel ideaModel, + final FeedbackPanel feedback + ) { + container.add( + new EmployeeAutoCompleteDivPanel( + "supervisorSelection", + LambdaModel.of(ideaModel.map(Idea::getMatch), Match::getSupervisor, Match::setSupervisor) + ) { + @Override + public void onNewEmployeeSelection(AjaxRequestTarget target, User newSelection) { + Idea idea = ideaModel.getObject(); + if ( + targetService.hasTargetsLeft( + idea.getApplicationPeriod(), + newSelection, + idea.getProjectType() + ) + ) { + ideaService.changeSupervisor(idea, newSelection, SciProSession.get().getUser()); + info("Supervisor changed to: " + newSelection.getFullName()); + } else { + error("Supervisor target numbers are reached. Unable to change supervisor."); + } + target.add(feedback); + target.add(container); + updateTarget(target); } - target.add(feedback); - target.add(container); - updateTarget(target); - } - @Override - protected void onConfigure() { - super.onConfigure(); - Idea idea = ideaModel.getObject(); - setEnabled(idea.getApplicationPeriod() != null && idea.getProjectType() != null); + @Override + protected void onConfigure() { + super.onConfigure(); + Idea idea = ideaModel.getObject(); + setEnabled(idea.getApplicationPeriod() != null && idea.getProjectType() != null); + } } - }); + ); addUnmatchButton(container, ideaModel); } private void addUnmatchButton(final WebMarkupContainer container, final IModel idea) { - AjaxConfirmationLink unmatchButton = new AjaxConfirmationLink<>("unmatch", idea, "Are you sure you want to unmatch this idea?") { + AjaxConfirmationLink unmatchButton = new AjaxConfirmationLink<>( + "unmatch", + idea, + "Are you sure you want to unmatch this idea?" + ) { @Override public void onClick(AjaxRequestTarget target) { ideaService.adminUnmatchIdea(getModelObject(), SciProSession.get().getUser()); @@ -157,24 +197,39 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { container.add(unmatchButton); } - private void addAuthorSelection(final WebMarkupContainer container, final Idea idea, final FeedbackPanel feedback) { + private void addAuthorSelection( + final WebMarkupContainer container, + final Idea idea, + final FeedbackPanel feedback + ) { SortedSet authors = new TreeSet<>(new User.ByNameComparator()); for (IdeaParticipation ip : idea.getIdeaParticipations()) { authors.add(ip.getUser()); } - AddUsersPanel authorsPanel = new AddUsersPanel("authorsPanel", new SetModel<>(authors), AddUsersPanel.LookFor.AUTHORS); + AddUsersPanel authorsPanel = new AddUsersPanel( + "authorsPanel", + new SetModel<>(authors), + AddUsersPanel.LookFor.AUTHORS + ); container.add(authorsPanel); authorsPanel.setEnabled(idea.getApplicationPeriod() != null); AjaxLink saveAuthors = new AjaxLink<>("saveAuthorButton") { - @Override public void onClick(AjaxRequestTarget target) { - Pair acceptance = ideaService.validateAdminAddAuthors(idea, authorsPanel.getModelObject()); + Pair acceptance = ideaService.validateAdminAddAuthors( + idea, + authorsPanel.getModelObject() + ); if (acceptance.getHead()) { ideaService.setAuthors(idea, authorsPanel.getModelObject(), SciProSession.get().getUser()); if (authorsPanel.getModelObject().isEmpty()) { - info("Authors " + getAuthorsString(originalAuthors) + " removed from the idea " + idea.getTitle()); + info( + "Authors " + + getAuthorsString(originalAuthors) + + " removed from the idea " + + idea.getTitle() + ); } else { info("Authors changed on the idea " + idea.getTitle()); } @@ -199,7 +254,7 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { } } - private String getAuthorsString(Collection students){ + private String getAuthorsString(Collection students) { boolean first = true; StringBuilder authors = new StringBuilder(); for (User user : students) { @@ -213,5 +268,3 @@ public abstract class AdminIdeaDetailsCrudPanel extends Panel { return authors.toString(); } } - - diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanel.java index e3c8430270..e3df91519b 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanel.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.match; +import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; -import java.util.Optional; - public abstract class AdminIdeaDetailsPanel extends Panel { private Panel overviewPanel; @@ -27,7 +26,6 @@ public abstract class AdminIdeaDetailsPanel extends Panel { private void addPanels(IModel ideaModel, final WebMarkupContainer wmc) { add(new IdeaExportPanel("exportStatus", ideaModel)); overviewPanel = new AdminIdeaDetailsCrudPanel("panel", ideaModel) { - @Override public void updateAndClose(AjaxRequestTarget target) { update(target); @@ -48,7 +46,6 @@ public abstract class AdminIdeaDetailsPanel extends Panel { private void addOverviewLink() { overviewLink = new AjaxFallbackLink<>("overviewLink") { - @Override protected void onConfigure() { super.onConfigure(); @@ -66,7 +63,6 @@ public abstract class AdminIdeaDetailsPanel extends Panel { private void addHistoryLink() { historyLink = new AjaxFallbackLink<>("historyLink") { - @Override protected void onConfigure() { super.onConfigure(); diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanel.java index 68b9906a77..bdce5a2d37 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; @@ -20,27 +24,25 @@ import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.dataproviders.PageAdapter; import se.su.dsv.scipro.profile.UserLinkPanel; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class AdminIdeaHistoryPanel extends Panel { public static final String DATA_TABLE = "dataTable"; + @Inject - private MatchService matchService; + private MatchService matchService; public AdminIdeaHistoryPanel(String id, IModel model) { - super(id); - addDataTable(model); - } + super(id); + addDataTable(model); + } - private void addDataTable(final IModel model) { + private void addDataTable(final IModel model) { SortableDataProvider provider = new SortableDataProvider<>() { @Override public Iterator iterator(long first, long count) { - return matchService.getMatchHistory(model.getObject(), new PageAdapter(first, count, getSort())).iterator(); + return matchService + .getMatchHistory(model.getObject(), new PageAdapter(first, count, getSort())) + .iterator(); } @Override @@ -55,23 +57,29 @@ public class AdminIdeaHistoryPanel extends Panel { }; provider.setSort("dateCreated", SortOrder.DESCENDING); add(new ExportableDataPanel<>(DATA_TABLE, createColumns(), provider)); - } + } private List> createColumns() { - List> columns = new ArrayList<>(); + List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of("Date"), Match::getDateCreated, "dateCreated", DateStyle.DATETIME)); columns.add(new EnumLambdaColumn<>(Model.of("Status"), "status", Match::getStatus)); - columns.add(new AbstractColumn<>(Model.of("Supervisor"), "supervisor.fullName") { - @Override - public void populateItem(Item> item, String componentId, IModel rowModel) { - if (rowModel.getObject().getSupervisor() != null) { - item.add(new UserLinkPanel(componentId, LambdaModel.of(rowModel, Match::getSupervisor, Match::setSupervisor))); - } else { - item.add(new Label(componentId, "None")); + columns.add( + new AbstractColumn<>(Model.of("Supervisor"), "supervisor.fullName") { + @Override + public void populateItem(Item> item, String componentId, IModel rowModel) { + if (rowModel.getObject().getSupervisor() != null) { + item.add( + new UserLinkPanel( + componentId, + LambdaModel.of(rowModel, Match::getSupervisor, Match::setSupervisor) + ) + ); + } else { + item.add(new Label(componentId, "None")); + } } - } - }); + ); columns.add(new UserColumn<>(Model.of("Change made by"), "changedBy.fullName", Match::getChangedBy)); return columns; } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanel.java index 9d54aad13a..0d303299b5 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; @@ -15,10 +18,6 @@ import se.su.dsv.scipro.datatables.ClickableIconColumn; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class AdminIdeaOverviewPanel extends AbstractAdminIdeaPanel { public static final String HEADER_MEETING = "First meeting"; @@ -33,63 +32,91 @@ public class AdminIdeaOverviewPanel extends AbstractAdminIdeaPanel { @Override protected List> addPanelSpecificColumns() { List> list = new ArrayList<>(); - list.add(new AbstractExportableColumn<>(Model.of(HEADER_MEETING)) { - @Override - public void populateItem(Item> item, String componentId, IModel ideaModel) { - Idea idea = ideaModel.getObject(); - if (idea.getFirstMeeting() != null) { - item.add(new DateLabel(componentId, ideaModel.map(Idea::getFirstMeeting).map(FirstMeeting::getFirstMeetingDate))); - } else { - item.add(new Label(componentId, "-")); + list.add( + new AbstractExportableColumn<>(Model.of(HEADER_MEETING)) { + @Override + public void populateItem(Item> item, String componentId, IModel ideaModel) { + Idea idea = ideaModel.getObject(); + if (idea.getFirstMeeting() != null) { + item.add( + new DateLabel( + componentId, + ideaModel.map(Idea::getFirstMeeting).map(FirstMeeting::getFirstMeetingDate) + ) + ); + } else { + item.add(new Label(componentId, "-")); + } } - } - @Override - public IModel getDataModel(IModel rowModel) { - Idea idea = rowModel.getObject(); - if (idea.getFirstMeeting() != null) { - return Model.of(idea.getFirstMeeting().getFirstMeetingDate().toString()); - } else { - return Model.of("-"); + @Override + public IModel getDataModel(IModel rowModel) { + Idea idea = rowModel.getObject(); + if (idea.getFirstMeeting() != null) { + return Model.of(idea.getFirstMeeting().getFirstMeetingDate().toString()); + } else { + return Model.of("-"); + } } } - }); + ); final boolean isAdmin = SciProSession.get().authorizedForRole(Roles.ADMIN); if (isAdmin) { - list.add(new AbstractExportableColumn<>(Model.of("Inactive")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { + list.add( + new AbstractExportableColumn<>(Model.of("Inactive")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxCheckboxWrapper( + componentId, + LambdaModel.of(rowModel, Idea::isInactive, Idea::setInactive) + ) { + @Override + public void onChange(AjaxRequestTarget target, boolean selected) { + ideaService.inactivateIdea( + rowModel.getObject(), + selected, + SciProSession.get().getUser() + ); + success(getString("inactive", rowModel)); + target.add(feedback); + target.add(dataTable); + } + } + ); + } - cellItem.add(new AjaxCheckboxWrapper(componentId, LambdaModel.of(rowModel, Idea::isInactive, Idea::setInactive)) { - @Override - public void onChange(AjaxRequestTarget target, boolean selected) { - ideaService.inactivateIdea(rowModel.getObject(), selected, SciProSession.get().getUser()); - success(getString("inactive", rowModel)); - target.add(feedback); - target.add(dataTable); - } - }); + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(!rowModel.getObject().isInactive()); + } } + ); + list.add( + new ClickableIconColumn<>( + Model.of("Delete"), + null, + ClickableIconColumn.DELETE, + "Are you sure you want to delete this idea?" + ) { + @Override + public boolean shouldBeVisible(IModel rowModel) { + return (rowModel.getObject().getMatchStatus() == Idea.Status.UNMATCHED); + } - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(!rowModel.getObject().isInactive()); + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + ideaService.deleteUnmatchedIdea(clicked.getObject()); + info("Idea '" + clicked.getObject().getTitle() + "' deleted successfully"); + target.add(feedback); + target.add(dataTable); + } } - }); - list.add(new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE, "Are you sure you want to delete this idea?") { - @Override - public boolean shouldBeVisible(IModel rowModel) { - return rowModel.getObject().getMatchStatus() == Idea.Status.UNMATCHED; - } - - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - ideaService.deleteUnmatchedIdea(clicked.getObject()); - info("Idea '" + clicked.getObject().getTitle() + "' deleted successfully"); - target.add(feedback); - target.add(dataTable); - } - }); + ); } return list; } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPage.java index 8430e6d33b..5da6b8e5f9 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.Model; import se.su.dsv.scipro.basepages.BasePage; @@ -9,19 +12,17 @@ import se.su.dsv.scipro.mail.MailEventService; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.stream.Collectors; - -@Authorization(authorizedRoles = {Roles.ADMIN, Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.SYSADMIN }) public class AdminIdeaPopupPage extends BasePage { public static final String IDEA_PANEL = "ideaPanel"; @Inject private PreliminaryMatchService preliminaryMatchService; + @Inject private IdeaService ideaService; + @Inject private MailEventService mailEventService; @@ -29,61 +30,75 @@ public class AdminIdeaPopupPage extends BasePage { final AdminIdeaPopupPanel ideaPopupPanel = new AdminIdeaPopupPanel(IDEA_PANEL); add(ideaPopupPanel); - add(new ConfirmationLink("sendStatus", Model.of("Are you sure you want to send the status e-mails?")) { - @Override - public void onClick() { - final IdeaService.Filter filter = ideaPopupPanel.getFilter(); + add( + new ConfirmationLink("sendStatus", Model.of("Are you sure you want to send the status e-mails?")) { + @Override + public void onClick() { + final IdeaService.Filter filter = ideaPopupPanel.getFilter(); - if (filter.getApplicationPeriod() == null) { - error("Please select an application period in the filter"); - return; - } - ideaService.findAll(filter) + if (filter.getApplicationPeriod() == null) { + error("Please select an application period in the filter"); + return; + } + ideaService + .findAll(filter) .stream() .filter(idea -> idea.getMatchStatus() == Idea.Status.MATCHED) .collect(Collectors.groupingBy(idea -> idea.getMatch().getSupervisor())) .forEach((supervisor, ideas) -> { - final StringBuilder message = new StringBuilder(); - message.append("You have been matched to ") - .append(ideas.size()) - .append(" ideas for the period ") - .append(filter.getApplicationPeriod().getName()) - .append("\n\n") - .append("Now would be a good time to schedule the first meeting if you have yet not done so.") - .append("\n\n") - .append("Here are the ideas you've been matched to:") - .append('\n'); + message + .append("You have been matched to ") + .append(ideas.size()) + .append(" ideas for the period ") + .append(filter.getApplicationPeriod().getName()) + .append("\n\n") + .append( + "Now would be a good time to schedule the first meeting if you have yet not done so." + ) + .append("\n\n") + .append("Here are the ideas you've been matched to:") + .append('\n'); ideas.forEach(idea -> { - message.append("* ") - .append(idea.getTitle()) - .append(" (") - .append(idea.getProjectType().getName()) - .append(')') - .append('\n'); - idea.getIdeaParticipations() - .forEach(author -> message.append(" - ") - .append(author.getUser().getFullName()) - .append(" <") - .append(author.getUser().getEmailAddress()) - .append('>') - .append('\n')); + message + .append("* ") + .append(idea.getTitle()) + .append(" (") + .append(idea.getProjectType().getName()) + .append(')') + .append('\n'); + idea + .getIdeaParticipations() + .forEach(author -> + message + .append(" - ") + .append(author.getUser().getFullName()) + .append(" <") + .append(author.getUser().getEmailAddress()) + .append('>') + .append('\n') + ); }); final MailEvent mailEvent = new MailEvent(); mailEvent.setRecipients(Collections.singleton(supervisor)); - mailEvent.setSubject("Matched ideas for the period " + filter.getApplicationPeriod().getName()); + mailEvent.setSubject( + "Matched ideas for the period " + filter.getApplicationPeriod().getName() + ); mailEvent.setMessageBody(message.toString()); mailEventService.save(mailEvent); }); - success("E-mail sent"); + success("E-mail sent"); + } } - }); - add(new Link("complete") { - @Override - public void onClick() { - preliminaryMatchService.completePreliminaryMatch(ideaPopupPanel.getFilter()); + ); + add( + new Link("complete") { + @Override + public void onClick() { + preliminaryMatchService.completePreliminaryMatch(ideaPopupPanel.getFilter()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPanel.java index 4ce65e95a3..0a7aa99670 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaPopupPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; @@ -18,12 +23,6 @@ import se.su.dsv.scipro.components.EmployeeAutoComplete; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - public class AdminIdeaPopupPanel extends AbstractAdminIdeaPanel { @Inject @@ -37,51 +36,63 @@ public class AdminIdeaPopupPanel extends AbstractAdminIdeaPanel { protected List> addPanelSpecificColumns() { List> list = new ArrayList<>(); list.add(new LambdaColumn<>(Model.of("Supervisor unit"), this::getSupervisorUnitName)); - list.add(new AbstractColumn<>(Model.of("Preliminary match")) { - @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - if (rowModel.getObject().getType() == Idea.Type.STUDENT) { - final IModel preliminaryMatch = getPreliminaryMatch(rowModel); - cellItem.add(new PreliminaryCell(componentId, preliminaryMatch)); - } else { - cellItem.add(new EmptyPanel(componentId)); + list.add( + new AbstractColumn<>(Model.of("Preliminary match")) { + @Override + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + if (rowModel.getObject().getType() == Idea.Type.STUDENT) { + final IModel preliminaryMatch = getPreliminaryMatch(rowModel); + cellItem.add(new PreliminaryCell(componentId, preliminaryMatch)); + } else { + cellItem.add(new EmptyPanel(componentId)); + } } } - }); - list.add(new AbstractExportableColumn<>(Model.of("\"Student idea form\"")) { - @Override - protected Component createDisplayComponent(final String componentId, final IModel dataModel) { - return new MultiLineLabel(componentId, dataModel); - } + ); + list.add( + new AbstractExportableColumn<>(Model.of("\"Student idea form\"")) { + @Override + protected Component createDisplayComponent(final String componentId, final IModel dataModel) { + return new MultiLineLabel(componentId, dataModel); + } - @Override - public IModel getDataModel(IModel rowModel) { - return new IModel<>() { - private final StringBuilder stringBuilder = new StringBuilder(); + @Override + public IModel getDataModel(IModel rowModel) { + return new IModel<>() { + private final StringBuilder stringBuilder = new StringBuilder(); - /* constructor */ { - appendIfNotEmpty("BACKGROUND", TholanderBox::getBackground); - appendIfNotEmpty("LITERATURE", TholanderBox::getLiterature); - appendIfNotEmpty("PROBLEM", TholanderBox::getProblem); - appendIfNotEmpty("METHOD", TholanderBox::getMethod); - appendIfNotEmpty("INTERESTS", TholanderBox::getInterests); - } - - private void appendIfNotEmpty(String label, Function f) { - final String s = f.apply(rowModel.getObject().getTholanderBox()); - if (s != null && !s.isBlank()) { - stringBuilder.append(label).append(": ").append(s).append("\n\n"); + /* constructor */{ + appendIfNotEmpty("BACKGROUND", TholanderBox::getBackground); + appendIfNotEmpty("LITERATURE", TholanderBox::getLiterature); + appendIfNotEmpty("PROBLEM", TholanderBox::getProblem); + appendIfNotEmpty("METHOD", TholanderBox::getMethod); + appendIfNotEmpty("INTERESTS", TholanderBox::getInterests); } - } - @Override - public String getObject() { - return stringBuilder.toString(); - } - }; + private void appendIfNotEmpty(String label, Function f) { + final String s = f.apply(rowModel.getObject().getTholanderBox()); + if (s != null && !s.isBlank()) { + stringBuilder.append(label).append(": ").append(s).append("\n\n"); + } + } + + @Override + public String getObject() { + return stringBuilder.toString(); + } + }; + } } - }); - list.add(new LambdaColumn<>(Model.of("Research area"), idea -> idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null)); + ); + list.add( + new LambdaColumn<>(Model.of("Research area"), idea -> + idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null + ) + ); list.add(new KeywordsColumn<>(Model.of("Keywords"))); list.add(new LambdaColumn<>(Model.of("Description"), Idea::getDescription)); list.add(new LambdaColumn<>(Model.of("Prerequisites"), Idea::getPrerequisites)); @@ -90,10 +101,10 @@ public class AdminIdeaPopupPanel extends AbstractAdminIdeaPanel { private String getSupervisorUnitName(Idea idea) { return Optional.ofNullable(idea.getMatch()) - .map(Match::getSupervisor) - .map(User::getUnit) - .map(Unit::getTitle) - .orElse(null); + .map(Match::getSupervisor) + .map(User::getUnit) + .map(Unit::getTitle) + .orElse(null); } private IModel getPreliminaryMatch(final IModel rowModel) { @@ -101,42 +112,48 @@ public class AdminIdeaPopupPanel extends AbstractAdminIdeaPanel { @Override protected PreliminaryMatch load() { final Idea idea = rowModel.getObject(); - final PreliminaryMatch preliminaryMatch - = preliminaryMatchService.findByIdea(idea); - return preliminaryMatch == null - ? new PreliminaryMatch(idea) - : preliminaryMatch; + final PreliminaryMatch preliminaryMatch = preliminaryMatchService.findByIdea(idea); + return preliminaryMatch == null ? new PreliminaryMatch(idea) : preliminaryMatch; } }; } private class PreliminaryCell extends Panel { + public PreliminaryCell(final String id, final IModel model) { super(id, model); - add(new EmployeeAutoComplete("supervisor", LambdaModel.of(model, PreliminaryMatch::getSupervisor, PreliminaryMatch::setSupervisor)) { - @Override - protected void onInitialize() { - super.onInitialize(); - getSettings().setPlaceholder("Supervisor"); - } + add( + new EmployeeAutoComplete( + "supervisor", + LambdaModel.of(model, PreliminaryMatch::getSupervisor, PreliminaryMatch::setSupervisor) + ) { + @Override + protected void onInitialize() { + super.onInitialize(); + getSettings().setPlaceholder("Supervisor"); + } - @Override - protected void action(final AjaxRequestTarget target, final User object) { - preliminaryMatchService.save(model.getObject()); - } + @Override + protected void action(final AjaxRequestTarget target, final User object) { + preliminaryMatchService.save(model.getObject()); + } - @Override - public boolean getAllowClear() { - return true; + @Override + public boolean getAllowClear() { + return true; + } } - }); + ); final AjaxFormComponentUpdatingBehavior saveOnChange = new AjaxFormComponentUpdatingBehavior("input") { @Override protected void onUpdate(final AjaxRequestTarget target) { preliminaryMatchService.save(model.getObject()); } }; - final TextArea comment = new TextArea<>("comment", LambdaModel.of(model, PreliminaryMatch::getComment, PreliminaryMatch::setComment)); + final TextArea comment = new TextArea<>( + "comment", + LambdaModel.of(model, PreliminaryMatch::getComment, PreliminaryMatch::setComment) + ); comment.add(saveOnChange); add(comment); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPage.java index 8a9b0a0000..e72c9cc1b2 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -22,22 +28,18 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static java.util.Arrays.asList; - -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { public static final String TABLE = "table"; public static final String STATUS_FILTER = "statusFilter"; + @Inject ApplicationPeriodService applicationPeriodService; + @Inject IdeaService ideaService; + @Inject ProjectTypeService projectTypeService; @@ -50,14 +52,19 @@ public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { } private void addStatusFilter() { - add(new AjaxCheckBoxMultipleChoice<>(STATUS_FILTER, getStatusModel(), - getStatusChoices(), new EnumChoiceRenderer<>(this)) { - - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataTable); + add( + new AjaxCheckBoxMultipleChoice<>( + STATUS_FILTER, + getStatusModel(), + getStatusChoices(), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); } private IModel> getStatusModel() { @@ -80,10 +87,17 @@ public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new LambdaColumn<>(new StringResourceModel("applicationPeriod", this), "name", ApplicationPeriod::getName)); + columns.add( + new LambdaColumn<>(new StringResourceModel("applicationPeriod", this), "name", ApplicationPeriod::getName) + ); columns.add(totalIdeasColumn()); for (ProjectType projectType : projectTypeService.findWithModule(ProjectModule.MATCH)) { - columns.add(ideasByProjectTypeColumn(new StringResourceModel("projectTypeHeader", this, Model.of(projectType)), projectType)); + columns.add( + ideasByProjectTypeColumn( + new StringResourceModel("projectTypeHeader", this, Model.of(projectType)), + projectType + ) + ); } columns.add(ideasByIdeaTypeColumn(new StringResourceModel("supervisorIdeas", this), Idea.Type.SUPERVISOR)); columns.add(ideasByIdeaTypeColumn(new StringResourceModel("studentIdeas", this), Idea.Type.STUDENT)); @@ -95,8 +109,17 @@ public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { private AbstractExportableColumn totalIdeasColumn() { return new AbstractExportableColumn<>(new ResourceModel("totalIdeas").wrapOnAssignment(this)) { @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new Label(componentId, String.valueOf(ideaService.countByApplicationPeriod(rowModel.getObject(), params)))); + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new Label( + componentId, + String.valueOf(ideaService.countByApplicationPeriod(rowModel.getObject(), params)) + ) + ); } @Override @@ -106,31 +129,59 @@ public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { }; } - private IColumn ideasByProjectTypeColumn(IModel headerModel, final ProjectType projectType) { + private IColumn ideasByProjectTypeColumn( + IModel headerModel, + final ProjectType projectType + ) { return new AbstractExportableColumn<>(headerModel) { @Override - public void populateItem(Item> cellItem, String id, IModel model) { - cellItem.add(new Label(id, String.valueOf(ideaService.countByApplicationPeriodAndProjectType(model.getObject(), projectType, params)))); + public void populateItem( + Item> cellItem, + String id, + IModel model + ) { + cellItem.add( + new Label( + id, + String.valueOf( + ideaService.countByApplicationPeriodAndProjectType(model.getObject(), projectType, params) + ) + ) + ); } @Override public IModel getDataModel(IModel rowModel) { - return Model.of(String.valueOf(ideaService.countByApplicationPeriodAndProjectType(rowModel.getObject(), projectType, params))); + return Model.of( + String.valueOf( + ideaService.countByApplicationPeriodAndProjectType(rowModel.getObject(), projectType, params) + ) + ); } }; } private IColumn ideasByIdeaTypeColumn(IModel headerModel, final Idea.Type type) { return new AbstractExportableColumn<>(headerModel) { - @Override - public void populateItem(Item> cellItem, String id, IModel model) { - cellItem.add(new Label(id, String.valueOf(ideaService.countByApplicationPeriodAndType(model.getObject(), type, params)))); + public void populateItem( + Item> cellItem, + String id, + IModel model + ) { + cellItem.add( + new Label( + id, + String.valueOf(ideaService.countByApplicationPeriodAndType(model.getObject(), type, params)) + ) + ); } @Override public IModel getDataModel(IModel rowModel) { - return Model.of(String.valueOf(ideaService.countByApplicationPeriodAndType(rowModel.getObject(), type, params))); + return Model.of( + String.valueOf(ideaService.countByApplicationPeriodAndType(rowModel.getObject(), type, params)) + ); } }; } @@ -138,15 +189,25 @@ public class AdminIdeaStatisticsPage extends AbstractAdminStatisticsPage { private AbstractColumn numberOfStudentsColumn() { return new AbstractExportableColumn<>(new ResourceModel("numberOfStudents").wrapOnAssignment(this)) { @Override - public void populateItem(Item> item, String id, IModel model) { - item.add(new Label(id, String.valueOf(ideaService.countAuthorsByApplicationPeriod(model.getObject(), params)))); + public void populateItem( + Item> item, + String id, + IModel model + ) { + item.add( + new Label( + id, + String.valueOf(ideaService.countAuthorsByApplicationPeriod(model.getObject(), params)) + ) + ); } @Override public IModel getDataModel(IModel rowModel) { - return Model.of(String.valueOf(ideaService.countAuthorsByApplicationPeriod(rowModel.getObject(), params))); + return Model.of( + String.valueOf(ideaService.countAuthorsByApplicationPeriod(rowModel.getObject(), params)) + ); } }; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPage.java index c5f938e6b2..b6857b051e 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -12,44 +15,49 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - -@Authorization(authorizedRoles={Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminIdeaStatusStatisticsPage extends AbstractAdminStatisticsPage { @Inject private IdeaService ideaService; + @Inject private ProjectTypeService projectTypeService; - public AdminIdeaStatusStatisticsPage() { + public AdminIdeaStatusStatisticsPage() { setUpStatusList(); - } + } private void setUpStatusList() { List statuses = Arrays.asList(Idea.Status.values()); - add(new ListView<>("projectTypeHeaders", getProjectTypes()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("name", item.getModel().map(ProjectType::getName))); + add( + new ListView<>("projectTypeHeaders", getProjectTypes()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("name", item.getModel().map(ProjectType::getName))); + } } - }); + ); ListView listView = new ListView<>("statusList", statuses) { - @Override protected void populateItem(final ListItem item) { item.add(new Label("status", item.getModelObject().toString())); item.add(new Label("total", String.valueOf(ideaService.countIdeas(item.getModelObject(), null)))); - item.add(new ListView<>("projectTypes", getProjectTypes()) { - @Override - protected void populateItem(ListItem projectType) { - projectType.add(new Label("value", - String.valueOf(ideaService.countIdeas(item.getModelObject(), projectType.getModelObject())))); + item.add( + new ListView<>("projectTypes", getProjectTypes()) { + @Override + protected void populateItem(ListItem projectType) { + projectType.add( + new Label( + "value", + String.valueOf( + ideaService.countIdeas(item.getModelObject(), projectType.getModelObject()) + ) + ) + ); + } } - }); - + ); } }; add(listView); @@ -63,5 +71,4 @@ public class AdminIdeaStatusStatisticsPage extends AbstractAdminStatisticsPage { } }; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordCrudPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordCrudPanel.java index 7c249041f5..bf749df1cb 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordCrudPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordCrudPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -23,14 +26,11 @@ import se.su.dsv.scipro.dataproviders.GenericDataProvider; import se.su.dsv.scipro.datatables.AjaxCheckboxWrapper; import se.su.dsv.scipro.datatables.ClickableIconColumn; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class AdminKeywordCrudPanel extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(AdminKeywordCrudPanel.class); private final FeedbackPanel feedback; + @Inject private KeywordService keywordService; @@ -68,12 +68,17 @@ public class AdminKeywordCrudPanel extends Panel { modalWindowPlus.setTitle("Create new keyword"); Keyword k = new Keyword(); k.setKeyword(""); - modalWindowPlus.setContent(new EditKeywordPanel(modalWindowPlus.getContentId(), new DetachableServiceModel<>(keywordService, k)) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dataTable); + modalWindowPlus.setContent( + new EditKeywordPanel( + modalWindowPlus.getContentId(), + new DetachableServiceModel<>(keywordService, k) + ) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -92,55 +97,65 @@ public class AdminKeywordCrudPanel extends Panel { List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of(DATE_CREATED), Keyword::getDateCreated, "dateCreated")); columns.add(new LambdaColumn<>(Model.of(KEYWORD), "keyword", Keyword::getKeyword)); - columns.add(new AbstractExportableColumn<>(Model.of(ACTIVE)) { - @Override - public void populateItem(Item> item, String id, final IModel model) { - final Keyword keyword = model.getObject(); - final boolean state = !keyword.isDeleted(); - item.add(new AjaxCheckboxWrapper(id, Model.of(state)) { - @Override - public void onChange(AjaxRequestTarget target, boolean selected) { - model.getObject().setDeleted(state); - keywordService.save(model.getObject()); - target.add(dataTable); - } - }); - } - - @Override - public IModel getDataModel(IModel rowModel) { - return Model.of(!rowModel.getObject().isDeleted()); - } - }); - columns.add(new ClickableIconColumn<>(Model.of(EDIT), null, ClickableIconColumn.EDIT) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setTitle("Edit keyword: " + clicked.getObject().getKeyword()); - modalWindowPlus.setContent(new EditKeywordPanel(modalWindowPlus.getContentId(), clicked) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dataTable); - } - }); - modalWindowPlus.show(target); - target.add(dataTable); - } - }); - columns.add(new ClickableIconColumn<>(Model.of(DELETE), null, ClickableIconColumn.DELETE) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - try { - keywordService.delete(clicked.getObject().getId()); - info("Keyword deleted"); - } catch (Exception e) { - String message = "Could not delete keyword, it is being used"; - error(message); - LOGGER.info(message, e); + columns.add( + new AbstractExportableColumn<>(Model.of(ACTIVE)) { + @Override + public void populateItem(Item> item, String id, final IModel model) { + final Keyword keyword = model.getObject(); + final boolean state = !keyword.isDeleted(); + item.add( + new AjaxCheckboxWrapper(id, Model.of(state)) { + @Override + public void onChange(AjaxRequestTarget target, boolean selected) { + model.getObject().setDeleted(state); + keywordService.save(model.getObject()); + target.add(dataTable); + } + } + ); + } + + @Override + public IModel getDataModel(IModel rowModel) { + return Model.of(!rowModel.getObject().isDeleted()); } - target.add(feedback); - target.add(dataTable); } - }); + ); + columns.add( + new ClickableIconColumn<>(Model.of(EDIT), null, ClickableIconColumn.EDIT) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setTitle("Edit keyword: " + clicked.getObject().getKeyword()); + modalWindowPlus.setContent( + new EditKeywordPanel(modalWindowPlus.getContentId(), clicked) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dataTable); + } + } + ); + modalWindowPlus.show(target); + target.add(dataTable); + } + } + ); + columns.add( + new ClickableIconColumn<>(Model.of(DELETE), null, ClickableIconColumn.DELETE) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + try { + keywordService.delete(clicked.getObject().getId()); + info("Keyword deleted"); + } catch (Exception e) { + String message = "Could not delete keyword, it is being used"; + error(message); + LOGGER.info(message, e); + } + target.add(feedback); + target.add(dataTable); + } + } + ); return columns; } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordPage.java index 70521e0b0f..a27cd20d35 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordPage.java @@ -4,15 +4,15 @@ import org.apache.wicket.markup.html.panel.FeedbackPanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class AdminKeywordPage extends AbstractAdminMatchPage { public static final String FEEDBACK = "feedback"; public AdminKeywordPage() { add(new FeedbackPanel(FEEDBACK)); - add(new AdminKeywordSwitchPanel(PANEL)); - } + add(new AdminKeywordSwitchPanel(PANEL)); + } static final String PANEL = "switchPanel"; } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanel.java index 2c48ee1bfe..ae13916bf3 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanel.java @@ -16,38 +16,40 @@ public class AdminKeywordSwitchPanel extends Panel { currentPanel = keywordPanel; setOutputMarkupId(true); - add(new Link(KEYWORD_LINK) { - @Override - public void onClick() { - currentPanel.replaceWith(keywordPanel); - currentPanel = keywordPanel; - } + add( + new Link(KEYWORD_LINK) { + @Override + public void onClick() { + currentPanel.replaceWith(keywordPanel); + currentPanel = keywordPanel; + } - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(!currentPanel.equals(keywordPanel)); + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(!currentPanel.equals(keywordPanel)); + } } + ); + add( + new Link(AREA_LINK) { + @Override + public void onClick() { + currentPanel.replaceWith(areaPanel); + currentPanel = areaPanel; + } - }); - add(new Link(AREA_LINK) { - @Override - public void onClick() { - currentPanel.replaceWith(areaPanel); - currentPanel = areaPanel; + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(!currentPanel.equals(areaPanel)); + } } - - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(!currentPanel.equals(areaPanel)); - } - }); + ); add(currentPanel); } static final String PANEL = "panel"; static final String KEYWORD_LINK = "keywordLink"; static final String AREA_LINK = "areaLink"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminManageIdeaPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminManageIdeaPage.java index 072fcab532..a2ed31d221 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminManageIdeaPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminManageIdeaPage.java @@ -3,8 +3,9 @@ package se.su.dsv.scipro.match; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.ADMIN, Roles.STUDADM}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.STUDADM }) public class AdminManageIdeaPage extends AbstractAdminMatchPage { + public AdminManageIdeaPage() { add(new AdminIdeaOverviewPanel("panel")); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPage.java index 61e358973a..ac2cad7c3c 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPage.java @@ -9,5 +9,5 @@ public class AdminManageMatchPeriodsPage extends AbstractAdminMatchPage implemen public AdminManageMatchPeriodsPage() { add(new AdminApplicationPeriodsPanel(PANEL)); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminProgramPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminProgramPage.java index ac7ad7c479..37b2c94c6a 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminProgramPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminProgramPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -25,11 +28,7 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.Program; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class AdminProgramPage extends AbstractAdminMatchPage { private static final Logger LOGGER = LoggerFactory.getLogger(AdminProgramPage.class); @@ -53,7 +52,7 @@ public class AdminProgramPage extends AbstractAdminMatchPage { addDialog(); addCreateNewLink(); - } + } private void addDialog() { modalWindowPlus = new ModalWindowPlus("dialog"); @@ -66,12 +65,17 @@ public class AdminProgramPage extends AbstractAdminMatchPage { public void onClick(AjaxRequestTarget target) { modalWindowPlus.setTitle("Create new program"); Program program = new Program(); - modalWindowPlus.setContent(new EditProgramPanel(modalWindowPlus.getContentId(), new DetachableServiceModel<>(programService, program)) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dp); + modalWindowPlus.setContent( + new EditProgramPanel( + modalWindowPlus.getContentId(), + new DetachableServiceModel<>(programService, program) + ) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dp); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -82,47 +86,68 @@ public class AdminProgramPage extends AbstractAdminMatchPage { List> columns = new ArrayList<>(); columns.add(new LambdaColumn<>(Model.of("Name"), "name", Program::getName)); columns.add(new LambdaColumn<>(Model.of("Name in English"), "nameEn", Program::getNameEn)); - columns.add(new AbstractColumn<>(Model.of("Has external system identifier")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - String hasExternalIdentifier = (rowModel.getObject().getExternalId() == null) ? "No" : "Yes"; - cellItem.add(new Label(componentId, Model.of(hasExternalIdentifier))); + columns.add( + new AbstractColumn<>(Model.of("Has external system identifier")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + String hasExternalIdentifier = (rowModel.getObject().getExternalId() == null) ? "No" : "Yes"; + cellItem.add(new Label(componentId, Model.of(hasExternalIdentifier))); + } } - }); - columns.add(new ClickableIconColumn<>(Model.of("Edit program"), null, ClickableIconColumn.EDIT) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setTitle("Edit program: " + clicked.getObject().getName()); - modalWindowPlus.setContent(new EditProgramPanel(modalWindowPlus.getContentId(), clicked) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dp); - } - }); - modalWindowPlus.show(target); - } - }); - columns.add(new AbstractColumn<>(Model.of("Delete")) { - @Override - public void populateItem(Item> cellItem, final String componentId, final IModel rowModel) { - AjaxIconLinkPanel delete = new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), "Are you sure?") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - try { - programService.delete(model.getObject()); - info("Deleted program"); - } catch (WicketRuntimeException wre) { - String message = "Could not delete program"; - error(message); - LOGGER.info(message, wre); + ); + columns.add( + new ClickableIconColumn<>(Model.of("Edit program"), null, ClickableIconColumn.EDIT) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setTitle("Edit program: " + clicked.getObject().getName()); + modalWindowPlus.setContent( + new EditProgramPanel(modalWindowPlus.getContentId(), clicked) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dp); + } } - target.add(feedbackPanel); - target.add(dp); - } - }; - cellItem.add(delete); + ); + modalWindowPlus.show(target); + } } - }); + ); + columns.add( + new AbstractColumn<>(Model.of("Delete")) { + @Override + public void populateItem( + Item> cellItem, + final String componentId, + final IModel rowModel + ) { + AjaxIconLinkPanel delete = new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + "Are you sure?" + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + try { + programService.delete(model.getObject()); + info("Deleted program"); + } catch (WicketRuntimeException wre) { + String message = "Could not delete program"; + error(message); + LOGGER.info(message, wre); + } + target.add(feedbackPanel); + target.add(dp); + } + }; + cellItem.add(delete); + } + } + ); return columns; } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanel.java index 38eefd7755..aae587e0b2 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -26,18 +29,16 @@ import se.su.dsv.scipro.springdata.services.SupervisorService; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.ResearchAreaService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class AdminResearchAreaCrudPanel extends Panel { public static final String DATA_TABLE = "dataTable"; @Inject private ResearchAreaService researchAreaService; + @Inject private KeywordService keywordService; + @Inject private SupervisorService supervisorService; @@ -67,12 +68,17 @@ public class AdminResearchAreaCrudPanel extends Panel { public void onClick(AjaxRequestTarget target) { modalWindowPlus.setTitle("Create new research area"); ResearchArea researchArea = new ResearchArea(); - modalWindowPlus.setContent(new EditResearchAreaPanel(modalWindowPlus.getContentId(), new DetachableServiceModel<>(researchAreaService, researchArea)) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dataTable); + modalWindowPlus.setContent( + new EditResearchAreaPanel( + modalWindowPlus.getContentId(), + new DetachableServiceModel<>(researchAreaService, researchArea) + ) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -106,7 +112,11 @@ public class AdminResearchAreaCrudPanel extends Panel { private AbstractColumn getExternalIdentifier() { return new AbstractColumn<>(Model.of("Has external system identifier")) { @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { String hasExternalIdentifier = (rowModel.getObject().getIdentifier() == null) ? "No" : "Yes"; cellItem.add(new Label(componentId, Model.of(hasExternalIdentifier))); } @@ -118,20 +128,25 @@ public class AdminResearchAreaCrudPanel extends Panel { @Override public void populateItem(Item> item, String id, IModel model) { final Long supervisorCount = supervisorService.countByResearchArea(model.getObject()); - item.add(new LabelAndLinkColumn<>(id, model, "Details") { + item.add( + new LabelAndLinkColumn<>(id, model, "Details") { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + modalWindowPlus.setContent( + new AdminResearchAreaSupervisorPanel(modalWindowPlus.getContentId(), model) + ); + modalWindowPlus.setTitle( + "Research area " + model.getObject().getTitle() + " supervisors relationships" + ); + modalWindowPlus.show(target); + } - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - modalWindowPlus.setContent(new AdminResearchAreaSupervisorPanel(modalWindowPlus.getContentId(), model)); - modalWindowPlus.setTitle("Research area " + model.getObject().getTitle() + " supervisors relationships"); - modalWindowPlus.show(target); + @Override + public String labelString() { + return supervisorCount + " "; + } } - - @Override - public String labelString() { - return supervisorCount + " "; - } - }); + ); } @Override @@ -146,19 +161,25 @@ public class AdminResearchAreaCrudPanel extends Panel { @Override public void populateItem(Item> item, String id, IModel model) { final Long keywordCount = keywordService.countByResearchArea(model.getObject()); - item.add(new LabelAndLinkColumn<>(id, model, "Details") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - modalWindowPlus.setContent(new AdminResearchAreaKeywordPanel(modalWindowPlus.getContentId(), model)); - modalWindowPlus.setTitle("Research area " + model.getObject().getTitle() + " keyword relationships"); - modalWindowPlus.show(target); - } + item.add( + new LabelAndLinkColumn<>(id, model, "Details") { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + modalWindowPlus.setContent( + new AdminResearchAreaKeywordPanel(modalWindowPlus.getContentId(), model) + ); + modalWindowPlus.setTitle( + "Research area " + model.getObject().getTitle() + " keyword relationships" + ); + modalWindowPlus.show(target); + } - @Override - public String labelString() { - return keywordCount + " "; + @Override + public String labelString() { + return keywordCount + " "; + } } - }); + ); } @Override @@ -170,16 +191,17 @@ public class AdminResearchAreaCrudPanel extends Panel { private ClickableIconColumn getEditKeywords() { return new ClickableIconColumn<>(Model.of("Edit keyword relationships"), null, ClickableIconColumn.EDIT) { - @Override protected void onClick(IModel clicked, AjaxRequestTarget target) { modalWindowPlus.setTitle("Edit keyword relationships: " + clicked.getObject().getTitle()); - modalWindowPlus.setContent(new AdminResearchAreaEditPanel(modalWindowPlus.getContentId(), clicked) { - @Override - protected void updateTarget(AjaxRequestTarget target) { - target.add(dataTable); + modalWindowPlus.setContent( + new AdminResearchAreaEditPanel(modalWindowPlus.getContentId(), clicked) { + @Override + protected void updateTarget(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -190,12 +212,14 @@ public class AdminResearchAreaCrudPanel extends Panel { @Override protected void onClick(IModel clicked, AjaxRequestTarget target) { modalWindowPlus.setTitle("Edit research area: " + clicked.getObject().getTitle()); - modalWindowPlus.setContent(new EditResearchAreaPanel(modalWindowPlus.getContentId(), clicked) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dataTable); + modalWindowPlus.setContent( + new EditResearchAreaPanel(modalWindowPlus.getContentId(), clicked) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -204,22 +228,33 @@ public class AdminResearchAreaCrudPanel extends Panel { private AbstractColumn getDelete() { return new AbstractColumn<>(Model.of("Delete")) { @Override - public void populateItem(Item> cellItem, final String componentId, final IModel rowModel) { - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), "Are you sure?") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - researchAreaService.delete(model.getObject()); - info("Deleted research area"); - target.add(feedbackPanel); - target.add(dataTable); - } + public void populateItem( + Item> cellItem, + final String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + "Are you sure?" + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + researchAreaService.delete(model.getObject()); + info("Deleted research area"); + target.add(feedbackPanel); + target.add(dataTable); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(keywordService.countByResearchArea(rowModel.getObject()) < 1); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(keywordService.countByResearchArea(rowModel.getObject()) < 1); + } } - }); + ); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanel.java index 1b38d7822d..cb9a1c2d05 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -13,71 +15,87 @@ import se.su.dsv.scipro.components.KeywordAutoComplete; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import jakarta.inject.Inject; -import java.util.List; - public abstract class AdminResearchAreaEditPanel extends GenericPanel { @Inject - private KeywordService keywordService; + private KeywordService keywordService; - public AdminResearchAreaEditPanel(String id, IModel model) { - super(id, model); - FeedbackPanel feedback = new FeedbackPanel("feedback"); - feedback.setOutputMarkupId(true); - add(feedback); - WebMarkupContainer container = new WebMarkupContainer("container"); - container.setOutputMarkupId(true); - add(container); + public AdminResearchAreaEditPanel(String id, IModel model) { + super(id, model); + FeedbackPanel feedback = new FeedbackPanel("feedback"); + feedback.setOutputMarkupId(true); + add(feedback); + WebMarkupContainer container = new WebMarkupContainer("container"); + container.setOutputMarkupId(true); + add(container); - addInputField(container, feedback); - addKeywordList(container, feedback); - } + addInputField(container, feedback); + addKeywordList(container, feedback); + } - private void addInputField(final WebMarkupContainer container, final FeedbackPanel feedback) { + private void addInputField(final WebMarkupContainer container, final FeedbackPanel feedback) { KeywordAutoComplete autoComplete = new KeywordAutoComplete("inputField") { @Override protected void action(AjaxRequestTarget pTarget, Keyword newSelection) { keywordService.addConnection(newSelection, AdminResearchAreaEditPanel.this.getModelObject()); - info("Relation added, Keyword: " + newSelection.getKeyword() + ", Research area: "+ - AdminResearchAreaEditPanel.this.getModelObject().getTitle()); + info( + "Relation added, Keyword: " + + newSelection.getKeyword() + + ", Research area: " + + AdminResearchAreaEditPanel.this.getModelObject().getTitle() + ); pTarget.add(feedback); pTarget.add(container); updateTarget(pTarget); } }; container.add(autoComplete); - } + } - private void addKeywordList(final WebMarkupContainer container, final FeedbackPanel feedback) { - container.add(new ListView<>("listView", getKeywords()) { - @Override - protected void populateItem(ListItem item) { - final Keyword keyword = item.getModelObject(); - item.add(new Label("keywordName", item.getModel().map(Keyword::getKeyword))); - item.add(new AjaxConfirmationLink("removeLink", "Are you sure you want to delete the relationship to " + keyword.getKeyword() + "?") { - @Override - public void onClick(AjaxRequestTarget target) { - keywordService.deleteConnection(keyword, AdminResearchAreaEditPanel.this.getModelObject()); - info("Relationship between Keyword: " + keyword.getKeyword() + " and Research area: " + - AdminResearchAreaEditPanel.this.getModelObject().getTitle() + " removed"); - target.add(feedback); - target.add(container); - updateTarget(target); - } - }); - } - }); - } + private void addKeywordList(final WebMarkupContainer container, final FeedbackPanel feedback) { + container.add( + new ListView<>("listView", getKeywords()) { + @Override + protected void populateItem(ListItem item) { + final Keyword keyword = item.getModelObject(); + item.add(new Label("keywordName", item.getModel().map(Keyword::getKeyword))); + item.add( + new AjaxConfirmationLink( + "removeLink", + "Are you sure you want to delete the relationship to " + keyword.getKeyword() + "?" + ) { + @Override + public void onClick(AjaxRequestTarget target) { + keywordService.deleteConnection( + keyword, + AdminResearchAreaEditPanel.this.getModelObject() + ); + info( + "Relationship between Keyword: " + + keyword.getKeyword() + + " and Research area: " + + AdminResearchAreaEditPanel.this.getModelObject().getTitle() + + " removed" + ); + target.add(feedback); + target.add(container); + updateTarget(target); + } + } + ); + } + } + ); + } private IModel> getKeywords() { return new LoadableDetachableModel<>() { - @Override - protected List load() { - return keywordService.findByResearchArea(getModelObject()); - } - }; + @Override + protected List load() { + return keywordService.findByResearchArea(getModelObject()); + } + }; } - protected abstract void updateTarget(AjaxRequestTarget target); + protected abstract void updateTarget(AjaxRequestTarget target); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanel.java index 56d11f22bd..2a7cd04bd3 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; @@ -12,14 +16,10 @@ import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.dataproviders.PageAdapter; import se.su.dsv.scipro.system.ResearchArea; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class AdminResearchAreaKeywordPanel extends Panel { public static final String DATA_TABLE = "dataTable"; + @Inject private KeywordService keywordService; @@ -32,7 +32,9 @@ public class AdminResearchAreaKeywordPanel extends Panel { SortableDataProvider provider = new SortableDataProvider<>() { @Override public Iterator iterator(long first, long count) { - return keywordService.findByResearchArea(areaModel.getObject(), new PageAdapter(first, count, getSort())).iterator(); + return keywordService + .findByResearchArea(areaModel.getObject(), new PageAdapter(first, count, getSort())) + .iterator(); } @Override @@ -50,5 +52,4 @@ public class AdminResearchAreaKeywordPanel extends Panel { columns.add(new LambdaColumn<>(Model.of("Keyword"), "keyword", Keyword::getKeyword)); add(new ExportableDataPanel<>(DATA_TABLE, columns, provider)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanel.java index 67507ba015..2c9c84346c 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; @@ -14,14 +18,10 @@ import se.su.dsv.scipro.springdata.services.SupervisorService; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class AdminResearchAreaSupervisorPanel extends Panel { public static final String DATA_TABLE = "dataTable"; + @Inject private SupervisorService supervisorService; @@ -34,7 +34,9 @@ public class AdminResearchAreaSupervisorPanel extends Panel { SortableDataProvider provider = new SortableDataProvider<>() { @Override public Iterator iterator(long first, long count) { - return supervisorService.findByResearchArea(areaModel.getObject(), new PageAdapter(first, count, getSort())).iterator(); + return supervisorService + .findByResearchArea(areaModel.getObject(), new PageAdapter(first, count, getSort())) + .iterator(); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/match/AdminUnitPage.java b/view/src/main/java/se/su/dsv/scipro/match/AdminUnitPage.java index 260bc2d449..2df36c77ff 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/AdminUnitPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AdminUnitPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -26,11 +29,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.Unit; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.SYSADMIN, Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN, Roles.ADMIN }) public class AdminUnitPage extends AbstractAdminMatchPage { private static final Logger LOGGER = LoggerFactory.getLogger(AdminUnitPage.class); @@ -54,7 +53,7 @@ public class AdminUnitPage extends AbstractAdminMatchPage { addDialog(); addCreateNewLink(); - } + } private void addDialog() { modalWindowPlus = new ModalWindowPlus("dialog"); @@ -67,12 +66,14 @@ public class AdminUnitPage extends AbstractAdminMatchPage { public void onClick(AjaxRequestTarget target) { modalWindowPlus.setTitle("Create new unit"); Unit unit = new Unit(); - modalWindowPlus.setContent(new EditUnitPanel(modalWindowPlus.getContentId(), new DetachableServiceModel<>(unitService, unit)) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dp); + modalWindowPlus.setContent( + new EditUnitPanel(modalWindowPlus.getContentId(), new DetachableServiceModel<>(unitService, unit)) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dp); + } } - }); + ); modalWindowPlus.show(target); } }; @@ -82,48 +83,69 @@ public class AdminUnitPage extends AbstractAdminMatchPage { private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new LambdaColumn<>(Model.of("Title"), "title", Unit::getTitle)); - columns.add(new AbstractColumn<>(Model.of("Has external system identifier")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - String hasExternalIdentifier = (rowModel.getObject().getIdentifier() == null) ? "No" : "Yes"; - cellItem.add(new Label(componentId, Model.of(hasExternalIdentifier))); + columns.add( + new AbstractColumn<>(Model.of("Has external system identifier")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + String hasExternalIdentifier = (rowModel.getObject().getIdentifier() == null) ? "No" : "Yes"; + cellItem.add(new Label(componentId, Model.of(hasExternalIdentifier))); + } } - }); + ); columns.add(new LambdaColumn<>(Model.of("Match responsible"), "matchResponsible", Unit::getMatchResponsible)); - columns.add(new ClickableIconColumn<>(Model.of("Edit unit"), null, ClickableIconColumn.EDIT) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setTitle("Edit unit: " + clicked.getObject().getTitle()); - modalWindowPlus.setContent(new EditUnitPanel(modalWindowPlus.getContentId(), clicked) { - @Override - public void onSave(AjaxRequestTarget target) { - target.add(dp); - } - }); - modalWindowPlus.show(target); - } - }); - columns.add(new AbstractColumn<>(Model.of("Delete")) { - @Override - public void populateItem(Item> cellItem, final String componentId, final IModel rowModel) { - AjaxIconLinkPanel delete = new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), "Are you sure?") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - try { - unitService.delete(model.getObject()); - info("Deleted unit"); - } catch (WicketRuntimeException wre) { - String message = "Could not delete unit"; - error(message); - LOGGER.info(message, wre); + columns.add( + new ClickableIconColumn<>(Model.of("Edit unit"), null, ClickableIconColumn.EDIT) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setTitle("Edit unit: " + clicked.getObject().getTitle()); + modalWindowPlus.setContent( + new EditUnitPanel(modalWindowPlus.getContentId(), clicked) { + @Override + public void onSave(AjaxRequestTarget target) { + target.add(dp); + } } - target.add(feedbackPanel); - target.add(dp); - } - }; - cellItem.add(delete); + ); + modalWindowPlus.show(target); + } } - }); + ); + columns.add( + new AbstractColumn<>(Model.of("Delete")) { + @Override + public void populateItem( + Item> cellItem, + final String componentId, + final IModel rowModel + ) { + AjaxIconLinkPanel delete = new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + "Are you sure?" + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + try { + unitService.delete(model.getObject()); + info("Deleted unit"); + } catch (WicketRuntimeException wre) { + String message = "Could not delete unit"; + error(message); + LOGGER.info(message, wre); + } + target.add(feedbackPanel); + target.add(dp); + } + }; + cellItem.add(delete); + } + } + ); return columns; } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/AjaxIdeaFilterPanel.java b/view/src/main/java/se/su/dsv/scipro/match/AjaxIdeaFilterPanel.java index 1cf788e4aa..12fbbd875a 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/AjaxIdeaFilterPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/AjaxIdeaFilterPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; +import static se.su.dsv.scipro.match.AbstractAdminIdeaPanel.PRESELECTED_APPLICATION_PERIOD; + +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -28,24 +34,22 @@ import se.su.dsv.scipro.system.ResearchAreaService; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - -import static java.util.Arrays.asList; -import static se.su.dsv.scipro.match.AbstractAdminIdeaPanel.PRESELECTED_APPLICATION_PERIOD; - public abstract class AjaxIdeaFilterPanel extends GenericPanel { + private static final int MIN_TITLE_LENGTH = 3; @Inject private ProjectTypeService projectTypeService; + @Inject private UnitService unitService; + @Inject private KeywordService keywordService; + @Inject private ResearchAreaService researchAreaService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -68,20 +72,23 @@ public abstract class AjaxIdeaFilterPanel extends GenericPanel( + add( + new AjaxCheckBoxMultipleChoice<>( "statusFilter", LambdaModel.of(getModel(), IdeaService.Filter::getStatuses, IdeaService.Filter::setStatuses), getStatusChoices(), - new EnumChoiceRenderer<>(AjaxIdeaFilterPanel.this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - filterChanged(target); + new EnumChoiceRenderer<>(AjaxIdeaFilterPanel.this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + filterChanged(target); + } } - }); + ); } private List getStatusChoices() { @@ -89,42 +96,51 @@ public abstract class AjaxIdeaFilterPanel extends GenericPanel( + add( + new AjaxCheckBoxMultipleChoice<>( "typeFilter", LambdaModel.of(getModel(), IdeaService.Filter::getTypes, IdeaService.Filter::setTypes), asList(Idea.Type.STUDENT, Idea.Type.SUPERVISOR), - new EnumChoiceRenderer<>(AjaxIdeaFilterPanel.this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - filterChanged(target); + new EnumChoiceRenderer<>(AjaxIdeaFilterPanel.this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + filterChanged(target); + } } - }); + ); } private void projectTypeFilter() { - add(new AjaxCheckBoxMultipleChoice<>( + add( + new AjaxCheckBoxMultipleChoice<>( "projectTypeFilter", LambdaModel.of(getModel(), IdeaService.Filter::getLevels, IdeaService.Filter::setLevels), projectTypeService.findWithModule(ProjectModule.MATCH), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - filterChanged(target); + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + filterChanged(target); + } } - }); + ); } private void unitFilter() { - add(new AjaxDropDownChoice<>( + add( + new AjaxDropDownChoice<>( "unitFilter", LambdaModel.of(getModel(), IdeaService.Filter::getUnit, IdeaService.Filter::setUnit), unitService.findAll(), - new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, Unit objectSelected) { - filterChanged(target); + new LambdaChoiceRenderer<>(Unit::getTitle, Unit::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, Unit objectSelected) { + filterChanged(target); + } } - }); + ); } private void newKeywordsFilter() { @@ -154,73 +170,97 @@ public abstract class AjaxIdeaFilterPanel extends GenericPanel( + add( + new AjaxDropDownChoice<>( "areaFilter", LambdaModel.of(getModel(), IdeaService.Filter::getResearchArea, IdeaService.Filter::setResearchArea), researchAreaService.findNotDeleted(), - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { - filterChanged(target); - keywordPanel.setVisible(objectSelected != null && !keywordService.findByResearchArea(objectSelected).isEmpty()); - target.add(keywordPanel); + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { + filterChanged(target); + keywordPanel.setVisible( + objectSelected != null && !keywordService.findByResearchArea(objectSelected).isEmpty() + ); + target.add(keywordPanel); + } } - }); + ); } private void newSupervisorFilter() { - add(new EmployeeAutoComplete("supervisorFilter", LambdaModel.of(getModel(), IdeaService.Filter::getSupervisor, IdeaService.Filter::setSupervisor)) { - @Override - protected void action(AjaxRequestTarget target, User employee) { - filterChanged(target); + add( + new EmployeeAutoComplete( + "supervisorFilter", + LambdaModel.of(getModel(), IdeaService.Filter::getSupervisor, IdeaService.Filter::setSupervisor) + ) { + @Override + protected void action(AjaxRequestTarget target, User employee) { + filterChanged(target); + } } - }); + ); } private void newAuthorFilter() { - add(new AuthorAutoComplete("authorFilter", LambdaModel.of(getModel(), IdeaService.Filter::getAuthor, IdeaService.Filter::setAuthor)) { - @Override - protected void action(AjaxRequestTarget target, User newSelection) { - filterChanged(target); + add( + new AuthorAutoComplete( + "authorFilter", + LambdaModel.of(getModel(), IdeaService.Filter::getAuthor, IdeaService.Filter::setAuthor) + ) { + @Override + protected void action(AjaxRequestTarget target, User newSelection) { + filterChanged(target); + } } - }); + ); } private void programFilter() { - add(new ProgramAutoComplete("programFilter", LambdaModel.of(getModel(), IdeaService.Filter::getProgram, IdeaService.Filter::setProgram)) { - @Override - protected void action(AjaxRequestTarget target, Program object) { - filterChanged(target); + add( + new ProgramAutoComplete( + "programFilter", + LambdaModel.of(getModel(), IdeaService.Filter::getProgram, IdeaService.Filter::setProgram) + ) { + @Override + protected void action(AjaxRequestTarget target, Program object) { + filterChanged(target); + } } - }); + ); } private void dateFilter() { Date startDate = Date.from(ZonedDateTime.now().minusYears(1).toInstant()); - add(new DeactivatableDatePickerPanel("dateContainer", Model.of(startDate), new Model<>()) { - @Override - protected void datesChanged(final AjaxRequestTarget target) { - getModelObject().setCreatedAfter(getStartDate().getObject()); - getModelObject().setCreatedBefore(getEndDate().getObject()); - filterChanged(target); + add( + new DeactivatableDatePickerPanel("dateContainer", Model.of(startDate), new Model<>()) { + @Override + protected void datesChanged(final AjaxRequestTarget target) { + getModelObject().setCreatedAfter(getStartDate().getObject()); + getModelObject().setCreatedBefore(getEndDate().getObject()); + filterChanged(target); + } } - }); + ); } private TextField newTitleFilter(final String id) { TextField titleField = new TextField<>(id, new Model<>()); - titleField.add(new AjaxFormComponentUpdatingBehavior("keyup") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - final String titleString = titleField.getModelObject(); - if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { - getModelObject().setTitleContains(titleString); - } else { - getModelObject().setTitleContains(null); + titleField.add( + new AjaxFormComponentUpdatingBehavior("keyup") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + final String titleString = titleField.getModelObject(); + if (titleString != null && titleString.length() >= MIN_TITLE_LENGTH) { + getModelObject().setTitleContains(titleString); + } else { + getModelObject().setTitleContains(null); + } + filterChanged(target); } - filterChanged(target); } - }); + ); return titleField; } @@ -228,14 +268,23 @@ public abstract class AjaxIdeaFilterPanel extends GenericPanel list = applicationPeriodService.findAll(); list.sort(Comparator.comparing(ApplicationPeriod::getStartDate).reversed()); final AjaxDropDownChoice applicationPeriodAjaxDropDownChoice = new AjaxDropDownChoice<>( - "applicationPeriodFilter", - LambdaModel.of(getModel(), IdeaService.Filter::getApplicationPeriod, IdeaService.Filter::setApplicationPeriod), - list, - new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId)) { + "applicationPeriodFilter", + LambdaModel.of( + getModel(), + IdeaService.Filter::getApplicationPeriod, + IdeaService.Filter::setApplicationPeriod + ), + list, + new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId) + ) { @Override public void onNewSelection(AjaxRequestTarget target, ApplicationPeriod objectSelected) { filterChanged(target); - getSession().setMetaData(PRESELECTED_APPLICATION_PERIOD, objectSelected != null ? objectSelected.getId() : null); + getSession() + .setMetaData( + PRESELECTED_APPLICATION_PERIOD, + objectSelected != null ? objectSelected.getId() : null + ); } }; applicationPeriodAjaxDropDownChoice.setNullValid(true); @@ -243,37 +292,53 @@ public abstract class AjaxIdeaFilterPanel extends GenericPanel("publishedFilter", new Model<>(PublishedFilter.ALL), Arrays.asList(PublishedFilter.values()), new EnumChoiceRenderer<>(this)) { - { - setRequired(true); - } - - @Override - protected void update(final AjaxRequestTarget target) { - switch (getModelObject()) { - case ALL: - AjaxIdeaFilterPanel.this.getModelObject().setPublished(null); - break; - case PUBLISHED: - AjaxIdeaFilterPanel.this.getModelObject().setPublished(Boolean.TRUE); - break; - case UNPUBLISHED: - AjaxIdeaFilterPanel.this.getModelObject().setPublished(Boolean.FALSE); - break; + add( + new AjaxRadioChoice<>( + "publishedFilter", + new Model<>(PublishedFilter.ALL), + Arrays.asList(PublishedFilter.values()), + new EnumChoiceRenderer<>(this) + ) { + { + setRequired(true); + } + + @Override + protected void update(final AjaxRequestTarget target) { + switch (getModelObject()) { + case ALL: + AjaxIdeaFilterPanel.this.getModelObject().setPublished(null); + break; + case PUBLISHED: + AjaxIdeaFilterPanel.this.getModelObject().setPublished(Boolean.TRUE); + break; + case UNPUBLISHED: + AjaxIdeaFilterPanel.this.getModelObject().setPublished(Boolean.FALSE); + break; + } + filterChanged(target); } - filterChanged(target); } - }); + ); } - private enum PublishedFilter { ALL, PUBLISHED, UNPUBLISHED } + private enum PublishedFilter { + ALL, + PUBLISHED, + UNPUBLISHED, + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/CompleteIdeaDialogPanel.java b/view/src/main/java/se/su/dsv/scipro/match/CompleteIdeaDialogPanel.java index 94523a9039..a6b43ea949 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/CompleteIdeaDialogPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/CompleteIdeaDialogPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.head.IHeaderResponse; @@ -33,23 +39,20 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - public class CompleteIdeaDialogPanel extends GenericPanel { @Inject private IdeaService ideaService; + @Inject private UserService userService; + @Inject private ProjectService projectService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; @@ -65,31 +68,34 @@ public class CompleteIdeaDialogPanel extends GenericPanel { } private class CompleteIdeaForm extends Form { + private CoAuthorChoice coAuthorChoice; private WebMarkupContainer activePartnerProjectWarning; private DropDownChoice programDropDownChoice; public CompleteIdeaForm(String id, IModel model) { super(id, model); - add(new Label("title", model.map(Idea::getTitle))); add(new Label("type", model.map(Idea::getProjectType).map(ProjectType::getName))); - add(new ListView<>("languages", model.map(Idea::getLanguages).map(ArrayList::new)) { - @Override - protected void populateItem(final ListItem item) { - item.add(new EnumLabel<>("language", item.getModel())); + add( + new ListView<>("languages", model.map(Idea::getLanguages).map(ArrayList::new)) { + @Override + protected void populateItem(final ListItem item) { + item.add(new EnumLabel<>("language", item.getModel())); + } } - }); + ); final Set partners = getModelObject() - .getIdeaParticipations() - .stream() - .map(IdeaParticipation::getUser) - .filter(user -> !user.equals(SciProSession.get().getUser())) - .collect(Collectors.toSet()); + .getIdeaParticipations() + .stream() + .map(IdeaParticipation::getUser) + .filter(user -> !user.equals(SciProSession.get().getUser())) + .collect(Collectors.toSet()); - IModel supportMail = LoadableDetachableModel.of(generalSystemSettingsService::getGeneralSystemSettingsInstance) - .map(GeneralSystemSettings::getActiveProjectIdeaSupportMail); + IModel supportMail = LoadableDetachableModel.of( + generalSystemSettingsService::getGeneralSystemSettingsInstance + ).map(GeneralSystemSettings::getActiveProjectIdeaSupportMail); activePartnerProjectWarning = new WebMarkupContainer("activePartnerProjectWarning") { { add(new ExternalLink("supportMail", supportMail.map(mail -> "mailto:" + mail), supportMail)); @@ -99,24 +105,29 @@ public class CompleteIdeaDialogPanel extends GenericPanel { protected void onConfigure() { super.onConfigure(); final ProjectType selectedProjectType = getModelObject().getProjectType(); - final boolean partnerHasActiveProject = coAuthorChoice.getModelObject() - .stream() - .map(partner -> projectService.getActiveProjectsByUserAndProjectType(partner, selectedProjectType)) - .flatMap(Collection::stream) - .findAny() - .isPresent(); + final boolean partnerHasActiveProject = coAuthorChoice + .getModelObject() + .stream() + .map(partner -> + projectService.getActiveProjectsByUserAndProjectType(partner, selectedProjectType) + ) + .flatMap(Collection::stream) + .findAny() + .isPresent(); setVisible(partnerHasActiveProject); } }; activePartnerProjectWarning.setOutputMarkupPlaceholderTag(true); add(activePartnerProjectWarning); coAuthorChoice = new CoAuthorChoice("coAuthorChoice", Model.of(partners)); - coAuthorChoice.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(activePartnerProjectWarning); + coAuthorChoice.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(activePartnerProjectWarning); + } } - }); + ); add(coAuthorChoice); add(new ComponentFeedbackPanel("coAuthorFeedback", coAuthorChoice)); add(new BookmarkablePageLink("partnerLink", ProjectPartnerPage.class)); @@ -125,14 +136,17 @@ public class CompleteIdeaDialogPanel extends GenericPanel { add(new MultiLineLabel("prerequisites", getModel().map(Idea::getPrerequisites))); programDropDownChoice = new DropDownChoice<>( - "programDropDown", - new Model<>(getCurrentProgram()), - new ListAdapterModel<>(getUserModel().map(User::getPrograms)), - new LambdaChoiceRenderer<>(Program::getName, Program::getId)) { + "programDropDown", + new Model<>(getCurrentProgram()), + new ListAdapterModel<>(getUserModel().map(User::getPrograms)), + new LambdaChoiceRenderer<>(Program::getName, Program::getId) + ) { @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("cidp_program_toggle", "click", "$('#cidp_program').toggle()")); + response.render( + OnEventHeaderItem.forMarkupId("cidp_program_toggle", "click", "$('#cidp_program').toggle()") + ); } @Override @@ -154,7 +168,13 @@ public class CompleteIdeaDialogPanel extends GenericPanel { super.onValidate(); final Collection partners = new HashSet<>(coAuthorChoice.getConvertedInput()); for (User partner : partners) { - if (ideaService.authorParticipatingOnOtherActiveIdea(partner, getModelObject().getApplicationPeriod(), getModelObject())) { + if ( + ideaService.authorParticipatingOnOtherActiveIdea( + partner, + getModelObject().getApplicationPeriod(), + getModelObject() + ) + ) { coAuthorChoice.error(getString("coAuthorParticipating", Model.of(partner))); } } @@ -167,7 +187,12 @@ public class CompleteIdeaDialogPanel extends GenericPanel { error(getString("partner.already.has.an.active.project.on.this.level", Model.of(partner))); } } - if (!applicationPeriodService.hasIdeaSizeExemption(SciProSession.get().getUser(), getModelObject().getApplicationPeriod())) { + if ( + !applicationPeriodService.hasIdeaSizeExemption( + SciProSession.get().getUser(), + getModelObject().getApplicationPeriod() + ) + ) { if (partners.size() < projectType.getMinAuthors() - 1) { coAuthorChoice.error(getString("too.few.authors", Model.of(projectType))); } @@ -209,12 +234,14 @@ public class CompleteIdeaDialogPanel extends GenericPanel { add(new Label("research_area", model.map(Idea::getResearchArea).map(ResearchArea::getTitle))); - add(new ListView<>("keywords", model.map(Idea::getKeywords).map(ArrayList::new)) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label("keyword", item.getModel().map(Keyword::getKeyword))); + add( + new ListView<>("keywords", model.map(Idea::getKeywords).map(ArrayList::new)) { + @Override + protected void populateItem(final ListItem item) { + item.add(new Label("keyword", item.getModel().map(Keyword::getKeyword))); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/EditKeywordPanel.java b/view/src/main/java/se/su/dsv/scipro/match/EditKeywordPanel.java index 72e8ed4518..7f74350cb6 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/EditKeywordPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/EditKeywordPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxButton; @@ -21,15 +25,11 @@ import se.su.dsv.scipro.components.AjaxDropDownChoice; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.ResearchAreaService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - public abstract class EditKeywordPanel extends Panel { @Inject private KeywordService keywordService; + @Inject private ResearchAreaService researchAreaService; @@ -41,28 +41,35 @@ public abstract class EditKeywordPanel extends Panel { public abstract void onSave(AjaxRequestTarget target); private class KeywordForm extends Form { + private final AjaxDropDownChoice addResearchAreas; private final ListView researchAreas; private final List currentAreas; public KeywordForm(String id, IModel model) { super(id, model); - currentAreas = new ArrayList<>(getModelObject().getResearchAreas()); final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); - RequiredTextField keyword = new RequiredTextField<>("keyword", LambdaModel.of(model, Keyword::getKeyword, Keyword::setKeyword)); + RequiredTextField keyword = new RequiredTextField<>( + "keyword", + LambdaModel.of(model, Keyword::getKeyword, Keyword::setKeyword) + ); wmc.add(keyword); wmc.add(new ComponentFeedbackPanel("keywordFeedback", keyword)); - final WebMarkupContainer raWMC = new WebMarkupContainer("raWMC"); raWMC.setOutputMarkupId(true); wmc.add(raWMC); - addResearchAreas = new AjaxDropDownChoice<>("addResearchAreas", new Model<>(null), getSelectableResearchAreas(currentAreas), new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { + addResearchAreas = new AjaxDropDownChoice<>( + "addResearchAreas", + new Model<>(null), + getSelectableResearchAreas(currentAreas), + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { @Override public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { if (objectSelected != null && !currentAreas.contains(objectSelected)) { @@ -79,27 +86,36 @@ public abstract class EditKeywordPanel extends Panel { researchAreas = new ListView<>("researchAreas", new ArrayList<>(currentAreas)) { @Override protected void populateItem(final ListItem item) { - item.add(new Label("title", LambdaModel.of(item.getModel(), ResearchArea::getTitle, ResearchArea::setTitle))); - item.add(new AjaxLink("remove") { - @Override - public void onClick(AjaxRequestTarget target) { - currentAreas.remove(item.getModelObject()); - researchAreas.setList(currentAreas); - addResearchAreas.setModelObject(null); - target.add(raWMC); + item.add( + new Label( + "title", + LambdaModel.of(item.getModel(), ResearchArea::getTitle, ResearchArea::setTitle) + ) + ); + item.add( + new AjaxLink("remove") { + @Override + public void onClick(AjaxRequestTarget target) { + currentAreas.remove(item.getModelObject()); + researchAreas.setList(currentAreas); + addResearchAreas.setModelObject(null); + target.add(raWMC); + } } - }); + ); } }; raWMC.add(researchAreas); - raWMC.add(new Label("noAreas", "No research areas") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(currentAreas.isEmpty()); + raWMC.add( + new Label("noAreas", "No research areas") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(currentAreas.isEmpty()); + } } - }); + ); FeedbackPanel feedback = new FeedbackPanel("feedback", message -> !message.isRendered()); feedback.setOutputMarkupId(true); @@ -107,24 +123,25 @@ public abstract class EditKeywordPanel extends Panel { add(wmc); - add(new AjaxButton("save") { - @Override - protected void onSubmit(AjaxRequestTarget target) { + add( + new AjaxButton("save") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + Keyword keyword = KeywordForm.this.getModelObject(); + keyword.setResearchAreas(new HashSet<>(currentAreas)); + KeywordForm.this.setModelObject(keywordService.save(keyword)); - Keyword keyword = KeywordForm.this.getModelObject(); - keyword.setResearchAreas(new HashSet<>(currentAreas)); - KeywordForm.this.setModelObject(keywordService.save(keyword)); + info("Saved"); + target.add(wmc); + onSave(target); + } - info("Saved"); - target.add(wmc); - onSave(target); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(wmc); + } } - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(wmc); - } - }); + ); } private IModel> getSelectableResearchAreas(List currentAreas) { @@ -136,4 +153,4 @@ public abstract class EditKeywordPanel extends Panel { }); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/EditProgramPanel.java b/view/src/main/java/se/su/dsv/scipro/match/EditProgramPanel.java index 167703949f..13fadc0177 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/EditProgramPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/EditProgramPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -12,8 +13,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.system.Program; -import jakarta.inject.Inject; - public abstract class EditProgramPanel extends Panel { @Inject @@ -30,19 +29,27 @@ public abstract class EditProgramPanel extends Panel { public ProgramForm(String id, IModel model) { super(id, model); - final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); - RequiredTextField name = new RequiredTextField<>("name", LambdaModel.of(model, Program::getName, Program::setName)); + RequiredTextField name = new RequiredTextField<>( + "name", + LambdaModel.of(model, Program::getName, Program::setName) + ); wmc.add(name); wmc.add(new ComponentFeedbackPanel("nameFeedback", name)); - RequiredTextField nameEn = new RequiredTextField<>("nameEn", LambdaModel.of(model, Program::getNameEn, Program::setNameEn)); + RequiredTextField nameEn = new RequiredTextField<>( + "nameEn", + LambdaModel.of(model, Program::getNameEn, Program::setNameEn) + ); wmc.add(nameEn); wmc.add(new ComponentFeedbackPanel("nameEnFeedback", nameEn)); - RequiredTextField code = new RequiredTextField<>("code", LambdaModel.of(model, Program::getCode, Program::setCode)); + RequiredTextField code = new RequiredTextField<>( + "code", + LambdaModel.of(model, Program::getCode, Program::setCode) + ); wmc.add(code); wmc.add(new ComponentFeedbackPanel("codeFeedback", code)); @@ -52,20 +59,22 @@ public abstract class EditProgramPanel extends Panel { add(wmc); - add(new AjaxButton("save") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - ProgramForm.this.setModelObject(programService.save(ProgramForm.this.getModelObject())); - info("Saved"); - target.add(wmc); - onSave(target); - } + add( + new AjaxButton("save") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + ProgramForm.this.setModelObject(programService.save(ProgramForm.this.getModelObject())); + info("Saved"); + target.add(wmc); + onSave(target); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(wmc); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/EditResearchAreaPanel.java b/view/src/main/java/se/su/dsv/scipro/match/EditResearchAreaPanel.java index 306e1bf4a8..63f7bccec6 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/EditResearchAreaPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/EditResearchAreaPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -13,8 +14,6 @@ import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.ResearchAreaService; -import jakarta.inject.Inject; - public abstract class EditResearchAreaPanel extends Panel { @Inject @@ -31,11 +30,13 @@ public abstract class EditResearchAreaPanel extends Panel { public ResearchAreaForm(String id, IModel model) { super(id, model); - final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); - RequiredTextField researchArea = new RequiredTextField<>("researchArea", LambdaModel.of(model, ResearchArea::getTitle, ResearchArea::setTitle)); + RequiredTextField researchArea = new RequiredTextField<>( + "researchArea", + LambdaModel.of(model, ResearchArea::getTitle, ResearchArea::setTitle) + ); wmc.add(researchArea); wmc.add(new ComponentFeedbackPanel("researchAreaFeedback", researchArea)); @@ -45,20 +46,24 @@ public abstract class EditResearchAreaPanel extends Panel { add(wmc); - add(new AjaxButton("save") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - ResearchAreaForm.this.setModelObject(researchAreaService.save(ResearchAreaForm.this.getModelObject())); - info("Saved"); - target.add(wmc); - onSave(target); - } + add( + new AjaxButton("save") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + ResearchAreaForm.this.setModelObject( + researchAreaService.save(ResearchAreaForm.this.getModelObject()) + ); + info("Saved"); + target.add(wmc); + onSave(target); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(wmc); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/EditUnitPanel.java b/view/src/main/java/se/su/dsv/scipro/match/EditUnitPanel.java index a2a7d1f0b5..663f8cfba2 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/EditUnitPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/EditUnitPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -16,8 +17,6 @@ import org.apache.wicket.validation.validator.EmailAddressValidator; import se.su.dsv.scipro.springdata.services.UnitService; import se.su.dsv.scipro.system.Unit; -import jakarta.inject.Inject; - public abstract class EditUnitPanel extends Panel { @Inject @@ -34,15 +33,20 @@ public abstract class EditUnitPanel extends Panel { public UnitForm(String id, final IModel model) { super(id, model); - final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); - RequiredTextField unit = new RequiredTextField<>("unit", LambdaModel.of(model, Unit::getTitle, Unit::setTitle)); + RequiredTextField unit = new RequiredTextField<>( + "unit", + LambdaModel.of(model, Unit::getTitle, Unit::setTitle) + ); wmc.add(unit); wmc.add(new ComponentFeedbackPanel("unitFeedback", unit)); - FormComponent matchResponsible = new EmailTextField("matchResponsible", LambdaModel.of(model, Unit::getMatchResponsible, Unit::setMatchResponsible)); + FormComponent matchResponsible = new EmailTextField( + "matchResponsible", + LambdaModel.of(model, Unit::getMatchResponsible, Unit::setMatchResponsible) + ); matchResponsible.add(EmailAddressValidator.getInstance()); wmc.add(matchResponsible); wmc.add(new ComponentFeedbackPanel("matchResponsibleFeedback", matchResponsible)); @@ -53,20 +57,22 @@ public abstract class EditUnitPanel extends Panel { add(wmc); - add(new AjaxButton("save") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - UnitForm.this.setModelObject(unitService.save(UnitForm.this.getModelObject())); - info("Saved"); - target.add(wmc); - onSave(target); - } + add( + new AjaxButton("save") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + UnitForm.this.setModelObject(unitService.save(UnitForm.this.getModelObject())); + info("Saved"); + target.add(wmc); + onSave(target); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(wmc); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaAuthorInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaAuthorInfoPanel.java index 7368f928fc..774f584048 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaAuthorInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaAuthorInfoPanel.java @@ -12,16 +12,17 @@ public class IdeaAuthorInfoPanel extends GenericPanel { public IdeaAuthorInfoPanel(String id, IModel model) { super(id, model); - add(new ListView<>("authors", new ListAdapterModel<>(model.map(Idea::getIdeaParticipations))) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLabel("user", item.getModel().map(IdeaParticipation::getUser))); + add( + new ListView<>("authors", new ListAdapterModel<>(model.map(Idea::getIdeaParticipations))) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLabel("user", item.getModel().map(IdeaParticipation::getUser))); + } } - }); + ); Label noAuthor = new Label("noAuthor", "Not available"); noAuthor.setVisible(getModelObject().getIdeaParticipations().isEmpty()); add(noAuthor); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaDetailsPanel.java index f5c517e655..7afbe8fd28 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaDetailsPanel.java @@ -16,36 +16,61 @@ import se.su.dsv.scipro.system.ResearchArea; public class IdeaDetailsPanel extends Panel { - public IdeaDetailsPanel(String id, IModel model, boolean showDescriptionAndPrereqs) { - super(id, model); + public IdeaDetailsPanel(String id, IModel model, boolean showDescriptionAndPrereqs) { + super(id, model); add(new Label("projectType", model.map(Idea::getProjectType).map(ProjectType::getName))); - add(new ListView<>("languages", - new ListAdapterModel<>(LambdaModel.of(model, Idea::getLanguages, Idea::setLanguages))) { - @Override - protected void populateItem(final ListItem item) { - item.add(new EnumLabel<>("name", item.getModel())); - } - }); - add(new Label("area", new NullReplacementModel( - model.map(Idea::getResearchArea).map(ResearchArea::getTitle), "No research area selected"))); - add(new Label("applicationPeriod", new NullReplacementModel( - model.map(Idea::getApplicationPeriod).map(ApplicationPeriod::getName), "Not connected to an application period"))); + add( + new ListView<>( + "languages", + new ListAdapterModel<>(LambdaModel.of(model, Idea::getLanguages, Idea::setLanguages)) + ) { + @Override + protected void populateItem(final ListItem item) { + item.add(new EnumLabel<>("name", item.getModel())); + } + } + ); + add( + new Label( + "area", + new NullReplacementModel( + model.map(Idea::getResearchArea).map(ResearchArea::getTitle), + "No research area selected" + ) + ) + ); + add( + new Label( + "applicationPeriod", + new NullReplacementModel( + model.map(Idea::getApplicationPeriod).map(ApplicationPeriod::getName), + "Not connected to an application period" + ) + ) + ); addDescriptionAndPrerequisites(model, showDescriptionAndPrereqs); - addKeywords(model); - } + addKeywords(model); + } - private void addDescriptionAndPrerequisites(IModel model, boolean show) { - MultiLineLabel descLabel = new MultiLineLabel("description", LambdaModel.of(model, Idea::getDescription, Idea::setDescription)); - MultiLineLabel reqsLabel = new MultiLineLabel("reqs", new NullReplacementModel( - LambdaModel.of(model, Idea::getPrerequisites, Idea::setPrerequisites), "No prerequisites added")); - descLabel.setVisible(show); - add(descLabel); - add(reqsLabel); - } - - private void addKeywords(IModel model) { - add(new Label("noKeysLabel", "No keywords available").setVisible(model.getObject().getKeywords().isEmpty())); - add(new Label("keywords", new KeywordsModel(model))); - } + private void addDescriptionAndPrerequisites(IModel model, boolean show) { + MultiLineLabel descLabel = new MultiLineLabel( + "description", + LambdaModel.of(model, Idea::getDescription, Idea::setDescription) + ); + MultiLineLabel reqsLabel = new MultiLineLabel( + "reqs", + new NullReplacementModel( + LambdaModel.of(model, Idea::getPrerequisites, Idea::setPrerequisites), + "No prerequisites added" + ) + ); + descLabel.setVisible(show); + add(descLabel); + add(reqsLabel); + } + private void addKeywords(IModel model) { + add(new Label("noKeysLabel", "No keywords available").setVisible(model.getObject().getKeywords().isEmpty())); + add(new Label("keywords", new KeywordsModel(model))); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaDownloadPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaDownloadPanel.java index 1eda4ffd44..11a7f0479c 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaDownloadPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaDownloadPanel.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.match; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; import org.apache.wicket.request.resource.CharSequenceResource; -import java.util.stream.Collectors; - public class IdeaDownloadPanel extends GenericPanel { public IdeaDownloadPanel(String id, IModel model) { @@ -17,7 +16,11 @@ public class IdeaDownloadPanel extends GenericPanel { protected void onInitialize() { super.onInitialize(); String ideaString = getIdeaString(); - CharSequenceResource resource = new CharSequenceResource("text/plain; charset=utf8", ideaString, getModelObject().getTitle() + ".txt"); + CharSequenceResource resource = new CharSequenceResource( + "text/plain; charset=utf8", + ideaString, + getModelObject().getTitle() + ".txt" + ); add(new ResourceLink("download", resource)); } @@ -30,26 +33,62 @@ public class IdeaDownloadPanel extends GenericPanel { sb.append("Description: ").append(separator).append(idea.getDescription()).append(separator).append(separator); sb.append("Type: ").append(separator).append(idea.getType()).append(separator).append(separator); sb.append("Language: ").append(separator).append(getLanguageNames(idea)).append(separator).append(separator); - sb.append("Prerequisites: ").append(separator).append(idea.getPrerequisites()).append(separator).append(separator); + sb + .append("Prerequisites: ") + .append(separator) + .append(idea.getPrerequisites()) + .append(separator) + .append(separator); if (idea.getResearchArea() != null) { - sb.append("ResearchArea: ").append(separator).append(idea.getResearchArea().getTitle()).append(separator).append(separator); + sb + .append("ResearchArea: ") + .append(separator) + .append(idea.getResearchArea().getTitle()) + .append(separator) + .append(separator); } sb.append("Keywords: ").append(separator).append(idea.getKeywordNames()).append(separator).append(separator); sb.append("Authors: ").append(separator).append(idea.getAuthorNames()).append(separator).append(separator); - sb.append("Application period: ").append(separator).append(idea.getApplicationPeriod() == null ? "" : idea.getApplicationPeriod().getName()).append(separator).append(separator); + sb + .append("Application period: ") + .append(separator) + .append(idea.getApplicationPeriod() == null ? "" : idea.getApplicationPeriod().getName()) + .append(separator) + .append(separator); sb.append("<<\"Student idea form\">>").append(separator).append(separator); - sb.append("Background? ").append(separator).append(idea.getTholanderBox().getBackground()).append(separator).append(separator); - sb.append("Literature? ").append(separator).append(idea.getTholanderBox().getLiterature()).append(separator).append(separator); - sb.append("Problem? ").append(separator).append(idea.getTholanderBox().getProblem()).append(separator).append(separator); - sb.append("Method? ").append(separator).append(idea.getTholanderBox().getMethod()).append(separator).append(separator); + sb + .append("Background? ") + .append(separator) + .append(idea.getTholanderBox().getBackground()) + .append(separator) + .append(separator); + sb + .append("Literature? ") + .append(separator) + .append(idea.getTholanderBox().getLiterature()) + .append(separator) + .append(separator); + sb + .append("Problem? ") + .append(separator) + .append(idea.getTholanderBox().getProblem()) + .append(separator) + .append(separator); + sb + .append("Method? ") + .append(separator) + .append(idea.getTholanderBox().getMethod()) + .append(separator) + .append(separator); sb.append("Interests? ").append(separator).append(idea.getTholanderBox().getInterests()).append(separator); return sb.toString(); } private String getLanguageNames(final Idea idea) { - return idea.getLanguages() - .stream() - .map(language -> getString("Language." + language.name())) - .collect(Collectors.joining(", ")); + return idea + .getLanguages() + .stream() + .map(language -> getString("Language." + language.name())) + .collect(Collectors.joining(", ")); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaExportPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaExportPanel.java index 60f5bde069..21df7c2059 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaExportPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaExportPanel.java @@ -9,7 +9,6 @@ public class IdeaExportPanel extends GenericPanel { public IdeaExportPanel(String id, IModel model) { super(id, model); - add(new Label("reason", model.map(Idea::getExport).map(IdeaExport::getReason))); add(new Label("explanation", new ResourceModel("explanation"))); } @@ -19,5 +18,4 @@ public class IdeaExportPanel extends GenericPanel { super.onConfigure(); setVisibilityAllowed(getModelObject().isExported() && !getModelObject().wasExportSuccessful()); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderCompletionPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderCompletionPanel.java index 5b3555da44..26d4ce15c0 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderCompletionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderCompletionPanel.java @@ -7,15 +7,41 @@ import org.apache.wicket.model.LambdaModel; import org.apache.wicket.validation.validator.StringValidator; public class IdeaTholanderCompletionPanel extends Panel { + public IdeaTholanderCompletionPanel(String id, IModel model) { super(id, model); - final IModel tholanderBox = model.map(Idea::getTholanderBox); + final IModel tholanderBox = model.map(Idea::getTholanderBox); - final StringValidator lengthValidator = StringValidator.maximumLength(TholanderBox.MAX_CHARS); - add(new TextArea<>("background", LambdaModel.of(tholanderBox, TholanderBox::getBackground, TholanderBox::setBackground)).add(lengthValidator)); - add(new TextArea<>("literature", LambdaModel.of(tholanderBox, TholanderBox::getLiterature, TholanderBox::setLiterature)).add(lengthValidator)); - add(new TextArea<>("problem", LambdaModel.of(tholanderBox, TholanderBox::getProblem, TholanderBox::setProblem)).add(lengthValidator)); - add(new TextArea<>("method", LambdaModel.of(tholanderBox, TholanderBox::getMethod, TholanderBox::setMethod)).add(lengthValidator)); - add(new TextArea<>("interests", LambdaModel.of(tholanderBox, TholanderBox::getInterests, TholanderBox::setInterests)).add(lengthValidator)); - } + final StringValidator lengthValidator = StringValidator.maximumLength(TholanderBox.MAX_CHARS); + add( + new TextArea<>( + "background", + LambdaModel.of(tholanderBox, TholanderBox::getBackground, TholanderBox::setBackground) + ).add(lengthValidator) + ); + add( + new TextArea<>( + "literature", + LambdaModel.of(tholanderBox, TholanderBox::getLiterature, TholanderBox::setLiterature) + ).add(lengthValidator) + ); + add( + new TextArea<>( + "problem", + LambdaModel.of(tholanderBox, TholanderBox::getProblem, TholanderBox::setProblem) + ).add(lengthValidator) + ); + add( + new TextArea<>( + "method", + LambdaModel.of(tholanderBox, TholanderBox::getMethod, TholanderBox::setMethod) + ).add(lengthValidator) + ); + add( + new TextArea<>( + "interests", + LambdaModel.of(tholanderBox, TholanderBox::getInterests, TholanderBox::setInterests) + ).add(lengthValidator) + ); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderInfoPanel.java index 6cba90972e..4ebd630bcb 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/IdeaTholanderInfoPanel.java @@ -6,11 +6,11 @@ import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; public class IdeaTholanderInfoPanel extends GenericPanel { + private static final java.util.Date WATSON_TO_THOLANDER_SWITCH = new java.util.Date(1475591820000L); public IdeaTholanderInfoPanel(String id, IModel model) { - super(id, model); - + super(id, model); final WebMarkupContainer watson = new WebMarkupContainer("watson") { @Override protected void onConfigure() { @@ -43,8 +43,6 @@ public class IdeaTholanderInfoPanel extends GenericPanel { } private IModel replaceEmpty(final IModel inner) { - return inner - .filter(s -> !s.isBlank()) - .orElseGet(() -> getString("waiting")); + return inner.filter(s -> !s.isBlank()).orElseGet(() -> getString("waiting")); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/KeywordFilterPanel.java b/view/src/main/java/se/su/dsv/scipro/match/KeywordFilterPanel.java index 8140be653c..36d20e7a36 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/KeywordFilterPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/KeywordFilterPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.extensions.markup.html.form.palette.Palette; @@ -12,11 +16,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.components.CSPPalette; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - public class KeywordFilterPanel extends GenericPanel> { public static final String PALETTE = "palette"; @@ -30,21 +29,24 @@ public class KeywordFilterPanel extends GenericPanel> { public KeywordFilterPanel(String id, IModel> selectable, IModel> selected) { super(id, selectable); - if (selected != null && selected.getObject() != null) { this.selection = selected.getObject(); } - add(new PaletteForm(FORM, LambdaModel.>of(() -> selection, newSelection -> selection = newSelection), selectable)); + add( + new PaletteForm( + FORM, + LambdaModel.>of(() -> selection, newSelection -> selection = newSelection), + selectable + ) + ); } public List getSelection() { return this.selection; } - protected void onKeywordsSelected(AjaxRequestTarget target, Set keywords) { - - } + protected void onKeywordsSelected(AjaxRequestTarget target, Set keywords) {} private class PaletteForm extends Form> { @@ -59,13 +61,15 @@ public class KeywordFilterPanel extends GenericPanel> { protected Recorder newRecorderComponent() { Recorder recorder = super.newRecorderComponent(); recorder.setType(String.class); - recorder.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(AjaxRequestTarget target) { - processInput(); - onKeywordsSelected(target, new HashSet<>(getSelection())); + recorder.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + processInput(); + onKeywordsSelected(target, new HashSet<>(getSelection())); + } } - }); + ); return recorder; } }; @@ -74,7 +78,5 @@ public class KeywordFilterPanel extends GenericPanel> { private IChoiceRenderer getRenderer() { return new LambdaChoiceRenderer<>(Keyword::getKeyword, Keyword::getId); } - } - -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/match/KeywordsColumn.java b/view/src/main/java/se/su/dsv/scipro/match/KeywordsColumn.java index b84c15c119..752c153583 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/KeywordsColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/match/KeywordsColumn.java @@ -4,6 +4,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.export.Abstr import org.apache.wicket.model.IModel; class KeywordsColumn extends AbstractExportableColumn { + public KeywordsColumn(IModel displayModel) { super(displayModel); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/KeywordsModel.java b/view/src/main/java/se/su/dsv/scipro/match/KeywordsModel.java index 606bb0b073..f6d18112c8 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/KeywordsModel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/KeywordsModel.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.match; - +import java.util.stream.Collectors; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; -import java.util.stream.Collectors; - class KeywordsModel extends LoadableDetachableModel { + private final IModel idea; public KeywordsModel(IModel idea) { diff --git a/view/src/main/java/se/su/dsv/scipro/match/ManualMatching.java b/view/src/main/java/se/su/dsv/scipro/match/ManualMatching.java index e7dff2d432..4c00f673ac 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/ManualMatching.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ManualMatching.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import static java.util.Comparator.comparing; +import static java.util.Comparator.reverseOrder; +import static se.su.dsv.scipro.match.AbstractAdminIdeaPanel.PRESELECTED_APPLICATION_PERIOD; + +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.form.palette.Palette; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -13,24 +19,23 @@ import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.data.DetachableServiceModelCollection; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.*; - -import static java.util.Comparator.comparing; -import static java.util.Comparator.reverseOrder; -import static se.su.dsv.scipro.match.AbstractAdminIdeaPanel.PRESELECTED_APPLICATION_PERIOD; - public class ManualMatching extends AbstractAdminMatchPage { + @Inject private ResearchAreaService researchAreaService; + @Inject private KeywordService keywordService; + @Inject private UserService userService; + @Inject private ProjectTypeService projectTypeService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private IdeaService ideaService; @@ -39,8 +44,11 @@ public class ManualMatching extends AbstractAdminMatchPage { } private class ManualMatchingForm extends Form { - private final IModel applicationPeriod = - new DetachableServiceModel<>(applicationPeriodService, getSession().getMetaData(PRESELECTED_APPLICATION_PERIOD)); + + private final IModel applicationPeriod = new DetachableServiceModel<>( + applicationPeriodService, + getSession().getMetaData(PRESELECTED_APPLICATION_PERIOD) + ); private final IModel researchArea = new DetachableServiceModel<>(researchAreaService); private final IModel> keywords = new DetachableServiceModelCollection<>(keywordService); private final IModel supervisor = new DetachableServiceModel<>(userService); @@ -52,30 +60,37 @@ public class ManualMatching extends AbstractAdminMatchPage { private ManualMatchingForm(final String id) { super(id); - add(new FeedbackPanel("feedback")); - final AjaxDropDownChoice applicationPeriodChoice = - new AjaxDropDownChoice<>( - "applicationPeriod", - applicationPeriod, - getApplicationPeriods(), - new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId)) { - @Override - public void onNewSelection(final AjaxRequestTarget target, final ApplicationPeriod ap) { - getSession().setMetaData(PRESELECTED_APPLICATION_PERIOD, ap != null ? ap.getId() : null); - } - }; + final AjaxDropDownChoice applicationPeriodChoice = new AjaxDropDownChoice<>( + "applicationPeriod", + applicationPeriod, + getApplicationPeriods(), + new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId) + ) { + @Override + public void onNewSelection(final AjaxRequestTarget target, final ApplicationPeriod ap) { + getSession().setMetaData(PRESELECTED_APPLICATION_PERIOD, ap != null ? ap.getId() : null); + } + }; applicationPeriodChoice.setRequired(true); add(applicationPeriodChoice); - final CheckBoxMultipleChoice languageChoice = - new BootstrapCheckBoxMultipleChoice<>("languages", this.languages, Arrays.asList(Language.values()), new EnumChoiceRenderer<>(this)); + final CheckBoxMultipleChoice languageChoice = new BootstrapCheckBoxMultipleChoice<>( + "languages", + this.languages, + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ); languageChoice.setRequired(true); add(languageChoice); - final RadioChoice projectTypeChoice = - new BootstrapRadioChoice<>("projectType", this.projectType, getProjectTypes(), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); + final RadioChoice projectTypeChoice = new BootstrapRadioChoice<>( + "projectType", + this.projectType, + getProjectTypes(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); projectTypeChoice.setRequired(true); add(projectTypeChoice); @@ -92,21 +107,28 @@ public class ManualMatching extends AbstractAdminMatchPage { final WebMarkupContainer keywordContainer = new WebMarkupContainer("keywordContainer"); keywordContainer.setOutputMarkupId(true); - final AjaxDropDownChoice researchAreaChoice = - new AjaxDropDownChoice<>( - "researchAreas", - researchArea, - getResearchAreas(), - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(final AjaxRequestTarget target, final ResearchArea objectSelected) { - target.add(keywordContainer); - } - }; + final AjaxDropDownChoice researchAreaChoice = new AjaxDropDownChoice<>( + "researchAreas", + researchArea, + getResearchAreas(), + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(final AjaxRequestTarget target, final ResearchArea objectSelected) { + target.add(keywordContainer); + } + }; researchAreaChoice.setRequired(true); add(researchAreaChoice); - final Palette keywordPalette = new CSPPalette<>("keywords", keywords, getKeywords(researchArea), new LambdaChoiceRenderer<>(Keyword::getKeyword, Keyword::getId), 10, false) { + final Palette keywordPalette = new CSPPalette<>( + "keywords", + keywords, + getKeywords(researchArea), + new LambdaChoiceRenderer<>(Keyword::getKeyword, Keyword::getId), + 10, + false + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -134,11 +156,7 @@ public class ManualMatching extends AbstractAdminMatchPage { for (User author : authors.getObject()) { idea.addIdeaParticipation(new IdeaParticipation(author, idea)); } - ideaService.saveSupervisorIdea( - idea, - supervisor.getObject(), - new ArrayList<>(keywords.getObject()), - true); + ideaService.saveSupervisorIdea(idea, supervisor.getObject(), new ArrayList<>(keywords.getObject()), true); getSession().success("Idea created"); setResponsePage(ManualMatching.class); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanel.java index a1d4fa13ba..6a28e63b07 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -25,19 +27,20 @@ import se.su.dsv.scipro.match.Idea.Type; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.*; - public class ProjectAllSupervisorIdeasPanel extends GenericPanel { @Inject private IdeaService ideaService; + @Inject private IdeaFacade ideaFacade; + @Inject private KeywordService keywordService; + @Inject private ResearchAreaService researchAreaService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -63,12 +66,23 @@ public class ProjectAllSupervisorIdeasPanel extends GenericPanel provider = new SortableDataProvider<>() { @Override public Iterator iterator(long first, long count) { - return ideaFacade.findIdeasPossibleToMatch(applicationPeriod.getObject(), SciProSession.get().getUser(), params, new PageAdapter(first, count, getSort())).iterator(); + return ideaFacade + .findIdeasPossibleToMatch( + applicationPeriod.getObject(), + SciProSession.get().getUser(), + params, + new PageAdapter(first, count, getSort()) + ) + .iterator(); } @Override public long size() { - return ideaFacade.countIdeasPossibleToMatch(applicationPeriod.getObject(), SciProSession.get().getUser(), params); + return ideaFacade.countIdeasPossibleToMatch( + applicationPeriod.getObject(), + SciProSession.get().getUser(), + params + ); } @Override @@ -86,42 +100,64 @@ public class ProjectAllSupervisorIdeasPanel extends GenericPanel(Model.of("Created"), Idea::getDateCreated, "dateCreated")); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Languages")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getLanguages, Idea::setLanguages))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new EnumLabel<>(componentId, t); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Languages")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getLanguages, Idea::setLanguages)) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new EnumLabel<>(componentId, t); + } + } + ); + } } - }); + ); - columns.add(new AbstractColumn<>(Model.of("Title"), "title") { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - modalWindowPlus.setContent(new AcceptIdeaDialogPanel(modalWindowPlus.getContentId(), model, applicationPeriod)); - modalWindowPlus.setTitle(model.getObject().getTitle()); - modalWindowPlus.show(target); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Title"), "title") { + @Override + public void populateItem(Item> components, String s, final IModel model) { + components.add( + new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + modalWindowPlus.setContent( + new AcceptIdeaDialogPanel(modalWindowPlus.getContentId(), model, applicationPeriod) + ); + modalWindowPlus.setTitle(model.getObject().getTitle()); + modalWindowPlus.show(target); + } + } + ); + } } - }); + ); columns.add(new UserColumn<>(Model.of("Supervisor"), "creator.fullName", Idea::getCreator)); - columns.add(new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null)); + columns.add( + new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> + idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null + ) + ); columns.add(new KeywordsColumn<>(Model.of("Keywords"))); return columns; } private void addFiltering() { - IModel> projectTypes = LoadableDetachableModel.of(() -> applicationPeriodService - .getTypesForStudent(getModelObject(), SciProSession.get().getUser())); + IModel> projectTypes = LoadableDetachableModel.of(() -> + applicationPeriodService.getTypesForStudent(getModelObject(), SciProSession.get().getUser()) + ); params = new IdeaService.Filter(); @@ -129,8 +165,12 @@ public class ProjectAllSupervisorIdeasPanel extends GenericPanel projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - LambdaModel.of(params::getLevels, params::setLevels), projectTypes, new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + LambdaModel.of(params::getLevels, params::setLevels), + projectTypes, + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { target.add(dataTable); @@ -153,17 +193,24 @@ public class ProjectAllSupervisorIdeasPanel extends GenericPanel("areaFilter", new Model<>(), + add( + new AjaxDropDownChoice<>( + "areaFilter", + new Model<>(), new ListModel<>(researchAreaService.findNotDeleted()), - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { - params.setResearchArea(getModelObject()); - target.add(dataTable); - keywordFilter.setVisible(objectSelected != null && !keywordService.findByResearchArea(params.getResearchArea()).isEmpty()); - target.add(keywordFilter); + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { + params.setResearchArea(getModelObject()); + target.add(dataTable); + keywordFilter.setVisible( + objectSelected != null && !keywordService.findByResearchArea(params.getResearchArea()).isEmpty() + ); + target.add(keywordFilter); + } } - }); + ); } private IModel> getKeywords() { diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPage.java index d3a35640cc..60138e9632 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -8,15 +9,13 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightProjectMyIdeas; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class ProjectIdeaDetailsPage extends AbstractIdeaProjectPage implements MenuHighlightProjectMyIdeas { + @Inject IdeaService ideaService; public ProjectIdeaDetailsPage(PageParameters pp) { super(pp); - final long ideaId; try { ideaId = pp.get(PageParameterKeys.MAP.get(Idea.class)).toLong(); @@ -29,35 +28,47 @@ public class ProjectIdeaDetailsPage extends AbstractIdeaProjectPage implements M throw new RestartResponseException(getApplication().getHomePage()); } final boolean isAuthor = idea - .getIdeaParticipations() - .stream() - .anyMatch(ideaParticipation -> ideaParticipation.getUser().equals(loggedInUser())); + .getIdeaParticipations() + .stream() + .anyMatch(ideaParticipation -> ideaParticipation.getUser().equals(loggedInUser())); if (!isAuthor) { throw new RestartResponseException(ProjectIdeaStartPage.class); } final DetachableServiceModel ideaModel = new DetachableServiceModel<>(ideaService, idea); add(new Label("title", ideaModel.map(Idea::getTitle))); - add(new CompleteIdeaDialogPanel("complete_supervisor_idea", ideaModel) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().getType() == Idea.Type.SUPERVISOR && ideaService.canEdit(getModelObject(), loggedInUser())); + add( + new CompleteIdeaDialogPanel("complete_supervisor_idea", ideaModel) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + getModelObject().getType() == Idea.Type.SUPERVISOR && + ideaService.canEdit(getModelObject(), loggedInUser()) + ); + } } - }); - add(new ProjectIdeaSubmissionPanel("edit_student_idea", ideaModel, false) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().getType() == Idea.Type.STUDENT && ideaService.canEdit(getModelObject(), loggedInUser())); + ); + add( + new ProjectIdeaSubmissionPanel("edit_student_idea", ideaModel, false) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + getModelObject().getType() == Idea.Type.STUDENT && + ideaService.canEdit(getModelObject(), loggedInUser()) + ); + } } - }); - add(new ProjectIdeaDetailsPanel("view_idea", ideaModel, this::loggedInUser) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!ideaService.canEdit(getModelObject(), loggedInUser())); + ); + add( + new ProjectIdeaDetailsPanel("view_idea", ideaModel, this::loggedInUser) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!ideaService.canEdit(getModelObject(), loggedInUser())); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPanel.java index f08c333f0f..e1f9112194 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaDetailsPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.basic.MultiLineLabel; @@ -14,11 +17,8 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Predicate; - public class ProjectIdeaDetailsPanel extends GenericPanel { + private final IModel currentUser; public ProjectIdeaDetailsPanel(final String id, final IModel model, final IModel currentUser) { @@ -27,57 +27,70 @@ public class ProjectIdeaDetailsPanel extends GenericPanel { add(new Label("title", model.map(Idea::getTitle))); add(new Label("type", model.map(Idea::getProjectType).map(ProjectType::getName))); - add(new AutoHidingListView<>("languages", model.map(Idea::getLanguages).map(ArrayList::new)) { - @Override - protected void populateItem(final ListItem item) { - item.add(new EnumLabel<>("language", item.getModel())); + add( + new AutoHidingListView<>("languages", model.map(Idea::getLanguages).map(ArrayList::new)) { + @Override + protected void populateItem(final ListItem item) { + item.add(new EnumLabel<>("language", item.getModel())); + } } - }); - add(new ListView<>("partners", model.map(this::getPartners)) { - @Override - protected void populateItem(final ListItem item) { - item.add(new UserLinkPanel("partner", item.getModel())); + ); + add( + new ListView<>("partners", model.map(this::getPartners)) { + @Override + protected void populateItem(final ListItem item) { + item.add(new UserLinkPanel("partner", item.getModel())); + } } - }); + ); - add(new IdeaTholanderInfoPanel("box", model) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject().getType() == Idea.Type.STUDENT); + add( + new IdeaTholanderInfoPanel("box", model) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject().getType() == Idea.Type.STUDENT); + } } - }); + ); - add(new MultiLineLabel("description", model.map(Idea::getDescription)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject().getType() == Idea.Type.SUPERVISOR); + add( + new MultiLineLabel("description", model.map(Idea::getDescription)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject().getType() == Idea.Type.SUPERVISOR); + } } - }); - add(new MultiLineLabel("prerequisites", model.map(Idea::getPrerequisites)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject().getType() == Idea.Type.SUPERVISOR); + ); + add( + new MultiLineLabel("prerequisites", model.map(Idea::getPrerequisites)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject().getType() == Idea.Type.SUPERVISOR); + } } - }); + ); add(new Label("research_area", model.map(Idea::getResearchArea).map(ResearchArea::getTitle))); - add(new ListView<>("keywords", model.map(Idea::getKeywords).map(ArrayList::new)) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label("keyword", item.getModel().map(Keyword::getKeyword))); + add( + new ListView<>("keywords", model.map(Idea::getKeywords).map(ArrayList::new)) { + @Override + protected void populateItem(final ListItem item) { + item.add(new Label("keyword", item.getModel().map(Keyword::getKeyword))); + } } - }); + ); } private List getPartners(final Idea idea) { - return idea.getIdeaParticipations() - .stream() - .map(IdeaParticipation::getUser) - .filter(Predicate.not(currentUser.getObject()::equals)) - .toList(); + return idea + .getIdeaParticipations() + .stream() + .map(IdeaParticipation::getUser) + .filter(Predicate.not(currentUser.getObject()::equals)) + .toList(); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaStartPage.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaStartPage.java index 22e7bbf687..f772a84856 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaStartPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -10,9 +11,7 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) public class ProjectIdeaStartPage extends AbstractIdeaProjectPage implements MenuHighlightProjectIdeas { @Inject @@ -29,17 +28,20 @@ public class ProjectIdeaStartPage extends AbstractIdeaProjectPage implements Men private void addMoreInfoAboutIdeaLink() { final String link = systemSettingsService.getExternalGettingStartedWithIdeaURL(); - add(new ExternalLink("moreInfo", link) { - @Override - protected void onComponentTag(ComponentTag tag) { - super.onComponentTag(tag); - tag.put("target", "_blank"); + add( + new ExternalLink("moreInfo", link) { + @Override + protected void onComponentTag(ComponentTag tag) { + super.onComponentTag(tag); + tag.put("target", "_blank"); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(link != null); + } } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(link != null); - } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPage.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPage.java index cbcba793e7..eaac821370 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.RestartResponseException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.string.StringValue; @@ -10,20 +12,19 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - -@Authorization(authorizedRoles={Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) public class ProjectIdeaSubmissionPage extends AbstractIdeaProjectPage implements MenuHighlightProjectIdeas { + public static final String SUBMISSION_PANEL = "submissionPanel"; + + @Inject + private IdeaService ideaService; + @Inject - private IdeaService ideaService; - @Inject private ApplicationPeriodService applicationPeriodService; - public ProjectIdeaSubmissionPage(PageParameters pp) { + public ProjectIdeaSubmissionPage(PageParameters pp) { super(pp); - Long ideaId = getIdFromParameter(pp, PageParameterKeys.MAP.get(Idea.class)); Long applicationPeriodId = getIdFromParameter(pp, PageParameterKeys.MAP.get(ApplicationPeriod.class)); @@ -33,7 +34,11 @@ public class ProjectIdeaSubmissionPage extends AbstractIdeaProjectPage implement if (ideaId != null) { idea = ideaService.findOne(ideaId); isNewIdea = false; - if (!idea.getCreator().equals(loggedInUser()) || idea.getMatchStatus() != Idea.Status.UNMATCHED || !applicationPeriodService.isOpen(idea.getApplicationPeriod())) { + if ( + !idea.getCreator().equals(loggedInUser()) || + idea.getMatchStatus() != Idea.Status.UNMATCHED || + !applicationPeriodService.isOpen(idea.getApplicationPeriod()) + ) { failAndRedirect(); } } else { @@ -44,11 +49,14 @@ public class ProjectIdeaSubmissionPage extends AbstractIdeaProjectPage implement if (applicationPeriod == null) { throw new RestartResponseException(ProjectIdeaStartPage.class); } - final List availablePeriods = applicationPeriodService.getCurrentStudentPeriods(SciProSession.get().getUser()); - final boolean isPeriodAvailableForSubmission = availablePeriods.stream() - .filter(StudentPeriod::allowedToSubmitIdea) - .map(StudentPeriod::getApplicationPeriod) - .anyMatch(applicationPeriod::equals); + final List availablePeriods = applicationPeriodService.getCurrentStudentPeriods( + SciProSession.get().getUser() + ); + final boolean isPeriodAvailableForSubmission = availablePeriods + .stream() + .filter(StudentPeriod::allowedToSubmitIdea) + .map(StudentPeriod::getApplicationPeriod) + .anyMatch(applicationPeriod::equals); if (!isPeriodAvailableForSubmission) { throw new RestartResponseException(ProjectIdeaStartPage.class); } @@ -56,21 +64,21 @@ public class ProjectIdeaSubmissionPage extends AbstractIdeaProjectPage implement isNewIdea = true; idea.setApplicationPeriod(applicationPeriod); } - add(new ProjectIdeaSubmissionPanel(SUBMISSION_PANEL, new DetachableServiceModel<>(ideaService, idea), isNewIdea)); - } + add( + new ProjectIdeaSubmissionPanel(SUBMISSION_PANEL, new DetachableServiceModel<>(ideaService, idea), isNewIdea) + ); + } private Long getIdFromParameter(PageParameters pp, String parameter) { Long id = null; StringValue value = pp.get(parameter); - if(!value.isNull()) { + if (!value.isNull()) { id = value.toLongObject(); } return id; } private void failAndRedirect() { - throw new RestartResponseException(getApplication().getApplicationSettings() - .getAccessDeniedPage()); - } - + throw new RestartResponseException(getApplication().getApplicationSettings().getAccessDeniedPage()); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanel.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanel.java index ebc4a70d71..acdf6b0655 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.*; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; @@ -25,10 +28,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.*; -import java.util.stream.Collectors; - public class ProjectIdeaSubmissionPanel extends GenericPanel { public static final String PROJECT_TYPE = "projectType"; @@ -36,18 +35,25 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { public static final String IDEA_FORM = "ideaForm"; public static final String PROGRAM = "program"; public static final String PROGRAM_DROP_DOWN = "programDropDown"; + @Inject private IdeaService ideaService; + @Inject private ResearchAreaService researchAreaService; + @Inject private KeywordService keywordService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private UserService userService; + @Inject private ProjectService projectService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; @@ -57,7 +63,6 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { public ProjectIdeaSubmissionPanel(String id, IModel model, boolean isNewIdea) { super(id, model); - pp = new PageParameters(); pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), model.getObject().getApplicationPeriod().getId()); @@ -79,7 +84,7 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { add(feedback); } - private LoadableDetachableModel getLoadedStudent(){ + private LoadableDetachableModel getLoadedStudent() { return new LoadableDetachableModel<>() { @Override protected User load() { @@ -106,7 +111,9 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { super(id, model); this.isNewIdea = isNewIdea; this.creator = SciProSession.get().getUser(); - final LoadableDetachableModel generalSystemSettings = LoadableDetachableModel.of(generalSystemSettingsService::getGeneralSystemSettingsInstance); + final LoadableDetachableModel generalSystemSettings = LoadableDetachableModel.of( + generalSystemSettingsService::getGeneralSystemSettingsInstance + ); supportMail = generalSystemSettings.map(GeneralSystemSettings::getActiveProjectIdeaSupportMail); addProjectTypeSelection(); addLanguageSelection(); @@ -124,30 +131,36 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { protected void onConfigure() { super.onConfigure(); final ApplicationPeriod applicationPeriod = getModelObject().getApplicationPeriod(); - setEnabled(applicationPeriodService.isOpen(applicationPeriod) - || applicationPeriodService.hasCurrentSubmitIdeaExemption(applicationPeriod, SciProSession.get().getUser())); + setEnabled( + applicationPeriodService.isOpen(applicationPeriod) || + applicationPeriodService.hasCurrentSubmitIdeaExemption(applicationPeriod, SciProSession.get().getUser()) + ); } private void addDeleteButton() { - add(new ConfirmationLink<>("delete", getModel(), Model.of("Are you sure you want to delete the idea?")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!isNewIdea); - } + add( + new ConfirmationLink<>("delete", getModel(), Model.of("Are you sure you want to delete the idea?")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!isNewIdea); + } - @Override - public void onClick() { - ideaService.delete(getModelObject()); - setResponsePage(ProjectIdeaStartPage.class); + @Override + public void onClick() { + ideaService.delete(getModelObject()); + setResponsePage(ProjectIdeaStartPage.class); + } } - }); + ); } private void addProjectTypeSelection() { IModel> projectTypes = getModel() - .map(Idea::getApplicationPeriod) - .map(applicationPeriod -> applicationPeriodService.getTypesForStudent(applicationPeriod, SciProSession.get().getUser())); + .map(Idea::getApplicationPeriod) + .map(applicationPeriod -> + applicationPeriodService.getTypesForStudent(applicationPeriod, SciProSession.get().getUser()) + ); final var activeProjectWarning = new WebMarkupContainer("activeProjectWarning") { { add(new ExternalLink("supportMail", supportMail.map(mail -> "mailto:" + mail), supportMail)); @@ -159,26 +172,31 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { final ProjectType selectedProjectType = getModelObject().getProjectType(); if (selectedProjectType != null) { final boolean hasActiveProject = !projectService - .getActiveProjectsByUserAndProjectType(SciProSession.get().getUser(), selectedProjectType) - .isEmpty(); + .getActiveProjectsByUserAndProjectType(SciProSession.get().getUser(), selectedProjectType) + .isEmpty(); setVisible(hasActiveProject); - } - else { + } else { setVisible(false); } } }; activeProjectWarning.setOutputMarkupPlaceholderTag(true); add(activeProjectWarning); - projectTypeChoice = new BootstrapRadioChoice<>(PROJECT_TYPE, LambdaModel.of(getModel(), Idea::getProjectType, Idea::setProjectType), - projectTypes, new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); - projectTypeChoice.add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(activeProjectWarning); - target.add(activePartnerProjectWarning); + projectTypeChoice = new BootstrapRadioChoice<>( + PROJECT_TYPE, + LambdaModel.of(getModel(), Idea::getProjectType, Idea::setProjectType), + projectTypes, + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); + projectTypeChoice.add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(activeProjectWarning); + target.add(activePartnerProjectWarning); + } } - }); + ); projectTypeChoice.setRequired(true); add(projectTypeChoice); add(new ComponentFeedbackPanel("projectTypeFeedback", projectTypeChoice)); @@ -186,11 +204,11 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { private void addCoAuthorSelection() { final Set partners = getModelObject() - .getIdeaParticipations() - .stream() - .map(IdeaParticipation::getUser) - .filter(user -> !user.equals(SciProSession.get().getUser())) - .collect(Collectors.toSet()); + .getIdeaParticipations() + .stream() + .map(IdeaParticipation::getUser) + .filter(user -> !user.equals(SciProSession.get().getUser())) + .collect(Collectors.toSet()); activePartnerProjectWarning = new WebMarkupContainer("activePartnerProjectWarning") { { add(new ExternalLink("supportMail", supportMail.map(mail -> "mailto:" + mail), supportMail)); @@ -201,15 +219,17 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { super.onConfigure(); final ProjectType selectedProjectType = getModelObject().getProjectType(); if (selectedProjectType != null) { - final boolean partnerHasActiveProject = coAuthorChoice.getModelObject() - .stream() - .map(partner -> projectService.getActiveProjectsByUserAndProjectType(partner, selectedProjectType)) - .flatMap(Collection::stream) - .findAny() - .isPresent(); + final boolean partnerHasActiveProject = coAuthorChoice + .getModelObject() + .stream() + .map(partner -> + projectService.getActiveProjectsByUserAndProjectType(partner, selectedProjectType) + ) + .flatMap(Collection::stream) + .findAny() + .isPresent(); setVisible(partnerHasActiveProject); - } - else { + } else { setVisible(false); } } @@ -217,12 +237,14 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { activePartnerProjectWarning.setOutputMarkupPlaceholderTag(true); add(activePartnerProjectWarning); coAuthorChoice = new CoAuthorChoice(CO_AUTHOR_CHOICE, Model.of(partners)); - coAuthorChoice.add(new AjaxFormComponentUpdatingBehavior("change") { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(activePartnerProjectWarning); + coAuthorChoice.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(activePartnerProjectWarning); + } } - }); + ); add(coAuthorChoice); add(new ComponentFeedbackPanel("coAuthorFeedback", coAuthorChoice)); add(new BookmarkablePageLink("partnerLink", ProjectPartnerPage.class)); @@ -238,22 +260,30 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { } }; add(program); - final Program currentProgram = getModelObject().getIdeaParticipations() - .stream() - .filter(ip -> ip.getUser().equals(student)) - .findAny() - .map(IdeaParticipation::getProgram) - .orElse(null); - programDropDownChoice = new DropDownChoice<>(PROGRAM_DROP_DOWN, new Model<>(currentProgram), - new ArrayList<>(student.getPrograms()), new LambdaChoiceRenderer<>(Program::getName, Program::getId)); + final Program currentProgram = getModelObject() + .getIdeaParticipations() + .stream() + .filter(ip -> ip.getUser().equals(student)) + .findAny() + .map(IdeaParticipation::getProgram) + .orElse(null); + programDropDownChoice = new DropDownChoice<>( + PROGRAM_DROP_DOWN, + new Model<>(currentProgram), + new ArrayList<>(student.getPrograms()), + new LambdaChoiceRenderer<>(Program::getName, Program::getId) + ); programDropDownChoice.setNullValid(true); program.add(programDropDownChoice); } - private void addLanguageSelection() { - CheckBoxMultipleChoice language = new BootstrapCheckBoxMultipleChoice<>("languages", LambdaModel.of(getModel(), Idea::getLanguages, Idea::setLanguages), - Arrays.asList(Language.values()), new EnumChoiceRenderer<>(this)); + CheckBoxMultipleChoice language = new BootstrapCheckBoxMultipleChoice<>( + "languages", + LambdaModel.of(getModel(), Idea::getLanguages, Idea::setLanguages), + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ); language.setRequired(true); add(new ComponentFeedbackPanel("languageFeedback", language)); add(language); @@ -261,7 +291,10 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { } private void addTitleField() { - TextField title = new TextField<>("title", LambdaModel.of(getModel(), Idea::getTitle, Idea::setTitle)); + TextField title = new TextField<>( + "title", + LambdaModel.of(getModel(), Idea::getTitle, Idea::setTitle) + ); title.setRequired(true); title.add(StringValidator.minimumLength(MIN_TITLE_LENGTH)); add(new ComponentFeedbackPanel("titleFeedback", title)); @@ -278,8 +311,12 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { List areas = researchAreaService.findNotDeleted(); - AjaxDropDownChoice areaDropDown = new AjaxDropDownChoice<>("area", LambdaModel.of(getModel(), Idea::getResearchArea, Idea::setResearchArea), - new ListModel<>(areas), new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { + AjaxDropDownChoice areaDropDown = new AjaxDropDownChoice<>( + "area", + LambdaModel.of(getModel(), Idea::getResearchArea, Idea::setResearchArea), + new ListModel<>(areas), + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { @Override public void onNewSelection(AjaxRequestTarget target, ResearchArea selected) { Set keywordHashSet = new HashSet<>(keywordService.findByResearchArea(selected)); @@ -294,10 +331,14 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { areaContainer.add(new ComponentFeedbackPanel("researchAreaFeedback", areaDropDown)); final Set keywords = getModelObject().getResearchArea() == null - ? new HashSet<>() - : new HashSet<>(keywordService.findByResearchArea(getModelObject().getResearchArea())); + ? new HashSet<>() + : new HashSet<>(keywordService.findByResearchArea(getModelObject().getResearchArea())); ProjectIdeaSubmissionPanel.this.keywords = getModelObject().getKeywords(); - keywordsPanel = new KeywordFilterPanel("keywords", new SetModel<>(keywords), new ListModel<>(new ArrayList<>(getModelObject().getKeywords()))) { + keywordsPanel = new KeywordFilterPanel( + "keywords", + new SetModel<>(keywords), + new ListModel<>(new ArrayList<>(getModelObject().getKeywords())) + ) { @Override public void onKeywordsSelected(AjaxRequestTarget target, Set selected) { ProjectIdeaSubmissionPanel.this.keywords = selected; @@ -322,8 +363,14 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { @Override protected void onSubmit() { - Idea idea = ideaService.saveStudentIdea(getModelObject(), creator, programDropDownChoice.getModelObject(), new HashSet<>(coAuthorChoice.getModelObject()), - new ArrayList<>(keywords), isNewIdea); + Idea idea = ideaService.saveStudentIdea( + getModelObject(), + creator, + programDropDownChoice.getModelObject(), + new HashSet<>(coAuthorChoice.getModelObject()), + new ArrayList<>(keywords), + isNewIdea + ); if (isNewIdea) { getSession().success(getString("ideaSubmitted", Model.of(idea))); } else { @@ -332,7 +379,6 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { setResponsePage(ProjectIdeaStartPage.class); } - @Override protected void onError() { if (getFeedbackMessages().isEmpty()) { @@ -348,11 +394,23 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { } final Collection partners = new HashSet<>(coAuthorChoice.getConvertedInput()); for (User partner : partners) { - if (ideaService.authorParticipatingOnOtherActiveIdea(partner, getModelObject().getApplicationPeriod(), getModelObject())) { + if ( + ideaService.authorParticipatingOnOtherActiveIdea( + partner, + getModelObject().getApplicationPeriod(), + getModelObject() + ) + ) { coAuthorChoice.error(getString("coAuthorParticipating", Model.of(partner))); } } - if (ideaService.authorParticipatingOnOtherActiveIdea(SciProSession.get().getUser(), getModelObject().getApplicationPeriod(), getModelObject())) { + if ( + ideaService.authorParticipatingOnOtherActiveIdea( + SciProSession.get().getUser(), + getModelObject().getApplicationPeriod(), + getModelObject() + ) + ) { error(getString("you.are.partner.on.other.idea")); } if (partners.contains(SciProSession.get().getUser())) { @@ -360,7 +418,11 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { } final ProjectType projectType = projectTypeChoice.getConvertedInput(); if (projectType != null) { - if (!projectService.getActiveProjectsByUserAndProjectType(SciProSession.get().getUser(), projectType).isEmpty()) { + if ( + !projectService + .getActiveProjectsByUserAndProjectType(SciProSession.get().getUser(), projectType) + .isEmpty() + ) { error(getString("you.already.have.an.active.project.on.this.level")); } for (User partner : partners) { @@ -368,7 +430,12 @@ public class ProjectIdeaSubmissionPanel extends GenericPanel { error(getString("partner.already.has.an.active.project.on.this.level", Model.of(partner))); } } - if (!applicationPeriodService.hasIdeaSizeExemption(SciProSession.get().getUser(), getModelObject().getApplicationPeriod())) { + if ( + !applicationPeriodService.hasIdeaSizeExemption( + SciProSession.get().getUser(), + getModelObject().getApplicationPeriod() + ) + ) { if (partners.size() < projectType.getMinAuthors() - 1) { coAuthorChoice.error(getString("too.few.authors", Model.of(projectType))); } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectMyIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectMyIdeasPanel.java index 3e9e7f12b5..5d4c93d4e4 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectMyIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectMyIdeasPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -16,27 +20,24 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.*; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.firstmeeting.FirstMeetingColumnPanel; import se.su.dsv.scipro.firstmeeting.FirstMeetingPanel; import se.su.dsv.scipro.match.Idea.Type; import se.su.dsv.scipro.profile.StudentProfileProgramPanel; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class ProjectMyIdeasPanel extends Panel { public static final String DATA_TABLE = "dataTable"; + @Inject private IdeaService ideaService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -57,7 +58,12 @@ public class ProjectMyIdeasPanel extends Panel { SortableDataProvider provider = new SortableDataProvider<>() { @Override public Iterator iterator(long first, long count) { - return ideaService.findAuthorIdeas(author, new PageRequest(first, count, new Sort(Sort.Direction.DESC, "dateCreated"))).iterator(); + return ideaService + .findAuthorIdeas( + author, + new PageRequest(first, count, new Sort(Sort.Direction.DESC, "dateCreated")) + ) + .iterator(); } @Override @@ -74,91 +80,138 @@ public class ProjectMyIdeasPanel extends Panel { } private List> createColumns() { - List> columns = new ArrayList<>(); columns.add(new DateColumn<>(Model.of("Created"), Idea::getDateCreated, "dateCreated")); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Title"), "title") { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel model) { - cellItem.add(LinkWrapper.apply(componentId, linkId -> { - PageParameters pageParameters = new PageParameters(); - pageParameters.set(PageParameterKeys.MAP.get(Idea.class), model.getObject().getId()); - AbstractLink link = new BookmarkablePageLink<>(linkId, ProjectIdeaDetailsPage.class, pageParameters); - link.setBody(LambdaModel.of(model, Idea::getTitle, Idea::setTitle)); - return link; - })); - } - }); - - columns.add(new AbstractColumn<>(Model.of("Authors")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new StudentProfileProgramPanel(componentId, t, false); - } - }); - } - }); - columns.add(new AbstractColumn<>(Model.of("Status"), "match.status") { - @Override - public void populateItem(Item> item, String id, IModel model) { - item.add(new Label(id, model.map(idea -> switch (idea.getMatchStatus()) { - case UNMATCHED -> "Submitted, waiting for matching by administrator"; - case MATCHED -> { - if (applicationPeriodService.courseStartHasPassed(idea.getApplicationPeriod())) { - yield "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you."; - } else { - yield "Matched, awaiting course start date"; - } - } - case COMPLETED -> "Matched, project started"; - case INACTIVE -> "Inactive"; - }))); - } - }); - - columns.add(new AbstractColumn<>(Model.of("Course start date")) { - @Override - public void populateItem(Item> item, String id, IModel iModel) { - item.add(new Label(id, iModel.map(Idea::getApplicationPeriod).map(ApplicationPeriod::getCourseStartDate))); - } - }); - - columns.add(new AbstractColumn<>(Model.of("Supervisor")) { - @Override - public void populateItem(Item> item, String id, IModel model) { - Idea idea = model.getObject(); - if ((idea.getType() == Type.SUPERVISOR || applicationPeriodService.courseStartHasPassed(idea.getApplicationPeriod())) && idea.getMatch().getSupervisor() != null) { - item.add(new Label(id, idea.getMatch().getSupervisor().getFullName())); - } else { - item.add(new Label(id, "Visible on course start date")); + columns.add( + new AbstractColumn<>(Model.of("Title"), "title") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel model + ) { + cellItem.add( + LinkWrapper.apply(componentId, linkId -> { + PageParameters pageParameters = new PageParameters(); + pageParameters.set(PageParameterKeys.MAP.get(Idea.class), model.getObject().getId()); + AbstractLink link = new BookmarkablePageLink<>( + linkId, + ProjectIdeaDetailsPage.class, + pageParameters + ); + link.setBody(LambdaModel.of(model, Idea::getTitle, Idea::setTitle)); + return link; + }) + ); } } - }); + ); - columns.add(new AbstractColumn<>(Model.of("First meeting")) { - @Override - public void populateItem(Item> item, String id, IModel model) { - item.add(new FirstMeetingColumnPanel(id, model) { - @Override - protected void onColumnClick(AjaxRequestTarget target, IModel model) { - openFirstMeetingDialog(target, model); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Authors")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>( + LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new StudentProfileProgramPanel(componentId, t, false); + } + } + ); + } } - }); + ); + columns.add( + new AbstractColumn<>(Model.of("Status"), "match.status") { + @Override + public void populateItem(Item> item, String id, IModel model) { + item.add( + new Label( + id, + model.map(idea -> + switch (idea.getMatchStatus()) { + case UNMATCHED -> "Submitted, waiting for matching by administrator"; + case MATCHED -> { + if ( + applicationPeriodService.courseStartHasPassed(idea.getApplicationPeriod()) + ) { + yield "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you."; + } else { + yield "Matched, awaiting course start date"; + } + } + case COMPLETED -> "Matched, project started"; + case INACTIVE -> "Inactive"; + } + ) + ) + ); + } + } + ); + + columns.add( + new AbstractColumn<>(Model.of("Course start date")) { + @Override + public void populateItem(Item> item, String id, IModel iModel) { + item.add( + new Label(id, iModel.map(Idea::getApplicationPeriod).map(ApplicationPeriod::getCourseStartDate)) + ); + } + } + ); + + columns.add( + new AbstractColumn<>(Model.of("Supervisor")) { + @Override + public void populateItem(Item> item, String id, IModel model) { + Idea idea = model.getObject(); + if ( + (idea.getType() == Type.SUPERVISOR || + applicationPeriodService.courseStartHasPassed(idea.getApplicationPeriod())) && + idea.getMatch().getSupervisor() != null + ) { + item.add(new Label(id, idea.getMatch().getSupervisor().getFullName())); + } else { + item.add(new Label(id, "Visible on course start date")); + } + } + } + ); + + columns.add( + new AbstractColumn<>(Model.of("First meeting")) { + @Override + public void populateItem(Item> item, String id, IModel model) { + item.add( + new FirstMeetingColumnPanel(id, model) { + @Override + protected void onColumnClick(AjaxRequestTarget target, IModel model) { + openFirstMeetingDialog(target, model); + } + } + ); + } + } + ); return columns; } - private void openFirstMeetingDialog(AjaxRequestTarget target, IModel model) { modalWindowPlus.setContent(new FirstMeetingPanel(modalWindowPlus.getContentId(), model)); modalWindowPlus.setTitle("Idea title: " + model.getObject().getTitle()); modalWindowPlus.show(target); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPage.java b/view/src/main/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPage.java index a08d766b65..71b4e674f3 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -12,10 +14,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - -@Authorization(authorizedRoles={Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) public class ProjectNewAllSupervisorIdeasPage extends AbstractIdeaProjectPage implements MenuHighlightProjectIdeas { @Inject @@ -31,26 +30,40 @@ public class ProjectNewAllSupervisorIdeasPage extends AbstractIdeaProjectPage im } catch (StringValueConversionException ignored) { throw new RestartResponseException(ProjectIdeaStartPage.class); } - final IModel applicationPeriod = new DetachableServiceModel<>(applicationPeriodService, applicationPeriodId); - final List availablePeriods = applicationPeriodService.getCurrentStudentPeriods(SciProSession.get().getUser()); - final boolean isPeriodAvailableForSelection = availablePeriods.stream() - .filter(StudentPeriod::allowedToSelectIdeas) - .map(StudentPeriod::getApplicationPeriod) - .anyMatch(applicationPeriod.getObject()::equals); + final IModel applicationPeriod = new DetachableServiceModel<>( + applicationPeriodService, + applicationPeriodId + ); + final List availablePeriods = applicationPeriodService.getCurrentStudentPeriods( + SciProSession.get().getUser() + ); + final boolean isPeriodAvailableForSelection = availablePeriods + .stream() + .filter(StudentPeriod::allowedToSelectIdeas) + .map(StudentPeriod::getApplicationPeriod) + .anyMatch(applicationPeriod.getObject()::equals); if (!isPeriodAvailableForSelection) { throw new RestartResponseException(ProjectIdeaStartPage.class); } - add(new ProjectAllSupervisorIdeasPanel("ideaPanel", applicationPeriod){ - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(applicationPeriodService.isOpen(getModelObject()) || applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption(getModelObject(), SciProSession.get().getUser())); + add( + new ProjectAllSupervisorIdeasPanel("ideaPanel", applicationPeriod) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + applicationPeriodService.isOpen(getModelObject()) || + applicationPeriodService.hasCurrentSelectSupervisorIdeaExemption( + getModelObject(), + SciProSession.get().getUser() + ) + ); + } } - }); - } - - private void addFeedback() { + ); + } + + private void addFeedback() { add(new FeedbackPanel("feedback").setOutputMarkupId(true)); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SelectResearchAreaPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SelectResearchAreaPanel.java index b76b1bd40c..9391a9317e 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SelectResearchAreaPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SelectResearchAreaPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import java.util.function.Predicate; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.GenericPanel; @@ -7,33 +8,35 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; -import java.util.function.Predicate; - public class SelectResearchAreaPanel extends GenericPanel { - public SelectResearchAreaPanel(String id, IModel supervisor) { super(id, supervisor); - - BookmarkablePageLink createIdea = new BookmarkablePageLink<>("create_idea", SupervisorIdeaSubmissionPage.class) { + BookmarkablePageLink createIdea = new BookmarkablePageLink<>( + "create_idea", + SupervisorIdeaSubmissionPage.class + ) { @Override protected void onConfigure() { super.onConfigure(); User currentUser = supervisor.getObject(); - boolean hasActiveResearchArea = currentUser.getResearchAreas() - .stream() - .anyMatch(Predicate.not(ResearchArea::isDeleted)); + boolean hasActiveResearchArea = currentUser + .getResearchAreas() + .stream() + .anyMatch(Predicate.not(ResearchArea::isDeleted)); setVisible(hasActiveResearchArea); } }; createIdea.setOutputMarkupPlaceholderTag(true); add(createIdea); - add(new UpdateResearchAreasPanel("update_research_areas", supervisor) { - @Override - protected void onResearchAreasUpdated(final AjaxRequestTarget target) { - target.add(createIdea); + add( + new UpdateResearchAreasPanel("update_research_areas", supervisor) { + @Override + protected void onResearchAreasUpdated(final AjaxRequestTarget target) { + target.add(createIdea); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanel.java index 481d21b47f..f4ebd4c4fd 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -13,12 +15,11 @@ import se.su.dsv.scipro.components.AutoHidingListView; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class StudentApplicationPeriodInfoPanel extends Panel { + @Inject private ApplicationPeriodService periodService; + @Inject private IdeaService ideaService; @@ -30,7 +31,6 @@ public class StudentApplicationPeriodInfoPanel extends Panel { public StudentApplicationPeriodInfoPanel(String id) { super(id); - IModel> currentPeriods = new LoadableDetachableModel<>() { @Override protected List load() { @@ -42,48 +42,65 @@ public class StudentApplicationPeriodInfoPanel extends Panel { } private void addListOfPeriods(final IModel> currentPeriods) { - add(new AutoHidingListView<>(PERIOD_LIST, currentPeriods) { + add( + new AutoHidingListView<>(PERIOD_LIST, currentPeriods) { + @Override + protected void populateItem(ListItem item) { + item.add( + new ApplicationPeriodInfoPanel("info", item.getModel().map(StudentPeriod::getApplicationPeriod)) + ); + addStudentStuff(item); + } - @Override - protected void populateItem(ListItem item) { - item.add(new ApplicationPeriodInfoPanel("info", item.getModel().map(StudentPeriod::getApplicationPeriod))); - addStudentStuff(item); + private void addStudentStuff(final ListItem item) { + PageParameters pp = new PageParameters(); + pp.add( + PageParameterKeys.MAP.get(ApplicationPeriod.class), + item.getModelObject().getApplicationPeriod().getId() + ); + WebMarkupContainer studentContainer = new WebMarkupContainer(STUDENT_CONTAINER) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + !ideaService.authorParticipatingOnActiveIdea( + SciProSession.get().getUser(), + item.getModelObject().getApplicationPeriod() + ) + ); + } + }; + item.add(studentContainer); + studentContainer.add( + new BookmarkablePageLink(SELECT_SUPERVISOR, ProjectNewAllSupervisorIdeasPage.class, pp) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(item.getModelObject().allowedToSelectIdeas()); + } + } + ); + studentContainer.add( + new BookmarkablePageLink(CREATE, ProjectIdeaSubmissionPage.class, pp) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(item.getModelObject().allowedToSubmitIdea()); + } + } + ); + } } + ); - private void addStudentStuff(final ListItem item) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), item.getModelObject().getApplicationPeriod().getId()); - WebMarkupContainer studentContainer = new WebMarkupContainer(STUDENT_CONTAINER) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!ideaService.authorParticipatingOnActiveIdea(SciProSession.get().getUser(), item.getModelObject().getApplicationPeriod())); - } - }; - item.add(studentContainer); - studentContainer.add(new BookmarkablePageLink(SELECT_SUPERVISOR, ProjectNewAllSupervisorIdeasPage.class, pp) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(item.getModelObject().allowedToSelectIdeas()); - } - }); - studentContainer.add(new BookmarkablePageLink(CREATE, ProjectIdeaSubmissionPage.class, pp) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(item.getModelObject().allowedToSubmitIdea()); - } - }); + add( + new Label(EMPTY, "No application period open") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(currentPeriods.getObject().isEmpty()); + } } - }); - - add(new Label(EMPTY, "No application period open") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(currentPeriods.getObject().isEmpty()); - } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanel.java b/view/src/main/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanel.java index e079121202..18183717ef 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanel.java @@ -1,47 +1,53 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.match.Idea.Status; -import jakarta.inject.Inject; - /** - * + * * Panel to display in Student datatables where the status of a submitted idea is needed. * */ public class StudentIdeaStatusColumnPanel extends Panel { public static final String LABEL = "label"; - @Inject - private ApplicationPeriodService periodService; - public StudentIdeaStatusColumnPanel(String id, IModel ideaModel) { - super(id, ideaModel); - Idea idea = ideaModel.getObject(); - Status currentStatus = idea.getMatchStatus(); - switch (currentStatus) { - case UNMATCHED: - add(new Label(LABEL, "Unmatched, waiting for supervisor")); - break; - case COMPLETED: - add(new Label(LABEL, "Matched, project started")); - break; + @Inject + private ApplicationPeriodService periodService; + + public StudentIdeaStatusColumnPanel(String id, IModel ideaModel) { + super(id, ideaModel); + Idea idea = ideaModel.getObject(); + Status currentStatus = idea.getMatchStatus(); + switch (currentStatus) { + case UNMATCHED: + add(new Label(LABEL, "Unmatched, waiting for supervisor")); + break; + case COMPLETED: + add(new Label(LABEL, "Matched, project started")); + break; case INACTIVE: add(new Label(LABEL, "Inactive")); break; - case MATCHED: - if(periodService.courseStartHasPassed(idea.getApplicationPeriod())){ - add(new Label(LABEL, "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you.")); - } else { - add(new Label(LABEL, "Matched, course starting " + idea.getApplicationPeriod().getCourseStartDate())); - } - break; + case MATCHED: + if (periodService.courseStartHasPassed(idea.getApplicationPeriod())) { + add( + new Label( + LABEL, + "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you." + ) + ); + } else { + add( + new Label(LABEL, "Matched, course starting " + idea.getApplicationPeriod().getCourseStartDate()) + ); + } + break; default: throw new IllegalStateException("Incorrect status"); - } - } - + } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAcceptIdeaDialogPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAcceptIdeaDialogPanel.java index ad4a5f09b6..69821fa3bb 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAcceptIdeaDialogPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAcceptIdeaDialogPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -10,8 +11,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; - public class SupervisorAcceptIdeaDialogPanel extends Panel { @Inject @@ -27,10 +26,8 @@ public class SupervisorAcceptIdeaDialogPanel extends Panel { add(new AcceptIdeaForm("form", model)); } - private class AcceptIdeaForm extends Form { - public AcceptIdeaForm(String id, final IModel model) { super(id, model); add(new IdeaAuthorInfoPanel("authors", model)); @@ -40,12 +37,17 @@ public class SupervisorAcceptIdeaDialogPanel extends Panel { } private void addAcceptButton(final IModel model) { - AjaxConfirmationLink accept = new AjaxConfirmationLink<>("accept", "Are you sure you want to accept to supervise this idea?") { - + AjaxConfirmationLink accept = new AjaxConfirmationLink<>( + "accept", + "Are you sure you want to accept to supervise this idea?" + ) { @Override public void onClick(AjaxRequestTarget target) { User supervisor = SciProSession.get().getUser(); - Either acceptance = ideaService.supervisorAcceptIdea(model.getObject(), supervisor); + Either acceptance = ideaService.supervisorAcceptIdea( + model.getObject(), + supervisor + ); if (acceptance.isRight()) { getSession().info("You are now supervising idea: " + acceptance.right().getTitle()); setResponsePage(SupervisorIdeaStartPage.class); @@ -58,7 +60,10 @@ public class SupervisorAcceptIdeaDialogPanel extends Panel { getSession().error("Application period is not open"); break; case TARGET_NUMBER_REACHED: - getSession().error("You have reached your current target numbers, you may not accept another idea"); + getSession() + .error( + "You have reached your current target numbers, you may not accept another idea" + ); break; } target.add(feedback); diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSelectableStudentIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSelectableStudentIdeasPanel.java index 6d772ad2f1..af74c2a00c 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSelectableStudentIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSelectableStudentIdeasPanel.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.match; -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.system.ProjectType; - import jakarta.inject.Inject; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.ProjectType; public class SupervisorAllSelectableStudentIdeasPanel extends SupervisorAllStudentIdeasPanel { @@ -26,6 +25,8 @@ public class SupervisorAllSelectableStudentIdeasPanel extends SupervisorAllStude @Override protected List getChoices() { - return new ArrayList<>(targetService.projectTypesWithTargetsLeft(getModelObject(), SciProSession.get().getUser())); + return new ArrayList<>( + targetService.projectTypesWithTargetsLeft(getModelObject(), SciProSession.get().getUser()) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPage.java index 6226e13614..ca706ab34a 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; @@ -7,23 +9,23 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorProjectIdea; import se.su.dsv.scipro.data.DetachableServiceModel; -import jakarta.inject.Inject; -import java.util.List; - -public class SupervisorAllStudentIdeasPage extends AbstractSupervisorProjectIdeaPage implements MenuHighlightSupervisorProjectIdea { +public class SupervisorAllStudentIdeasPage + extends AbstractSupervisorProjectIdeaPage + implements MenuHighlightSupervisorProjectIdea { @Inject private ApplicationPeriodService applicationPeriodService; public SupervisorAllStudentIdeasPage(PageParameters pp) { super(pp); - List currentPeriods = applicationPeriodService.getCurrentSupervisorPeriods(loggedInUser()); if (currentPeriods.isEmpty()) { add(new Label("ideas", new ResourceModel("no.current.period"))); - } - else { - IModel applicationPeriod = new DetachableServiceModel<>(applicationPeriodService, currentPeriods.get(0)); + } else { + IModel applicationPeriod = new DetachableServiceModel<>( + applicationPeriodService, + currentPeriods.get(0) + ); add(new SupervisorAllStudentIdeasPanel("ideas", applicationPeriod)); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanel.java index bac156a2d1..6a3f3f11b8 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -27,17 +29,17 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.util.*; - public class SupervisorAllStudentIdeasPanel extends GenericPanel { @Inject private IdeaService ideaService; + @Inject private KeywordService keywordService; + @Inject private ResearchAreaService researchAreaService; + @Inject private ApplicationPeriodService applicationPeriodService; @@ -74,7 +76,9 @@ public class SupervisorAllStudentIdeasPanel extends GenericPanel(Model.of("Created"), Idea::getDateCreated, "dateCreated")); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Languages")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getLanguages, Idea::setLanguages))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new EnumLabel<>(componentId, t); - } - }); - } - }); - - columns.add(new AbstractColumn<>(Model.of("Title"), "title") { - @Override - public void populateItem(Item> components, String s, final IModel model) { - components.add(new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - modalWindowPlus.setContent(new SupervisorAcceptIdeaDialogPanel(modalWindowPlus.getContentId(), model)); - modalWindowPlus.setTitle(model.getObject().getTitle()); - modalWindowPlus.show(target); - } - }); - } - }); - - columns.add(new AbstractColumn<>(Model.of("Authors")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new StudentProfileProgramPanel(componentId, t, false); - } - }); - } - }); - columns.add(new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null)); - columns.add(new KeywordsColumn<>(Model.of("Keywords"))); - columns.add(new AbstractColumn<>(Model.of("Supervisor"), "match.supervisor") { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - Idea idea = rowModel.getObject(); - if (idea.hasSupervisor()) { - cellItem.add(new UserLinkPanel(componentId, rowModel.map(Idea::getMatch).map(Match::getSupervisor))); - } else { - cellItem.add(new AjaxConfirmingLinkPanel<>(componentId, rowModel, Model.of("Select")) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - User supervisor = getCurrentSupervisor(); - Either acceptance = ideaService.supervisorAcceptIdea(model.getObject(), supervisor); - if (acceptance.isRight()) { - SupervisorAllStudentIdeasPanel.this.success("You are now supervising idea: " + acceptance.right().getTitle()); - setResponsePage(SupervisorIdeaStartPage.class); - } else { - switch (acceptance.left()) { - case ALREADY_MATCHED: - SupervisorAllStudentIdeasPanel.this.error("Idea has already been matched"); - break; - case APPLICATION_PERIOD_NOT_OPEN: - SupervisorAllStudentIdeasPanel.this.error("Application period is not open"); - break; - case TARGET_NUMBER_REACHED: - SupervisorAllStudentIdeasPanel.this.error("You have reached your current target numbers, you may not accept another idea"); - break; - } + columns.add( + new AbstractColumn<>(Model.of("Languages")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getLanguages, Idea::setLanguages)) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new EnumLabel<>(componentId, t); } - target.add(feedback); - target.add(dataTable); } - - private User getCurrentSupervisor() { - return SciProSession.get().getUser(); - } - }); + ); } } - }); + ); + + columns.add( + new AbstractColumn<>(Model.of("Title"), "title") { + @Override + public void populateItem(Item> components, String s, final IModel model) { + components.add( + new AjaxLinkPanel<>(s, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + modalWindowPlus.setContent( + new SupervisorAcceptIdeaDialogPanel(modalWindowPlus.getContentId(), model) + ); + modalWindowPlus.setTitle(model.getObject().getTitle()); + modalWindowPlus.show(target); + } + } + ); + } + } + ); + + columns.add( + new AbstractColumn<>(Model.of("Authors")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>( + LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new StudentProfileProgramPanel(componentId, t, false); + } + } + ); + } + } + ); + columns.add( + new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> + idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null + ) + ); + columns.add(new KeywordsColumn<>(Model.of("Keywords"))); + columns.add( + new AbstractColumn<>(Model.of("Supervisor"), "match.supervisor") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + Idea idea = rowModel.getObject(); + if (idea.hasSupervisor()) { + cellItem.add( + new UserLinkPanel(componentId, rowModel.map(Idea::getMatch).map(Match::getSupervisor)) + ); + } else { + cellItem.add( + new AjaxConfirmingLinkPanel<>(componentId, rowModel, Model.of("Select")) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + User supervisor = getCurrentSupervisor(); + Either acceptance = ideaService.supervisorAcceptIdea( + model.getObject(), + supervisor + ); + if (acceptance.isRight()) { + SupervisorAllStudentIdeasPanel.this.success( + "You are now supervising idea: " + acceptance.right().getTitle() + ); + setResponsePage(SupervisorIdeaStartPage.class); + } else { + switch (acceptance.left()) { + case ALREADY_MATCHED: + SupervisorAllStudentIdeasPanel.this.error( + "Idea has already been matched" + ); + break; + case APPLICATION_PERIOD_NOT_OPEN: + SupervisorAllStudentIdeasPanel.this.error( + "Application period is not open" + ); + break; + case TARGET_NUMBER_REACHED: + SupervisorAllStudentIdeasPanel.this.error( + "You have reached your current target numbers, you may not accept another idea" + ); + break; + } + } + target.add(feedback); + target.add(dataTable); + } + + private User getCurrentSupervisor() { + return SciProSession.get().getUser(); + } + } + ); + } + } + } + ); return columns; } private void addFiltering() { - - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - getProjectTypeModel(), getChoices(), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + getProjectTypeModel(), + getChoices(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { target.add(dataTable); @@ -201,17 +263,24 @@ public class SupervisorAllStudentIdeasPanel extends GenericPanel("areaFilter", new Model<>(), + add( + new AjaxDropDownChoice<>( + "areaFilter", + new Model<>(), new ListModel<>(researchAreaService.findNotDeleted()), - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { - filter.setResearchArea(getModelObject()); - target.add(dataTable); - keywordFilter.setVisible(getModelObject() != null && !keywordService.findByResearchArea(getModelObject()).isEmpty()); - target.add(keywordFilter); + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { + filter.setResearchArea(getModelObject()); + target.add(dataTable); + keywordFilter.setVisible( + getModelObject() != null && !keywordService.findByResearchArea(getModelObject()).isEmpty() + ); + target.add(keywordFilter); + } } - }); + ); } private IModel> getProjectTypeModel() { diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSupervisorIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSupervisorIdeasPanel.java index ab0c7b130b..16ad283a3b 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSupervisorIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorAllSupervisorIdeasPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -21,17 +23,17 @@ import se.su.dsv.scipro.dataproviders.FilteredDataProvider; import se.su.dsv.scipro.match.Idea.Type; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.*; - public class SupervisorAllSupervisorIdeasPanel extends Panel { @Inject private IdeaService ideaService; + @Inject private ProjectTypeService projectTypeService; + @Inject private KeywordService keywordService; + @Inject private ResearchAreaService researchAreaService; @@ -52,7 +54,10 @@ public class SupervisorAllSupervisorIdeasPanel extends Panel { } private void addDataTable() { - FilteredDataProvider provider = new FilteredDataProvider<>(ideaService, Model.of(params)); + FilteredDataProvider provider = new FilteredDataProvider<>( + ideaService, + Model.of(params) + ); provider.setSort("dateCreated", SortOrder.DESCENDING); dataTable = new ExportableDataPanel<>("dataTable", columns(), provider); add(dataTable); @@ -63,29 +68,39 @@ public class SupervisorAllSupervisorIdeasPanel extends Panel { columns.add(new DateColumn<>(Model.of("Created"), Idea::getDateCreated, "dateCreated")); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName())); - columns.add(new AbstractColumn<>(Model.of("Title")) { - @Override - public void populateItem(Item> item, String id, final IModel model) { - item.add(new AjaxLinkPanel<>(id, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - openDialog(model, target); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Title")) { + @Override + public void populateItem(Item> item, String id, final IModel model) { + item.add( + new AjaxLinkPanel<>(id, model, LambdaModel.of(model, Idea::getTitle, Idea::setTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + openDialog(model, target); + } + } + ); + } } - }); + ); - columns.add(new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null)); + columns.add( + new LambdaColumn<>(Model.of("Research Area"), "researchArea.title", idea -> + idea.getResearchArea() != null ? idea.getResearchArea().getTitle() : null + ) + ); columns.add(new KeywordsColumn<>(Model.of("Keywords"))); columns.add(new UserColumn<>(Model.of("Supervisor"), "creator.fullName", Idea::getCreator)); - columns.add(new AbstractColumn<>(Model.of("Status"), "match.status") { - @Override - public void populateItem(Item> item, String id, IModel model) { - item.add(new Label(id, ideaService.getStatusString(model.getObject()))); + columns.add( + new AbstractColumn<>(Model.of("Status"), "match.status") { + @Override + public void populateItem(Item> item, String id, IModel model) { + item.add(new Label(id, ideaService.getStatusString(model.getObject()))); + } } - }); + ); return columns; } @@ -95,13 +110,16 @@ public class SupervisorAllSupervisorIdeasPanel extends Panel { modalWindowPlus.show(target); } - private void addFiltering() { params.setStatuses(Arrays.asList(Idea.Status.COMPLETED, Idea.Status.MATCHED, Idea.Status.UNMATCHED)); params.setTypes(Collections.singletonList(Type.SUPERVISOR)); - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - getProjectTypes(), getProjectTypes(), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + getProjectTypes(), + getProjectTypes(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -132,17 +150,24 @@ public class SupervisorAllSupervisorIdeasPanel extends Panel { } private void researchAreaFilter(final KeywordFilterPanel keywordFilter) { - add(new AjaxDropDownChoice<>("areaFilter", new Model<>(), + add( + new AjaxDropDownChoice<>( + "areaFilter", + new Model<>(), new ListModel<>(researchAreaService.findNotDeleted()), - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { - params.setResearchArea(getModelObject()); - target.add(dataTable); - keywordFilter.setVisible(getModelObject() != null && !keywordService.findByResearchArea(getModelObject()).isEmpty()); - target.add(keywordFilter); + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ResearchArea objectSelected) { + params.setResearchArea(getModelObject()); + target.add(dataTable); + keywordFilter.setVisible( + getModelObject() != null && !keywordService.findByResearchArea(getModelObject()).isEmpty() + ); + target.add(keywordFilter); + } } - }); + ); } private IModel> getKeywords() { diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanel.java index 906f00321f..94bc844edc 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -13,12 +15,11 @@ import se.su.dsv.scipro.components.AutoHidingListView; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class SupervisorApplicationPeriodInfoPanel extends Panel { + @Inject private ApplicationPeriodService periodService; + @Inject private TargetService targetService; @@ -28,7 +29,6 @@ public class SupervisorApplicationPeriodInfoPanel extends Panel { public SupervisorApplicationPeriodInfoPanel(String id) { super(id); - final IModel> currentPeriods = new LoadableDetachableModel<>() { @Override protected List load() { @@ -36,32 +36,40 @@ public class SupervisorApplicationPeriodInfoPanel extends Panel { } }; - add(new AutoHidingListView<>(PERIOD_LIST, currentPeriods) { - @Override - protected void populateItem(final ListItem item) { - item.add(new ApplicationPeriodInfoPanel("info", item.getModel())); + add( + new AutoHidingListView<>(PERIOD_LIST, currentPeriods) { + @Override + protected void populateItem(final ListItem item) { + item.add(new ApplicationPeriodInfoPanel("info", item.getModel())); - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), item.getModelObject().getId()); + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(ApplicationPeriod.class), item.getModelObject().getId()); - item.add(new BookmarkablePageLink(SELECT_STUDENT, SupervisorSelectableStudentIdeasPage.class, pp) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(targetService.hasTargetsLeft(item.getModelObject(), SciProSession.get().getUser())); - } - }); + item.add( + new BookmarkablePageLink(SELECT_STUDENT, SupervisorSelectableStudentIdeasPage.class, pp) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + targetService.hasTargetsLeft(item.getModelObject(), SciProSession.get().getUser()) + ); + } + } + ); - item.add(new ApplicationPeriodSupervisorPanel("sup", item.getModel())); + item.add(new ApplicationPeriodSupervisorPanel("sup", item.getModel())); + } } - }); + ); - add(new Label(EMPTY, "No application period open") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(currentPeriods.getObject().isEmpty()); + add( + new Label(EMPTY, "No application period open") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(currentPeriods.getObject().isEmpty()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanel.java index 52ec0779c1..8c8b293540 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -19,11 +23,6 @@ import se.su.dsv.scipro.components.*; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.*; - -import static java.util.Arrays.asList; - public class SupervisorEditIdeaPanel extends Panel { public static final String PROJECT_TYPE = "projectType"; @@ -31,10 +30,13 @@ public class SupervisorEditIdeaPanel extends Panel { @Inject private ProjectTypeService projectTypeService; + @Inject private IdeaService ideaService; + @Inject private KeywordService keywordService; + @Inject private UserService userService; @@ -43,7 +45,6 @@ public class SupervisorEditIdeaPanel extends Panel { public SupervisorEditIdeaPanel(String id, IModel model, boolean isNewIdea) { super(id, model); - if (model.getObject().getKeywords() != null) { selectedKeywords = new HashSet<>(model.getObject().getKeywords()); } else { @@ -93,41 +94,64 @@ public class SupervisorEditIdeaPanel extends Panel { } private void addProjectTypeSelection() { - RadioChoice projectType = new BootstrapRadioChoice<>(PROJECT_TYPE, LambdaModel.of(getModel(), Idea::getProjectType, Idea::setProjectType), - projectTypeService.findWithModule(ProjectModule.MATCH), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); + RadioChoice projectType = new BootstrapRadioChoice<>( + PROJECT_TYPE, + LambdaModel.of(getModel(), Idea::getProjectType, Idea::setProjectType), + projectTypeService.findWithModule(ProjectModule.MATCH), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); projectType.setRequired(true); add(projectType); addComponentFeedback(this, "projectTypeFeedback", projectType); } private void addLanguageSelection() { - CheckBoxMultipleChoice language = new BootstrapCheckBoxMultipleChoice<>("language", LambdaModel.of(getModel(), Idea::getLanguages, Idea::setLanguages), - Arrays.asList(Language.values()), new EnumChoiceRenderer<>(this)); + CheckBoxMultipleChoice language = new BootstrapCheckBoxMultipleChoice<>( + "language", + LambdaModel.of(getModel(), Idea::getLanguages, Idea::setLanguages), + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ); language.setRequired(true); addComponentFeedback(this, "languageFeedback", language); add(language); } private void addTitleField() { - TextField title = new TextField<>("title", LambdaModel.of(getModel(), Idea::getTitle, Idea::setTitle)); + TextField title = new TextField<>( + "title", + LambdaModel.of(getModel(), Idea::getTitle, Idea::setTitle) + ); title.setRequired(true); title.add(StringValidator.lengthBetween(MIN_TITLE_LENGTH, MAX_TITLE_LENGTH)); addComponentFeedback(this, "titleFeedback", title); add(title); - add(new Label("titleSmallText", new StringResourceModel("titleDesc").setParameters(MIN_TITLE_LENGTH, MAX_TITLE_LENGTH))); + add( + new Label( + "titleSmallText", + new StringResourceModel("titleDesc").setParameters(MIN_TITLE_LENGTH, MAX_TITLE_LENGTH) + ) + ); add(new InfoPanel("titleInfo", new ResourceModel("titleInfo"))); } private void addDescriptionField() { - CounterTextArea description = new CounterTextArea("description", LambdaModel.of(getModel(), Idea::getDescription, Idea::setDescription), DESCRIPTION_MAX_CHARS); + CounterTextArea description = new CounterTextArea( + "description", + LambdaModel.of(getModel(), Idea::getDescription, Idea::setDescription), + DESCRIPTION_MAX_CHARS + ); description.setRequired(true); add(description); add(new InfoPanel("descriptionInfo", new ResourceModel("descriptionInfo"))); } private void addPrerequisitesField() { - CounterTextArea prerequisites = new CounterTextArea("prerequisites", LambdaModel.of(getModel(), Idea::getPrerequisites, Idea::setPrerequisites), PREREQS_MAX_CHARS); + CounterTextArea prerequisites = new CounterTextArea( + "prerequisites", + LambdaModel.of(getModel(), Idea::getPrerequisites, Idea::setPrerequisites), + PREREQS_MAX_CHARS + ); prerequisites.setRequired(true); add(prerequisites); add(new InfoPanel("prereqsInfo", new ResourceModel("prereqsInfo"))); @@ -141,21 +165,25 @@ public class SupervisorEditIdeaPanel extends Panel { areaContainer.add(areaDropDown); addComponentFeedback(areaContainer, "researchAreaFeedback", areaDropDown); - areaContainer.add(new AjaxLink<>("updateResearchAreas") { - @Override - public void onClick(final AjaxRequestTarget target) { - modalWindow.setTitle(getString("update_research_areas_title")); - modalWindow.setContent(id -> new UpdateResearchAreasPanel(id, getUser()) { - @Override - protected void onResearchAreasUpdated(final AjaxRequestTarget target) { - target.add(areaContainer); - modalWindow.refresh(target); - } - }); - modalWindow.setFooter(CloseFragment::new); - modalWindow.show(target); + areaContainer.add( + new AjaxLink<>("updateResearchAreas") { + @Override + public void onClick(final AjaxRequestTarget target) { + modalWindow.setTitle(getString("update_research_areas_title")); + modalWindow.setContent(id -> + new UpdateResearchAreasPanel(id, getUser()) { + @Override + protected void onResearchAreasUpdated(final AjaxRequestTarget target) { + target.add(areaContainer); + modalWindow.refresh(target); + } + } + ); + modalWindow.setFooter(CloseFragment::new); + modalWindow.show(target); + } } - }); + ); keywordsPanel = getKeywordsPanel(); areaContainer.add(getKeywordsPanel()); @@ -167,10 +195,12 @@ public class SupervisorEditIdeaPanel extends Panel { } private AjaxDropDownChoice getResearchAreaDropDown() { - AjaxDropDownChoice areaDropDown = new AjaxDropDownChoice<>("area", - LambdaModel.of(getModel(), Idea::getResearchArea, Idea::setResearchArea), - getSelectableResearchAreas(getModel()), - new ResearchAreaChoiceRenderer(this)) { + AjaxDropDownChoice areaDropDown = new AjaxDropDownChoice<>( + "area", + LambdaModel.of(getModel(), Idea::getResearchArea, Idea::setResearchArea), + getSelectableResearchAreas(getModel()), + new ResearchAreaChoiceRenderer(this) + ) { @Override public void onNewSelection(AjaxRequestTarget target, ResearchArea selected) { Set keywordsModelObject = new HashSet<>(keywordService.findByResearchArea(selected)); @@ -198,6 +228,7 @@ public class SupervisorEditIdeaPanel extends Panel { } private class CloseFragment extends Fragment { + public CloseFragment(final String id) { super(id, "close_fragment", SupervisorEditIdeaPanel.IdeaForm.this); } @@ -211,7 +242,11 @@ public class SupervisorEditIdeaPanel extends Panel { } private KeywordFilterPanel getKeywordsPanel() { - keywordsPanel = new KeywordFilterPanel("keywords", new SetModel<>(selectableKeywords), new ListModel<>(new ArrayList<>(selectedKeywords))) { + keywordsPanel = new KeywordFilterPanel( + "keywords", + new SetModel<>(selectableKeywords), + new ListModel<>(new ArrayList<>(selectedKeywords)) + ) { @Override public void onKeywordsSelected(AjaxRequestTarget target, Set selected) { selectedKeywords = selected; @@ -223,27 +258,38 @@ public class SupervisorEditIdeaPanel extends Panel { } private void addPublishedSelection() { - RadioChoice published = new BootstrapRadioChoice<>("published", LambdaModel.of(getModel(), Idea::isPublished, Idea::setPublished), - asList(Boolean.TRUE, Boolean.FALSE), getPublishedChoiceRenderer()); + RadioChoice published = new BootstrapRadioChoice<>( + "published", + LambdaModel.of(getModel(), Idea::isPublished, Idea::setPublished), + asList(Boolean.TRUE, Boolean.FALSE), + getPublishedChoiceRenderer() + ); add(published); add(new InfoPanel("publishInfo", new ResourceModel("publishInfo"))); } private void addSaveButton(final IModel model, final boolean isNewIdea) { - add(new AjaxButton("save") { - @Override - protected void onSubmit(AjaxRequestTarget target) { - ideaService.saveSupervisorIdea(model.getObject(), SciProSession.get().getUser(), new ArrayList<>(selectedKeywords), isNewIdea); - setResponsePage(SupervisorIdeaStartPage.class); - } + add( + new AjaxButton("save") { + @Override + protected void onSubmit(AjaxRequestTarget target) { + ideaService.saveSupervisorIdea( + model.getObject(), + SciProSession.get().getUser(), + new ArrayList<>(selectedKeywords), + isNewIdea + ); + setResponsePage(SupervisorIdeaStartPage.class); + } - @Override - protected void onError(AjaxRequestTarget target) { - getForm().error(getString("defaultError")); - updateFeedbackPanels(target); - target.appendJavaScript("window.scrollTo(0,0);"); + @Override + protected void onError(AjaxRequestTarget target) { + getForm().error(getString("defaultError")); + updateFeedbackPanels(target); + target.appendJavaScript("window.scrollTo(0,0);"); + } } - }); + ); } private void addComponentFeedback(WebMarkupContainer container, String id, Component component) { @@ -261,7 +307,9 @@ public class SupervisorEditIdeaPanel extends Panel { } private boolean keywordsNotWithinLimits() { - return selectedKeywords == null || selectedKeywords.isEmpty() || selectedKeywords.size() > MAX_KEYWORDS_SIZE; + return ( + selectedKeywords == null || selectedKeywords.isEmpty() || selectedKeywords.size() > MAX_KEYWORDS_SIZE + ); } private IChoiceRenderer getPublishedChoiceRenderer() { @@ -300,5 +348,4 @@ public class SupervisorEditIdeaPanel extends Panel { private void updateFeedbackPanels(final AjaxRequestTarget target) { target.getPage().visitChildren(FeedbackPanel.class, (feedback, visit) -> target.add(feedback)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPage.java index 51f921ae60..704cdb2689 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPage.java @@ -7,14 +7,15 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyIde import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.util.PageParameterKeys; -public class SupervisorIdeaDetailsPage extends AbstractSupervisorProjectIdeaPage implements MenuHighlightSupervisorMyIdeas { +public class SupervisorIdeaDetailsPage + extends AbstractSupervisorProjectIdeaPage + implements MenuHighlightSupervisorMyIdeas { @Inject private IdeaService ideaService; public SupervisorIdeaDetailsPage(PageParameters pp) { super(pp); - StringValue ideaId = pp.get(PageParameterKeys.MAP.get(Idea.class)); DetachableServiceModel ideaModel = new DetachableServiceModel<>(ideaService, ideaId.toLongObject()); diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanel.java index 06c3177fea..184e13dea5 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanel.java @@ -8,14 +8,13 @@ import se.su.dsv.scipro.match.Idea.Type; public class SupervisorIdeaDetailsPanel extends GenericPanel { - public SupervisorIdeaDetailsPanel(String id, IModel model) { - super(id, model); + public SupervisorIdeaDetailsPanel(String id, IModel model) { + super(id, model); add(new Label("title", LambdaModel.of(model, Idea::getTitle, Idea::setTitle))); add(new IdeaExportPanel("exportStatus", model)); - add(new IdeaDetailsPanel("ideaDetails", model, model.getObject().getType() == Type.SUPERVISOR)); - add(new IdeaAuthorInfoPanel("authors", model)); - add(new IdeaTholanderInfoPanel("tholander", model)); - add(new IdeaDownloadPanel("download", model)); - } - + add(new IdeaDetailsPanel("ideaDetails", model, model.getObject().getType() == Type.SUPERVISOR)); + add(new IdeaAuthorInfoPanel("authors", model)); + add(new IdeaTholanderInfoPanel("tholander", model)); + add(new IdeaDownloadPanel("download", model)); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaStartPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaStartPage.java index b90d6eeb3f..cd95c2ceb2 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaStartPage.java @@ -13,7 +13,7 @@ public class SupervisorIdeaStartPage extends AbstractSupervisorProjectIdeaPage { add(feedbackPanel); feedbackPanel.setOutputMarkupId(true); - if(loggedInUser().hasRole(Roles.SUPERVISOR)) { + if (loggedInUser().hasRole(Roles.SUPERVISOR)) { add(new SupervisorMyIdeasPanel("myIdeasPanel", this::loggedInUser)); } else { add(new EmptyPanel("myIdeasPanel")); diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPage.java index ff64fc4edb..cd8642c1fc 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -10,53 +11,54 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; +public class SupervisorIdeaSubmissionPage + extends AbstractSupervisorProjectIdeaPage + implements MenuHighlightSupervisorMyIdeas { -public class SupervisorIdeaSubmissionPage extends AbstractSupervisorProjectIdeaPage implements MenuHighlightSupervisorMyIdeas { - - @Inject - private IdeaService ideaService; - - public SupervisorIdeaSubmissionPage(PageParameters pp) { - super(pp); + @Inject + private IdeaService ideaService; + public SupervisorIdeaSubmissionPage(PageParameters pp) { + super(pp); Long ideaId = null; StringValue value = pp.get(PageParameterKeys.MAP.get(Idea.class)); - if(!value.isNull()) { + if (!value.isNull()) { ideaId = value.toLongObject(); } - Idea idea; - boolean isNewIdea; - - if(ideaId!=null) { - idea = ideaService.findOne(ideaId); - isNewIdea = false; - } - else { - idea = new Idea(); - isNewIdea = true; - } + Idea idea; + boolean isNewIdea; - if (SciProSession.get().hasActualRole(Roles.SUPERVISOR)){ - add(new SupervisorEditIdeaPanel("ideaPanel", new DetachableServiceModel<>(ideaService, idea), isNewIdea){ - @Override - protected void onConfigure(){ - super.onConfigure(); - setVisibilityAllowed(SciProSession.get().hasActualRole(Roles.SUPERVISOR)); + if (ideaId != null) { + idea = ideaService.findOne(ideaId); + isNewIdea = false; + } else { + idea = new Idea(); + isNewIdea = true; + } + + if (SciProSession.get().hasActualRole(Roles.SUPERVISOR)) { + add( + new SupervisorEditIdeaPanel("ideaPanel", new DetachableServiceModel<>(ideaService, idea), isNewIdea) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(SciProSession.get().hasActualRole(Roles.SUPERVISOR)); + } } - }); + ); } else { add(new EmptyPanel("ideaPanel")); } - add(new Label("noLabel", "You don't have the Employee role, so you cant create ideas here."){ - @Override - protected void onConfigure(){ - super.onConfigure(); - setVisibilityAllowed(!SciProSession.get().hasActualRole(Roles.SUPERVISOR)); + add( + new Label("noLabel", "You don't have the Employee role, so you cant create ideas here.") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!SciProSession.get().hasActualRole(Roles.SUPERVISOR)); + } } - }); - } - + ); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanel.java index 1382aa2a3c..cd59b023bf 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -31,17 +37,11 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static java.util.Arrays.asList; - public class SupervisorMyIdeasPanel extends Panel { @Inject private IdeaService ideaService; + @Inject ApplicationPeriodService applicationPeriodService; @@ -57,20 +57,21 @@ public class SupervisorMyIdeasPanel extends Panel { } private void setup() { - add(new AjaxLink("create") { - @Override - public void onClick(AjaxRequestTarget target) { - if (supervisor.getObject().getResearchAreas().stream().allMatch(ResearchArea::isDeleted)) { - modalWindowPlus.setTitle(new ResourceModel("select.research.area")); - modalWindowPlus.setContent(SelectResearchAreaFragment::new); - modalWindowPlus.setFooter(SelectResearchAreaFooterFragment::new); - modalWindowPlus.show(target); - } - else { - setResponsePage(SupervisorIdeaSubmissionPage.class); + add( + new AjaxLink("create") { + @Override + public void onClick(AjaxRequestTarget target) { + if (supervisor.getObject().getResearchAreas().stream().allMatch(ResearchArea::isDeleted)) { + modalWindowPlus.setTitle(new ResourceModel("select.research.area")); + modalWindowPlus.setContent(SelectResearchAreaFragment::new); + modalWindowPlus.setFooter(SelectResearchAreaFooterFragment::new); + modalWindowPlus.show(target); + } else { + setResponsePage(SupervisorIdeaSubmissionPage.class); + } } } - }); + ); addDialog(); addFiltering(); addInfoPanel(); @@ -78,18 +79,22 @@ public class SupervisorMyIdeasPanel extends Panel { } private class SelectResearchAreaFragment extends Fragment { + public SelectResearchAreaFragment(final String id) { super(id, "select_research_area_fragment", SupervisorMyIdeasPanel.this); - add(new UpdateResearchAreasPanel("update_research_areas", supervisor) { - @Override - protected void onResearchAreasUpdated(final AjaxRequestTarget target) { - modalWindowPlus.refresh(target); + add( + new UpdateResearchAreasPanel("update_research_areas", supervisor) { + @Override + protected void onResearchAreasUpdated(final AjaxRequestTarget target) { + modalWindowPlus.refresh(target); + } } - }); + ); } } private class SelectResearchAreaFooterFragment extends Fragment { + public SelectResearchAreaFooterFragment(final String id) { super(id, "select_research_area_footer_fragment", SupervisorMyIdeasPanel.this); } @@ -114,34 +119,50 @@ public class SupervisorMyIdeasPanel extends Panel { } private void dateFilter() { - add(new DeactivatableDatePickerPanel("createdBetween", + add( + new DeactivatableDatePickerPanel( + "createdBetween", LambdaModel.of(params::getCreatedAfter, params::setCreatedAfter), - LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(dataTable); + LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); } private void ideaStatusFilter() { - add(new AjaxCheckBoxMultipleChoice<>("statusFilter", getStatusModel(), - getStatuses(), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataTable); + add( + new AjaxCheckBoxMultipleChoice<>( + "statusFilter", + getStatusModel(), + getStatuses(), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); } private void ideaTypeFilter() { - add(new AjaxCheckBoxMultipleChoice<>("typeFilter", getIdeaTypeModel(), - getIdeaTypes(), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataTable); + add( + new AjaxCheckBoxMultipleChoice<>( + "typeFilter", + getIdeaTypeModel(), + getIdeaTypes(), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); } private void addInfoPanel() { @@ -154,40 +175,56 @@ public class SupervisorMyIdeasPanel extends Panel { columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName())); columns.add(newTitleColumn()); columns.add(newAuthorsColumn()); - columns.add(new AbstractExportableColumn<>(Model.of("Student selection")) { - @Override - public IModel getDataModel(final IModel rowModel) { - return new EnumModel<>(SupervisorMyIdeasPanel.this, new LoadableDetachableModel() { - @Override - protected SelectionState load() { - return ideaService.getSelectionState(rowModel.getObject()); - } - }); + columns.add( + new AbstractExportableColumn<>(Model.of("Student selection")) { + @Override + public IModel getDataModel(final IModel rowModel) { + return new EnumModel<>( + SupervisorMyIdeasPanel.this, + new LoadableDetachableModel() { + @Override + protected SelectionState load() { + return ideaService.getSelectionState(rowModel.getObject()); + } + } + ); + } } - }); + ); columns.add(newStatusColumn()); columns.add(newFirstMeetingColumn()); columns.add(newEditColumn()); - columns.add(new AbstractColumn<>(Model.of("Copy")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new AjaxLinkPanel<>(componentId, rowModel, Model.of("Copy")) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - User currentSupervisor = SciProSession.get().getUser(); - Idea copy = model.getObject().copy(currentSupervisor); - copy = ideaService.save(copy); - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Idea.class), copy.getId()); - setResponsePage(SupervisorIdeaSubmissionPage.class, pp); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Copy")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new AjaxLinkPanel<>(componentId, rowModel, Model.of("Copy")) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + User currentSupervisor = SciProSession.get().getUser(); + Idea copy = model.getObject().copy(currentSupervisor); + copy = ideaService.save(copy); + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Idea.class), copy.getId()); + setResponsePage(SupervisorIdeaSubmissionPage.class, pp); + } + } + ); + } } - }); + ); columns.add(newDeleteColumn()); - FilteredDataProvider provider = new FilteredDataProvider<>(ideaService, Model.of(params)); + FilteredDataProvider provider = new FilteredDataProvider<>( + ideaService, + Model.of(params) + ); provider.setSort("dateCreated", SortOrder.ASCENDING); dataTable = new ExportableDataPanel<>("dataTable", columns, provider); dataTable.setOutputMarkupId(true); @@ -198,19 +235,25 @@ public class SupervisorMyIdeasPanel extends Panel { return new AbstractColumn<>(Model.of("Authors")) { @Override public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new DisplayMultiplesPanel<>(componentId, new ListAdapterModel<>(LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations))) { - @Override - public Component getComponent(String componentId, IModel t) { - return new StudentProfileProgramPanel(componentId, t, false); + cellItem.add( + new DisplayMultiplesPanel<>( + componentId, + new ListAdapterModel<>( + LambdaModel.of(rowModel, Idea::getIdeaParticipations, Idea::setIdeaParticipations) + ) + ) { + @Override + public Component getComponent(String componentId, IModel t) { + return new StudentProfileProgramPanel(componentId, t, false); + } } - }); + ); } }; } private ClickableIconColumn newEditColumn() { return new ClickableIconColumn<>(Model.of("Edit"), null, ClickableIconColumn.EDIT) { - @Override protected void onClick(IModel model, AjaxRequestTarget target) { PageParameters pp = new PageParameters(); @@ -226,8 +269,12 @@ public class SupervisorMyIdeasPanel extends Panel { } private ClickableIconColumn newDeleteColumn() { - return new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE, "Are you sure you want to delete this idea?") { - + return new ClickableIconColumn<>( + Model.of("Delete"), + null, + ClickableIconColumn.DELETE, + "Are you sure you want to delete this idea?" + ) { @Override protected void onClick(IModel model, AjaxRequestTarget target) { ideaService.deleteUnmatchedIdea(model.getObject()); @@ -236,23 +283,23 @@ public class SupervisorMyIdeasPanel extends Panel { @Override public boolean shouldBeVisible(IModel model) { - return model.getObject().getMatchStatus() == Status.UNMATCHED && !model.getObject().isExported(); + return (model.getObject().getMatchStatus() == Status.UNMATCHED && !model.getObject().isExported()); } }; } private AbstractColumn newFirstMeetingColumn() { return new AbstractColumn<>(Model.of("First meeting")) { - @Override public void populateItem(Item> item, String id, final IModel model) { - item.add(new FirstMeetingColumnPanel(id, model) { - - @Override - protected void onColumnClick(AjaxRequestTarget target, IModel model) { - openFirstMeetingDialog(target, model); + item.add( + new FirstMeetingColumnPanel(id, model) { + @Override + protected void onColumnClick(AjaxRequestTarget target, IModel model) { + openFirstMeetingDialog(target, model); + } } - }); + ); } }; } @@ -261,13 +308,15 @@ public class SupervisorMyIdeasPanel extends Panel { return new AbstractExportableColumn<>(Model.of("Title"), "title") { @Override public void populateItem(Item> components, String s, IModel model) { - components.add(LinkWrapper.apply(s, id -> { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Idea.class), model.getObject().getId()); - var link = new BookmarkablePageLink<>(id, SupervisorIdeaDetailsPage.class, pp); - link.setBody(model.map(Idea::getTitle)); - return link; - })); + components.add( + LinkWrapper.apply(s, id -> { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Idea.class), model.getObject().getId()); + var link = new BookmarkablePageLink<>(id, SupervisorIdeaDetailsPage.class, pp); + link.setBody(model.map(Idea::getTitle)); + return link; + }) + ); } @Override @@ -303,8 +352,7 @@ public class SupervisorMyIdeasPanel extends Panel { } else { return getString("status.export.failed"); } - } - else { + } else { return getString("status.awaiting.project.creation"); } } else { @@ -317,12 +365,14 @@ public class SupervisorMyIdeasPanel extends Panel { } private void openFirstMeetingDialog(AjaxRequestTarget target, IModel model) { - modalWindowPlus.setContent(new FirstMeetingPanel(modalWindowPlus.getContentId(), model) { - @Override - public void onSaved(AjaxRequestTarget target) { - target.add(dataTable); + modalWindowPlus.setContent( + new FirstMeetingPanel(modalWindowPlus.getContentId(), model) { + @Override + public void onSaved(AjaxRequestTarget target) { + target.add(dataTable); + } } - }); + ); modalWindowPlus.setTitle("Idea title: " + model.getObject().getTitle()); modalWindowPlus.show(target); } @@ -344,5 +394,4 @@ public class SupervisorMyIdeasPanel extends Panel { private List getIdeaTypes() { return asList(Type.SUPERVISOR, Type.STUDENT); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPage.java index 352e1282e5..e68999737d 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPage.java @@ -3,12 +3,12 @@ package se.su.dsv.scipro.match; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorProjectIdea; -public class SupervisorNewAllSupervisorIdeasPage extends AbstractSupervisorProjectIdeaPage implements MenuHighlightSupervisorProjectIdea { - - - public SupervisorNewAllSupervisorIdeasPage(PageParameters pp) { - super(pp); - add(new SupervisorAllSupervisorIdeasPanel("ideaPanel")); - } +public class SupervisorNewAllSupervisorIdeasPage + extends AbstractSupervisorProjectIdeaPage + implements MenuHighlightSupervisorProjectIdea { + public SupervisorNewAllSupervisorIdeasPage(PageParameters pp) { + super(pp); + add(new SupervisorAllSupervisorIdeasPanel("ideaPanel")); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPage.java b/view/src/main/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPage.java index c31f81761d..4ca8ffca35 100755 --- a/view/src/main/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPage.java +++ b/view/src/main/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -7,11 +8,12 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyIde import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -public class SupervisorSelectableStudentIdeasPage extends AbstractSupervisorProjectIdeaPage implements MenuHighlightSupervisorMyIdeas { +public class SupervisorSelectableStudentIdeasPage + extends AbstractSupervisorProjectIdeaPage + implements MenuHighlightSupervisorMyIdeas { public static final String BACK_LINK = "backLink"; + @Inject private ApplicationPeriodService applicationPeriodService; diff --git a/view/src/main/java/se/su/dsv/scipro/match/UpdateResearchAreasPanel.java b/view/src/main/java/se/su/dsv/scipro/match/UpdateResearchAreasPanel.java index e5986be400..75c01ec9bd 100644 --- a/view/src/main/java/se/su/dsv/scipro/match/UpdateResearchAreasPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/match/UpdateResearchAreasPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import jakarta.inject.Inject; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.link.ExternalLink; @@ -13,19 +16,16 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserImportService; -import jakarta.inject.Inject; -import java.util.Set; -import java.util.stream.Collectors; - public class UpdateResearchAreasPanel extends Panel { + @Inject GeneralSystemSettingsService generalSystemSettingsService; + @Inject Set userImportServices; public UpdateResearchAreasPanel(final String id, final IModel supervisor) { super(id, supervisor); - GeneralSystemSettings generalSystemSettings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); add(new ExternalLink("selectResearchArea", generalSystemSettings.getDaisySelectResearchAreaURL())); @@ -33,28 +33,27 @@ public class UpdateResearchAreasPanel extends Panel { feedback.setOutputMarkupId(true); add(feedback); - add(new AjaxLink<>("sync", supervisor) { - @Override - public void onClick(AjaxRequestTarget target) { - Set imported = userImportServices.stream() + add( + new AjaxLink<>("sync", supervisor) { + @Override + public void onClick(AjaxRequestTarget target) { + Set imported = userImportServices + .stream() .map(uis -> uis.importResearchAreasForSupervisor(getModelObject())) .flatMap(Set::stream) .collect(Collectors.toSet()); - if (imported.stream().allMatch(ResearchArea::isDeleted)) { - error(getString("no.research.areas.found")); + if (imported.stream().allMatch(ResearchArea::isDeleted)) { + error(getString("no.research.areas.found")); + } else { + String names = imported.stream().map(ResearchArea::getTitle).collect(Collectors.joining(", ")); + success(getString("research.areas.imported", Model.of(names))); + } + target.add(feedback); + onResearchAreasUpdated(target); } - else { - String names = imported.stream() - .map(ResearchArea::getTitle) - .collect(Collectors.joining(", ")); - success(getString("research.areas.imported", Model.of(names))); - } - target.add(feedback); - onResearchAreasUpdated(target); } - }); + ); } - protected void onResearchAreasUpdated(final AjaxRequestTarget target) { - } + protected void onResearchAreasUpdated(final AjaxRequestTarget target) {} } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/EditMileStonePhasePanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/EditMileStonePhasePanel.java index 9e83e59b93..468f00dbd9 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/EditMileStonePhasePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/EditMileStonePhasePanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.milestones; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.markup.html.form.Form; @@ -12,8 +13,6 @@ import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.milestones.service.MilestonePhaseTemplateService; -import jakarta.inject.Inject; - /** * @author : emil-siv * Date: 2013-08-16 @@ -33,43 +32,52 @@ public class EditMileStonePhasePanel extends Panel { public EditMileStonePhasePanel(String id, IModel model) { super(id); - feedback = new FeedbackPanel(FEEDBACK); add(feedback.setOutputMarkupId(true)); add(new EditForm(EDIT_FORM, model)); - } private class EditForm extends Form { public EditForm(String id, IModel model) { super(id, model); + add( + new RequiredTextField<>( + TITLE, + LambdaModel.of(model, MilestonePhaseTemplate::getTitle, MilestonePhaseTemplate::setTitle) + ) + ); + add( + new TextArea<>( + DESCRIPTION, + LambdaModel.of( + model, + MilestonePhaseTemplate::getDescription, + MilestonePhaseTemplate::setDescription + ) + ).setRequired(true) + ); + add( + new AjaxSubmitLink(SAVE) { + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedback); + } - - add(new RequiredTextField<>(TITLE, LambdaModel.of(model, MilestonePhaseTemplate::getTitle, MilestonePhaseTemplate::setTitle))); - add(new TextArea<>(DESCRIPTION, LambdaModel.of(model, MilestonePhaseTemplate::getDescription, MilestonePhaseTemplate::setDescription)).setRequired(true)); - add(new AjaxSubmitLink(SAVE) { - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedback); + @Override + protected void onSubmit(AjaxRequestTarget target) { + activitySaved(target); + } } - - @Override - protected void onSubmit(AjaxRequestTarget target) { - activitySaved(target); - } - }); + ); } + @Override protected void onSubmit() { phaseService.save(getModelObject()); } - - } - - protected void activitySaved(AjaxRequestTarget target) { } + protected void activitySaved(AjaxRequestTarget target) {} } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanel.java index 3e84423325..abadfa8c3b 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.markup.html.form.*; @@ -7,7 +9,6 @@ import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.BootstrapCheckBoxMultipleChoice; import se.su.dsv.scipro.components.BootstrapRadioChoice; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; @@ -18,9 +19,7 @@ import se.su.dsv.scipro.system.Event; import se.su.dsv.scipro.system.EventService; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; - -import jakarta.inject.Inject; -import java.util.Arrays; +import se.su.dsv.scipro.system.Sort; public class EditMilestoneActivityPanel extends Panel { @@ -38,10 +37,13 @@ public class EditMilestoneActivityPanel extends Panel { @Inject private MilestoneActivityTemplateService activityService; + @Inject private MilestonePhaseTemplateService phaseService; + @Inject private ProjectTypeService projectTypeService; + @Inject private EventService eventService; @@ -49,12 +51,10 @@ public class EditMilestoneActivityPanel extends Panel { public EditMilestoneActivityPanel(String id, IModel model) { super(id); - feedback = new FeedbackPanel(FEEDBACK); add(feedback.setOutputMarkupId(true)); add(new EditForm(EDIT_FORM, model)); - } private class EditForm extends Form { @@ -63,41 +63,86 @@ public class EditMilestoneActivityPanel extends Panel { public EditForm(String id, IModel model) { super(id, model); - oldPhase = model.getObject().getMilestonePhaseTemplate(); - add(new RequiredTextField<>(TITLE, LambdaModel.of(model, MilestoneActivityTemplate::getTitle, MilestoneActivityTemplate::setTitle))); - add(new TextArea<>(DESCRIPTION, LambdaModel.of(model, MilestoneActivityTemplate::getDescription, MilestoneActivityTemplate::setDescription)).setRequired(true)); - add(new BootstrapRadioChoice<>(TYPE, + add( + new RequiredTextField<>( + TITLE, + LambdaModel.of(model, MilestoneActivityTemplate::getTitle, MilestoneActivityTemplate::setTitle) + ) + ); + add( + new TextArea<>( + DESCRIPTION, + LambdaModel.of( + model, + MilestoneActivityTemplate::getDescription, + MilestoneActivityTemplate::setDescription + ) + ).setRequired(true) + ); + add( + new BootstrapRadioChoice<>( + TYPE, LambdaModel.of(model, MilestoneActivityTemplate::getType, MilestoneActivityTemplate::setType), - Arrays.asList(MilestoneActivityTemplate.Type.values())) - .setRequired(true)); - add(new BootstrapCheckBoxMultipleChoice<>(PROJECT_TYPES, + Arrays.asList(MilestoneActivityTemplate.Type.values()) + ).setRequired(true) + ); + add( + new BootstrapCheckBoxMultipleChoice<>( + PROJECT_TYPES, model.map(MilestoneActivityTemplate::getProjectTypes), projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) - .setRequired(true)); - add(new CheckBox(EDITABLE_BY_AUTHORS, LambdaModel.of(model, MilestoneActivityTemplate::isEditableByStudents, MilestoneActivityTemplate::setEditableByStudents)).setOutputMarkupId(true)); - add(new DropDownChoice<>(MILE_STONE_PHASE_TEMPLATE, - LambdaModel.of(model, MilestoneActivityTemplate::getMilestonePhaseTemplate, MilestoneActivityTemplate::setMilestonePhaseTemplate), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ).setRequired(true) + ); + add( + new CheckBox( + EDITABLE_BY_AUTHORS, + LambdaModel.of( + model, + MilestoneActivityTemplate::isEditableByStudents, + MilestoneActivityTemplate::setEditableByStudents + ) + ).setOutputMarkupId(true) + ); + add( + new DropDownChoice<>( + MILE_STONE_PHASE_TEMPLATE, + LambdaModel.of( + model, + MilestoneActivityTemplate::getMilestonePhaseTemplate, + MilestoneActivityTemplate::setMilestonePhaseTemplate + ), phaseService.findAll(new Sort(Sort.Direction.ASC, SORT_ORDER)), - new LambdaChoiceRenderer<>(MilestonePhaseTemplate::getTitle, MilestonePhaseTemplate::getId)).setRequired(true)); - add(new DropDownChoice<>(EVENT, - LambdaModel.of(model, MilestoneActivityTemplate::getActivatedBy, MilestoneActivityTemplate::setActivatedBy), + new LambdaChoiceRenderer<>(MilestonePhaseTemplate::getTitle, MilestonePhaseTemplate::getId) + ).setRequired(true) + ); + add( + new DropDownChoice<>( + EVENT, + LambdaModel.of( + model, + MilestoneActivityTemplate::getActivatedBy, + MilestoneActivityTemplate::setActivatedBy + ), eventService.findAll(), - new LambdaChoiceRenderer<>(Event::getDescription, Event::getName)).setNullValid(true)); - add(new AjaxSubmitLink(SAVE) { + new LambdaChoiceRenderer<>(Event::getDescription, Event::getName) + ).setNullValid(true) + ); + add( + new AjaxSubmitLink(SAVE) { + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedback); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedback); + @Override + protected void onSubmit(AjaxRequestTarget target) { + activitySaved(target); + } } - - @Override - protected void onSubmit(AjaxRequestTarget target) { - activitySaved(target); - } - }); + ); } @Override @@ -106,6 +151,5 @@ public class EditMilestoneActivityPanel extends Panel { } } - protected void activitySaved(AjaxRequestTarget target) { - } + protected void activitySaved(AjaxRequestTarget target) {} } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/MileStoneActivityAdminPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/MileStoneActivityAdminPanel.java index 5631a9dcc9..5b62406b84 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/MileStoneActivityAdminPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/MileStoneActivityAdminPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -14,7 +16,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.DisplayMultiplesPanel; import se.su.dsv.scipro.components.ListAdapterModel; import se.su.dsv.scipro.components.ModalWindowPlus; @@ -24,9 +25,7 @@ import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.milestones.service.MilestoneActivityTemplateService; import se.su.dsv.scipro.milestones.service.MilestonePhaseTemplateService; import se.su.dsv.scipro.system.ProjectType; - -import jakarta.inject.Inject; -import java.util.List; +import se.su.dsv.scipro.system.Sort; public class MileStoneActivityAdminPanel extends Panel { @@ -48,6 +47,7 @@ public class MileStoneActivityAdminPanel extends Panel { @Inject private MilestonePhaseTemplateService phaseService; + @Inject private MilestoneActivityTemplateService activityService; @@ -57,7 +57,6 @@ public class MileStoneActivityAdminPanel extends Panel { public MileStoneActivityAdminPanel(String id) { super(id); - this.container = new WebMarkupContainer(LIST_CONTAINER); this.feedback = new FeedbackPanel(FEEDBACK); this.dialog = new ModalWindowPlus(DIALOG); @@ -70,46 +69,85 @@ public class MileStoneActivityAdminPanel extends Panel { } private void addCreateNewLink() { - add(new AjaxLink(CREATE_LINK) { - @Override - public void onClick(AjaxRequestTarget target) { - openDialog(target, Model.of(new MilestoneActivityTemplate())); + add( + new AjaxLink(CREATE_LINK) { + @Override + public void onClick(AjaxRequestTarget target) { + openDialog(target, Model.of(new MilestoneActivityTemplate())); + } } - }); - + ); } private void addPhaseList() { - container.add(new ListView<>(PHASE_LIST, getPhaseListModel()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); - addMileStoneList(item); + container.add( + new ListView<>(PHASE_LIST, getPhaseListModel()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); + addMileStoneList(item); + } } - }); + ); } private void addMileStoneList(ListItem item) { - item.add(new ListView<>(MILESTONE_LIST, getActivityListModel(item.getModel())) { - - @Override - protected void populateItem(ListItem item) { - item.add(new SortOrderPanel<>(MOVE, item.getModel(), activityService)); - item.add(new Label(MILESTONE_TITLE, LambdaModel.of(item.getModel(), MilestoneActivityTemplate::getTitle, MilestoneActivityTemplate::setTitle))); - item.add(new Label(TYPE, LambdaModel.of(item.getModel(), MilestoneActivityTemplate::getType, MilestoneActivityTemplate::setType))); - item.add(new DisplayMultiplesPanel<>(PROJECT_TYPES, new ListAdapterModel<>(LambdaModel.of(item.getModel(), MilestoneActivityTemplate::getProjectTypes, MilestoneActivityTemplate::setProjectTypes))) { - @Override - public Component getComponent(String componentId, IModel model) { - return new Label(componentId, LambdaModel.of(model, ProjectType::getName, ProjectType::setName)); - } - }); - item.add(newEditLink(EDIT, item.getModel())); - item.add(newActiveCheckBox(STATE_SWITCH, item.getModel())); + item.add( + new ListView<>(MILESTONE_LIST, getActivityListModel(item.getModel())) { + @Override + protected void populateItem(ListItem item) { + item.add(new SortOrderPanel<>(MOVE, item.getModel(), activityService)); + item.add( + new Label( + MILESTONE_TITLE, + LambdaModel.of( + item.getModel(), + MilestoneActivityTemplate::getTitle, + MilestoneActivityTemplate::setTitle + ) + ) + ); + item.add( + new Label( + TYPE, + LambdaModel.of( + item.getModel(), + MilestoneActivityTemplate::getType, + MilestoneActivityTemplate::setType + ) + ) + ); + item.add( + new DisplayMultiplesPanel<>( + PROJECT_TYPES, + new ListAdapterModel<>( + LambdaModel.of( + item.getModel(), + MilestoneActivityTemplate::getProjectTypes, + MilestoneActivityTemplate::setProjectTypes + ) + ) + ) { + @Override + public Component getComponent(String componentId, IModel model) { + return new Label( + componentId, + LambdaModel.of(model, ProjectType::getName, ProjectType::setName) + ); + } + } + ); + item.add(newEditLink(EDIT, item.getModel())); + item.add(newActiveCheckBox(STATE_SWITCH, item.getModel())); + } } - }); + ); } - private AjaxLink newEditLink(String id, final IModel phaseModel) { + private AjaxLink newEditLink( + String id, + final IModel phaseModel + ) { return new AjaxLink<>(id, phaseModel) { @Override public void onClick(AjaxRequestTarget target) { @@ -138,7 +176,9 @@ public class MileStoneActivityAdminPanel extends Panel { }; } - private LoadableDetachableModel> getActivityListModel(final IModel phaseModel) { + private LoadableDetachableModel> getActivityListModel( + final IModel phaseModel + ) { return new LoadableDetachableModel<>() { @Override protected List load() { @@ -149,15 +189,17 @@ public class MileStoneActivityAdminPanel extends Panel { private void openDialog(AjaxRequestTarget target, IModel model) { dialog.setTitle(model.getObject().getTitle() == null ? "New milestone" : "Edit milestone"); - dialog.setContent(new EditMilestoneActivityPanel(dialog.getContentId(), model) { - @Override - protected void activitySaved(AjaxRequestTarget target) { - info("Milestone saved"); - target.add(feedback); - target.add(container); - dialog.close(target); + dialog.setContent( + new EditMilestoneActivityPanel(dialog.getContentId(), model) { + @Override + protected void activitySaved(AjaxRequestTarget target) { + info("Milestone saved"); + target.add(feedback); + target.add(container); + dialog.close(target); + } } - }); + ); target.add(dialog); dialog.show(target); } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/MileStonePhaseAdminPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/MileStonePhaseAdminPanel.java index 1c52a1364b..ca7ab2c9df 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/MileStonePhaseAdminPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/MileStonePhaseAdminPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -12,14 +14,11 @@ import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.components.SortOrderPanel; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.milestones.service.MilestonePhaseTemplateService; - -import jakarta.inject.Inject; -import java.util.List; +import se.su.dsv.scipro.system.Sort; public class MileStonePhaseAdminPanel extends Panel { @@ -32,7 +31,6 @@ public class MileStonePhaseAdminPanel extends Panel { public MileStonePhaseAdminPanel(String id) { super(id); - this.container = new WebMarkupContainer(LIST_CONTAINER); this.feedback = new FeedbackPanel(FEEDBACK); this.dialog = new ModalWindowPlus(DIALOG); @@ -45,25 +43,28 @@ public class MileStonePhaseAdminPanel extends Panel { } private void addCreateNewLink() { - add(new AjaxLink(CREATE_LINK) { - @Override - public void onClick(AjaxRequestTarget target) { - openDialog(target, Model.of(new MilestonePhaseTemplate())); + add( + new AjaxLink(CREATE_LINK) { + @Override + public void onClick(AjaxRequestTarget target) { + openDialog(target, Model.of(new MilestonePhaseTemplate())); + } } - }); - + ); } private void addPhaseList() { - container.add(new ListView<>(PHASE_LIST, getListModel()) { - @Override - protected void populateItem(ListItem item) { - item.add(new SortOrderPanel<>(MOVE, item.getModel(), phaseService)); - item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); - item.add(newActiveCheckBox(STATE_SWITCH, item.getModel())); - item.add(newEditLink(EDIT, item.getModel())); + container.add( + new ListView<>(PHASE_LIST, getListModel()) { + @Override + protected void populateItem(ListItem item) { + item.add(new SortOrderPanel<>(MOVE, item.getModel(), phaseService)); + item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); + item.add(newActiveCheckBox(STATE_SWITCH, item.getModel())); + item.add(newEditLink(EDIT, item.getModel())); + } } - }); + ); } private AjaxCheckBox newActiveCheckBox(String id, final IModel phase) { @@ -97,15 +98,17 @@ public class MileStonePhaseAdminPanel extends Panel { private void openDialog(AjaxRequestTarget target, IModel model) { dialog.setTitle(model.getObject().getTitle() == null ? "New phase" : "Edit phase"); - dialog.setContent(new EditMileStonePhasePanel(dialog.getContentId(), model) { - @Override - protected void activitySaved(AjaxRequestTarget target) { - info("Phase saved"); - target.add(feedback); - target.add(container); - dialog.close(target); + dialog.setContent( + new EditMileStonePhasePanel(dialog.getContentId(), model) { + @Override + protected void activitySaved(AjaxRequestTarget target) { + info("Phase saved"); + target.add(feedback); + target.add(container); + dialog.close(target); + } } - }); + ); dialog.show(target); } @@ -119,5 +122,4 @@ public class MileStonePhaseAdminPanel extends Panel { static final String EDIT = "edit"; static final String SORT_ORDER = "sortOrder"; static final String MOVE = "move"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/pages/ProjectMileStonePage.java b/view/src/main/java/se/su/dsv/scipro/milestones/pages/ProjectMileStonePage.java index 17f2b880de..11a8cfe74c 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/pages/ProjectMileStonePage.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/pages/ProjectMileStonePage.java @@ -9,13 +9,12 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; -@Authorization(authorizedRoles = { Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.MILESTONES) public class ProjectMileStonePage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects { public ProjectMileStonePage(PageParameters pp) { super(pp); - add(new MileStoneOverviewPanel(OVERVIEW_PANEL, projectModel)); } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/pages/SupervisorMileStonePage.java b/view/src/main/java/se/su/dsv/scipro/milestones/pages/SupervisorMileStonePage.java index 63528d5931..12e3a6de4e 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/pages/SupervisorMileStonePage.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/pages/SupervisorMileStonePage.java @@ -9,20 +9,23 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.ProjectModule; -@Authorization(authorizedRoles = { Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.MILESTONES) -public class SupervisorMileStonePage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { +public class SupervisorMileStonePage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { static final String OVERVIEW_PANEL = "overviewPanel"; public SupervisorMileStonePage(PageParameters pp) { super(pp); - - add(new MileStoneOverviewPanel(OVERVIEW_PANEL, projectModel) { - @Override - protected boolean isSupervisorView() { - return true; + add( + new MileStoneOverviewPanel(OVERVIEW_PANEL, projectModel) { + @Override + protected boolean isSupervisorView() { + return true; + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCheckBoxPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCheckBoxPanel.java index 60460fca59..6c7e3f3a9d 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCheckBoxPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCheckBoxPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -14,8 +15,6 @@ import se.su.dsv.scipro.milestones.service.MileStoneService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class MileStoneCheckBoxPanel extends Panel { @Inject @@ -25,11 +24,22 @@ public class MileStoneCheckBoxPanel extends Panel { private final IModel activityModel; private final MilestoneActivityTemplate.Type activityType; - public MileStoneCheckBoxPanel(String id, IModel projectModel, IModel activityModel, MilestoneActivityTemplate.Type type) { + public MileStoneCheckBoxPanel( + String id, + IModel projectModel, + IModel activityModel, + MilestoneActivityTemplate.Type type + ) { this(id, projectModel, activityModel, null, type); } - public MileStoneCheckBoxPanel(String id, IModel projectModel, IModel activityModel, IModel studentModel, MilestoneActivityTemplate.Type type) { + public MileStoneCheckBoxPanel( + String id, + IModel projectModel, + IModel activityModel, + IModel studentModel, + MilestoneActivityTemplate.Type type + ) { super(id); this.projectModel = projectModel; this.activityModel = activityModel; @@ -41,7 +51,9 @@ public class MileStoneCheckBoxPanel extends Panel { private AjaxCheckBox newCheckBox(final IModel studentModel) { final boolean isProjectMileStone = studentModel == null; - final boolean isConfirmed = isProjectMileStone ? isProjectMileStoneConfirmed(activityModel) : isStudentMileStoneConfirmed(activityModel, studentModel); + final boolean isConfirmed = isProjectMileStone + ? isProjectMileStoneConfirmed(activityModel) + : isStudentMileStoneConfirmed(activityModel, studentModel); return new AjaxCheckBox(CHECKBOX, Model.of(isConfirmed)) { @Override @@ -64,7 +76,11 @@ public class MileStoneCheckBoxPanel extends Panel { protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); AjaxCallListener ajaxCallListener = new AjaxCallListener(); - ajaxCallListener.onPrecondition("if (!confirm('" + getConfirmationMessage(isConfirmed) + "')) {window.location.reload(); return false;}"); + ajaxCallListener.onPrecondition( + "if (!confirm('" + + getConfirmationMessage(isConfirmed) + + "')) {window.location.reload(); return false;}" + ); attributes.getAjaxCallListeners().add(ajaxCallListener); } }; @@ -75,16 +91,18 @@ public class MileStoneCheckBoxPanel extends Panel { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(isCorrectActivityType(activityModel) && - isSeminarActivity(activityModel) && - !isProjectMileStoneConfirmed(activityModel)); + setVisibilityAllowed( + isCorrectActivityType(activityModel) && + isSeminarActivity(activityModel) && + !isProjectMileStoneConfirmed(activityModel) + ); } }; } private boolean isSeminarActivity(IModel activityModel) { MilestoneActivityTemplate activity = activityModel.getObject(); - return activity.isAutomatic() && MilestoneActivityTemplate.CREATE_SEMINAR.equals(activity.getCode()); + return (activity.isAutomatic() && MilestoneActivityTemplate.CREATE_SEMINAR.equals(activity.getCode())); } private boolean isCorrectActivityType(IModel activityModel) { @@ -95,12 +113,28 @@ public class MileStoneCheckBoxPanel extends Panel { return mileStoneService.isConfirmed(projectModel.getObject(), activityModel.getObject()); } - private boolean isStudentMileStoneConfirmed(IModel activityModel, IModel studentModel) { - return mileStoneService.isConfirmed(projectModel.getObject(), studentModel.getObject(), activityModel.getObject()); + private boolean isStudentMileStoneConfirmed( + IModel activityModel, + IModel studentModel + ) { + return mileStoneService.isConfirmed( + projectModel.getObject(), + studentModel.getObject(), + activityModel.getObject() + ); } - private void updateStudentMileStone(IModel activityModel, IModel studentModel, boolean isConfirmed) { - mileStoneService.setConfirmed(projectModel.getObject(), studentModel.getObject(), activityModel.getObject(), !isConfirmed); + private void updateStudentMileStone( + IModel activityModel, + IModel studentModel, + boolean isConfirmed + ) { + mileStoneService.setConfirmed( + projectModel.getObject(), + studentModel.getObject(), + activityModel.getObject(), + !isConfirmed + ); } private void updateProjectMileStone(IModel activityModel, boolean isConfirmed) { diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCounterPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCounterPanel.java index 9b82d8eae9..33505bfba9 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCounterPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneCounterPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; @@ -8,17 +9,31 @@ import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MilestoneActivityTemplateService; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; - public class MileStoneCounterPanel extends Panel { @Inject private MilestoneActivityTemplateService activityService; - public MileStoneCounterPanel(String id, IModel completed, MilestoneActivityTemplate.Type type, IModel projectIModel) { + public MileStoneCounterPanel( + String id, + IModel completed, + MilestoneActivityTemplate.Type type, + IModel projectIModel + ) { super(id); add(new Label(COMPLETED, completed)); - add(new Label(TOTAL, Model.of(activityService.countActivities(type, projectIModel.getObject().getProjectType(), projectIModel.getObject().getStartDate())))); + add( + new Label( + TOTAL, + Model.of( + activityService.countActivities( + type, + projectIModel.getObject().getProjectType(), + projectIModel.getObject().getStartDate() + ) + ) + ) + ); } static final String COMPLETED = "completed"; diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneOverviewPanel.java index 34b4c08c8a..2c08e4e10a 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneOverviewPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -16,27 +19,24 @@ import se.su.dsv.scipro.milestones.service.MilestonePhaseTemplateService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class MileStoneOverviewPanel extends Panel { public static final String MILESTONE_DESCRIPTION = "milestoneDescription"; + @Inject private MilestonePhaseTemplateService phaseService; + @Inject private MilestoneActivityTemplateService activityService; + @Inject private MileStoneService mileStoneService; private final WebMarkupContainer container; private final IModel projectModel; - public MileStoneOverviewPanel(String id, IModel model) { super(id, model); - this.projectModel = model; this.container = new WebMarkupContainer(TABLE_CONTAINER); add(container.setOutputMarkupId(true)); @@ -47,43 +47,64 @@ public class MileStoneOverviewPanel extends Panel { } private void addTableHeaderWithStudentNames() { - container.add(new ListView<>(STUDENT_HEADER, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(STUDENT_NAME, item.getModelObject().getFullName())); + container.add( + new ListView<>(STUDENT_HEADER, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(STUDENT_NAME, item.getModelObject().getFullName())); + } } - }); + ); } private void addMileStonePhaseList() { - container.add(new ListView<>(PHASE_LIST, getPhaseListModel()) { - @Override - protected void populateItem(ListItem item) { - ListView mileStoneList = addMileStoneList(item.getModel()); - item.add(mileStoneList); - item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); - item.setVisible(mileStoneList.getViewSize() > 0); + container.add( + new ListView<>(PHASE_LIST, getPhaseListModel()) { + @Override + protected void populateItem(ListItem item) { + ListView mileStoneList = addMileStoneList(item.getModel()); + item.add(mileStoneList); + item.add(new Label(TITLE, item.getModel().map(MilestonePhaseTemplate::getTitle))); + item.setVisible(mileStoneList.getViewSize() > 0); + } } - }); + ); } private void addCounter() { - container.add(new MileStoneCounterPanel(PROJECT_COUNTER, countCompleted(null), MilestoneActivityTemplate.Type.PROJECT, projectModel)); - container.add(new ListView<>(STUDENT_COUNTER_LIST, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { - @Override - protected void populateItem(ListItem item) { - item.add(new MileStoneCounterPanel(STUDENT_COUNTER, countCompleted(item.getModel()), MilestoneActivityTemplate.Type.STUDENT, projectModel)); + container.add( + new MileStoneCounterPanel( + PROJECT_COUNTER, + countCompleted(null), + MilestoneActivityTemplate.Type.PROJECT, + projectModel + ) + ); + container.add( + new ListView<>(STUDENT_COUNTER_LIST, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { + @Override + protected void populateItem(ListItem item) { + item.add( + new MileStoneCounterPanel( + STUDENT_COUNTER, + countCompleted(item.getModel()), + MilestoneActivityTemplate.Type.STUDENT, + projectModel + ) + ); + } } - }); + ); } private ListView addMileStoneList(final IModel phaseModel) { return new ListView<>(MILESTONE_LIST, getActivityListModel(phaseModel)) { - @Override protected void populateItem(ListItem item) { item.add(new Label(MILESTONE_TITLE, item.getModel().map(MilestoneActivityTemplate::getTitle))); - item.add(new InfoPanel(MILESTONE_DESCRIPTION, item.getModel().map(MilestoneActivityTemplate::getDescription))); + item.add( + new InfoPanel(MILESTONE_DESCRIPTION, item.getModel().map(MilestoneActivityTemplate::getDescription)) + ); addSupervisorCheckBox(item); addAuthorStatusCheck(item); addStudentColumns(item); @@ -93,47 +114,83 @@ public class MileStoneOverviewPanel extends Panel { private void addSupervisorCheckBox(ListItem item) { final IModel activityModel = item.getModel(); - item.add(new MileStoneCheckBoxPanel(PROJECT_CHECKBOX, projectModel, item.getModel(), MilestoneActivityTemplate.Type.PROJECT) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isSupervisorView() || activityModel.getObject().isEditableByStudents()); + item.add( + new MileStoneCheckBoxPanel( + PROJECT_CHECKBOX, + projectModel, + item.getModel(), + MilestoneActivityTemplate.Type.PROJECT + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isSupervisorView() || activityModel.getObject().isEditableByStudents()); + } } - }); + ); } private void addAuthorStatusCheck(ListItem item) { final IModel activityModel = item.getModel(); - item.add(new MileStoneStatusPanel(PROJECT_STATUS, projectModel, item.getModel(), MilestoneActivityTemplate.Type.PROJECT) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isSupervisorView() && !activityModel.getObject().isEditableByStudents()); + item.add( + new MileStoneStatusPanel( + PROJECT_STATUS, + projectModel, + item.getModel(), + MilestoneActivityTemplate.Type.PROJECT + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!isSupervisorView() && !activityModel.getObject().isEditableByStudents()); + } } - }); + ); } private void addStudentColumns(ListItem item) { final IModel activityModel = item.getModel(); - item.add(new ListView<>(STUDENTS, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { - @Override - protected void populateItem(ListItem item) { - item.add(new MileStoneCheckBoxPanel(STUDENT_CHECKBOX, projectModel, activityModel, item.getModel(), MilestoneActivityTemplate.Type.STUDENT) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isSupervisorView() || activityModel.getObject().isEditableByStudents()); - } - }); - item.add(new MileStoneStatusPanel(STUDENT_STATUS, projectModel, activityModel, item.getModel(), MilestoneActivityTemplate.Type.STUDENT) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isSupervisorView() && !activityModel.getObject().isEditableByStudents()); - } - }); + item.add( + new ListView<>(STUDENTS, new ArrayList<>(projectModel.getObject().getProjectParticipants())) { + @Override + protected void populateItem(ListItem item) { + item.add( + new MileStoneCheckBoxPanel( + STUDENT_CHECKBOX, + projectModel, + activityModel, + item.getModel(), + MilestoneActivityTemplate.Type.STUDENT + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + isSupervisorView() || activityModel.getObject().isEditableByStudents() + ); + } + } + ); + item.add( + new MileStoneStatusPanel( + STUDENT_STATUS, + projectModel, + activityModel, + item.getModel(), + MilestoneActivityTemplate.Type.STUDENT + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + !isSupervisorView() && !activityModel.getObject().isEditableByStudents() + ); + } + } + ); + } } - }); + ); } private LoadableDetachableModel> getPhaseListModel() { @@ -145,7 +202,9 @@ public class MileStoneOverviewPanel extends Panel { }; } - private LoadableDetachableModel> getActivityListModel(final IModel phaseModel) { + private LoadableDetachableModel> getActivityListModel( + final IModel phaseModel + ) { return new LoadableDetachableModel<>() { @Override protected List load() { @@ -158,9 +217,9 @@ public class MileStoneOverviewPanel extends Panel { return new LoadableDetachableModel<>() { @Override protected Long load() { - return studentModel == null ? - mileStoneService.countProjectMilestones(projectModel.getObject(), true) - : mileStoneService.countMileStones(projectModel.getObject(), studentModel.getObject(), true); + return studentModel == null + ? mileStoneService.countProjectMilestones(projectModel.getObject(), true) + : mileStoneService.countMileStones(projectModel.getObject(), studentModel.getObject(), true); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneProgressPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneProgressPanel.java index 52b5075319..22af7e2583 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneProgressPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneProgressPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -11,9 +13,6 @@ import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MilestoneActivityTemplateService; import se.su.dsv.scipro.project.Project; -import jakarta.inject.Inject; -import java.util.List; - public class MileStoneProgressPanel extends Panel { @Inject @@ -23,7 +22,12 @@ public class MileStoneProgressPanel extends Panel { private final MilestoneActivityTemplate.Type type; private final IModel projectIModel; - public MileStoneProgressPanel(String id, IModel completed, MilestoneActivityTemplate.Type type, IModel projectIModel) { + public MileStoneProgressPanel( + String id, + IModel completed, + MilestoneActivityTemplate.Type type, + IModel projectIModel + ) { super(id); this.completed = completed; this.type = type; @@ -33,33 +37,42 @@ public class MileStoneProgressPanel extends Panel { } private void addProgressBar() { - add(new ListView(LIST, getActivities()) { + add( + new ListView(LIST, getActivities()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(LIST_BOX, NON_BREAKABLE_SPACE).setEscapeModelStrings(false)); + } - @Override - protected void populateItem(ListItem item) { - item.add(new Label(LIST_BOX, NON_BREAKABLE_SPACE).setEscapeModelStrings(false)); + @Override + protected ListItem newItem( + int index, + IModel itemModel + ) { + return new ListItem(index, getListItemModel(getModel(), index)) { + @Override + protected void onComponentTag(final ComponentTag tag) { + tag.put( + "class", + (getIndex() > completed.getObject() - 1) ? "progress-white" : "progress-green" + ); + super.onComponentTag(tag); + } + }; + } } - - @Override - protected ListItem newItem(int index, IModel itemModel) { - return new ListItem(index, getListItemModel(getModel(), index)) { - @Override - protected void onComponentTag(final ComponentTag tag) { - tag.put("class", (getIndex() > completed.getObject() - 1) ? "progress-white" : "progress-green"); - super.onComponentTag(tag); - } - }; - } - - }); - + ); } private LoadableDetachableModel> getActivities() { return new LoadableDetachableModel>() { @Override protected List load() { - return activityService.getActivities(type, projectIModel.getObject().getProjectType(), projectIModel.getObject().getStartDate()); + return activityService.getActivities( + type, + projectIModel.getObject().getProjectType(), + projectIModel.getObject().getStartDate() + ); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneStatusPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneStatusPanel.java index 935852b3dd..81c287b63e 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneStatusPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MileStoneStatusPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.WebComponent; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -12,8 +13,6 @@ import se.su.dsv.scipro.milestones.service.MileStoneService; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class MileStoneStatusPanel extends Panel { @Inject @@ -23,11 +22,22 @@ public class MileStoneStatusPanel extends Panel { private final IModel activityModel; private final MilestoneActivityTemplate.Type activityType; - public MileStoneStatusPanel(String id, IModel projectModel, IModel activityModel, MilestoneActivityTemplate.Type type) { + public MileStoneStatusPanel( + String id, + IModel projectModel, + IModel activityModel, + MilestoneActivityTemplate.Type type + ) { this(id, projectModel, activityModel, null, type); } - public MileStoneStatusPanel(String id, IModel projectModel, final IModel activityModel, IModel studentModel, MilestoneActivityTemplate.Type type) { + public MileStoneStatusPanel( + String id, + IModel projectModel, + final IModel activityModel, + IModel studentModel, + MilestoneActivityTemplate.Type type + ) { super(id); this.projectModel = projectModel; this.activityModel = activityModel; @@ -36,21 +46,27 @@ public class MileStoneStatusPanel extends Panel { final boolean isProjectMileStone = studentModel == null; final Milestone milestone = isProjectMileStone ? getProjectMileStone() : getStudentMileStone(studentModel); - add(new WebComponent(CHECK_ICON) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(milestone.isConfirmed()); + add( + new WebComponent(CHECK_ICON) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(milestone.isConfirmed()); + } } - }); + ); - add(new WebMarkupContainer(NOT_CHECKED) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!milestone.isConfirmed() && activityType == activityModel.getObject().getType()); - } - }.add(new AttributeAppender("title", getNotCompletedModel(), ""))); + add( + new WebMarkupContainer(NOT_CHECKED) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + !milestone.isConfirmed() && activityType == activityModel.getObject().getType() + ); + } + }.add(new AttributeAppender("title", getNotCompletedModel(), "")) + ); } private Milestone getProjectMileStone() { @@ -58,7 +74,11 @@ public class MileStoneStatusPanel extends Panel { } private Milestone getStudentMileStone(IModel studentModel) { - return mileStoneService.getMileStone(projectModel.getObject(), studentModel.getObject(), activityModel.getObject()); + return mileStoneService.getMileStone( + projectModel.getObject(), + studentModel.getObject(), + activityModel.getObject() + ); } private StringResourceModel getNotCompletedModel() { diff --git a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanel.java b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanel.java index 225cf7f1c1..6c67199ea9 100644 --- a/view/src/main/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones.panels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -15,94 +17,121 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; - @ProjectModuleComponent(ProjectModule.MILESTONES) public class MilestoneSummaryPanel extends Panel { - @Inject - private MileStoneService mileStoneService; - @Inject - private MilestoneActivityTemplateService activityService; + @Inject + private MileStoneService mileStoneService; - private final IModel projectModel; + @Inject + private MilestoneActivityTemplateService activityService; + + private final IModel projectModel; public MilestoneSummaryPanel(String id, IModel projectModel) { - super(id); - this.projectModel = projectModel; + super(id); + this.projectModel = projectModel; - addProjectProgress(); - addStudentProgress(); - addUpcomingActivities(); - } + addProjectProgress(); + addStudentProgress(); + addUpcomingActivities(); + } - private void addProjectProgress() { - add(new MileStoneProgressPanel(PROJECT_PROGRESS, countProject(), MilestoneActivityTemplate.Type.PROJECT, projectModel)); - } + private void addProjectProgress() { + add( + new MileStoneProgressPanel( + PROJECT_PROGRESS, + countProject(), + MilestoneActivityTemplate.Type.PROJECT, + projectModel + ) + ); + } - private void addStudentProgress() { - add(new ListView<>(STUDENT_LIST, new ListAdapterModel<>(LambdaModel.of(projectModel, Project::getProjectParticipants, Project::setProjectParticipants))) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(STUDENT_NAME, item.getModelObject().getFullName())); - item.add(new MileStoneProgressPanel(STUDENT_PROGRESS, countStudent(item.getModel()), MilestoneActivityTemplate.Type.STUDENT, projectModel)); - } - }); - } + private void addStudentProgress() { + add( + new ListView<>( + STUDENT_LIST, + new ListAdapterModel<>( + LambdaModel.of(projectModel, Project::getProjectParticipants, Project::setProjectParticipants) + ) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(STUDENT_NAME, item.getModelObject().getFullName())); + item.add( + new MileStoneProgressPanel( + STUDENT_PROGRESS, + countStudent(item.getModel()), + MilestoneActivityTemplate.Type.STUDENT, + projectModel + ) + ); + } + } + ); + } - private void addUpcomingActivities() { - final FilteredListModel upcoming = new FilteredListModel<>(getActivitiesInOrder()) { - @Override - protected boolean accept(MilestoneActivityTemplate mileStoneActivity) { - return !mileStoneService.isConfirmed(projectModel.getObject(), mileStoneActivity); - } - }; - ListView listView = new ListView<>(UPCOMING_LIST, upcoming) { - @Override - protected void populateItem(final ListItem item) { - item.add(new Label(TITLE, item.getModel().map(MilestoneActivityTemplate::getTitle))); - } - }; + private void addUpcomingActivities() { + final FilteredListModel upcoming = new FilteredListModel<>(getActivitiesInOrder()) { + @Override + protected boolean accept(MilestoneActivityTemplate mileStoneActivity) { + return !mileStoneService.isConfirmed(projectModel.getObject(), mileStoneActivity); + } + }; + ListView listView = new ListView<>(UPCOMING_LIST, upcoming) { + @Override + protected void populateItem(final ListItem item) { + item.add(new Label(TITLE, item.getModel().map(MilestoneActivityTemplate::getTitle))); + } + }; listView.setViewSize(ACTIVITIES_TO_SHOW); - add(listView); - } + add(listView); + } private IModel countStudent(final IModel studentModel) { - return Model.of(mileStoneService.countMileStones(projectModel.getObject(), studentModel.getObject(), true)); - } + return Model.of(mileStoneService.countMileStones(projectModel.getObject(), studentModel.getObject(), true)); + } - private IModel countProject() { - return new LoadableDetachableModel<>() { - @Override - protected Long load() { - return mileStoneService.countProjectMilestones(projectModel.getObject(), true); - } - }; - } + private IModel countProject() { + return new LoadableDetachableModel<>() { + @Override + protected Long load() { + return mileStoneService.countProjectMilestones(projectModel.getObject(), true); + } + }; + } - private IModel> getActivitiesInOrder() { - return new LoadableDetachableModel<>() { - @Override - protected List load() { - return activityService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, projectModel.getObject()); - } - }; - } + private IModel> getActivitiesInOrder() { + return new LoadableDetachableModel<>() { + @Override + protected List load() { + return activityService.getActivitiesInOrder( + MilestoneActivityTemplate.Type.PROJECT, + projectModel.getObject() + ); + } + }; + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(activityService.countActivities(projectModel.getObject().getProjectType(), projectModel.getObject().getStartDate()) != 0); - } + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + activityService.countActivities( + projectModel.getObject().getProjectType(), + projectModel.getObject().getStartDate() + ) != + 0 + ); + } - static final String STUDENT_LIST = "studentList"; - static final String STUDENT_NAME = "studentName"; - static final String STUDENT_PROGRESS = "studentProgress"; - static final String PROJECT_PROGRESS = "projectProgress"; - static final String UPCOMING_LIST = "upcomingList"; - static final String TITLE = "title"; - - static final int ACTIVITIES_TO_SHOW = 3; + static final String STUDENT_LIST = "studentList"; + static final String STUDENT_NAME = "studentName"; + static final String STUDENT_PROGRESS = "studentProgress"; + static final String PROJECT_PROGRESS = "projectProgress"; + static final String UPCOMING_LIST = "upcomingList"; + static final String TITLE = "title"; + static final int ACTIVITIES_TO_SHOW = 3; } diff --git a/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanel.java b/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanel.java index f46fe4ca8a..aa720b0876 100755 --- a/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.nonworkdays; +import jakarta.inject.Inject; +import java.time.LocalDate; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.markup.html.form.Form; @@ -13,9 +15,6 @@ import se.su.dsv.scipro.components.BootstrapDatePicker; import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriod; import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriodService; -import jakarta.inject.Inject; -import java.time.LocalDate; - public abstract class NonWorkDaysCRUDPanel extends Panel { public static final String FEEDBACK = "feedback"; @@ -34,31 +33,46 @@ public abstract class NonWorkDaysCRUDPanel extends Panel { public NonWorkDaysCRUDPanel(String id, final IModel model) { super(id, model); - feedback = new FeedbackPanel(FEEDBACK); feedback.setOutputMarkupId(true); add(feedback); Form form = new Form<>(FORM, model); - form.add(new RequiredTextField<>(START_DATE, LambdaModel.of(model, NonWorkDayPeriod::getStartDate, NonWorkDayPeriod::setStartDate), LocalDate.class) - .add(new BootstrapDatePicker())); - form.add(new RequiredTextField<>(END_DATE, LambdaModel.of(model, NonWorkDayPeriod::getEndDate, NonWorkDayPeriod::setEndDate), LocalDate.class) - .add(new BootstrapDatePicker())); - form.add(new TextArea<>(COMMENT, LambdaModel.of(model, NonWorkDayPeriod::getComment, NonWorkDayPeriod::setComment)) - .setRequired(true)); + form.add( + new RequiredTextField<>( + START_DATE, + LambdaModel.of(model, NonWorkDayPeriod::getStartDate, NonWorkDayPeriod::setStartDate), + LocalDate.class + ).add(new BootstrapDatePicker()) + ); + form.add( + new RequiredTextField<>( + END_DATE, + LambdaModel.of(model, NonWorkDayPeriod::getEndDate, NonWorkDayPeriod::setEndDate), + LocalDate.class + ).add(new BootstrapDatePicker()) + ); + form.add( + new TextArea<>( + COMMENT, + LambdaModel.of(model, NonWorkDayPeriod::getComment, NonWorkDayPeriod::setComment) + ).setRequired(true) + ); - form.add(new AjaxSubmitLink(SAVE) { - @Override - protected void onSubmit(AjaxRequestTarget target) { - target.add(feedback); - if (model.getObject().getStartDate().isAfter(model.getObject().getEndDate())) { - error("Start date has to be before end date"); - return; + form.add( + new AjaxSubmitLink(SAVE) { + @Override + protected void onSubmit(AjaxRequestTarget target) { + target.add(feedback); + if (model.getObject().getStartDate().isAfter(model.getObject().getEndDate())) { + error("Start date has to be before end date"); + return; + } + model.setObject(nonWorkDayPeriodService.save(model.getObject())); + handleSave(target); } - model.setObject(nonWorkDayPeriodService.save(model.getObject())); - handleSave(target); } - }); + ); add(form); } } diff --git a/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPage.java b/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPage.java index 1c26c2880b..8e2dcd5b65 100644 --- a/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPage.java +++ b/view/src/main/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.nonworkdays; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -19,13 +23,9 @@ import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriodService; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class NonWorkDaysPage extends AbstractAdminProjectPage { + public static final String DIALOG = "modalWindowPlus"; public static final String ADD = "add"; public static final String FEEDBACK = "feedback"; @@ -58,18 +58,20 @@ public class NonWorkDaysPage extends AbstractAdminProjectPage { } private void addAddNewLink() { - add(new AjaxLink(ADD) { - @Override - public void onClick(AjaxRequestTarget target) { - modalWindowPlus.setTitle("Add new non work days period"); - NonWorkDayPeriod nonWorkDayPeriod = new NonWorkDayPeriod(); - nonWorkDayPeriod.setStartDate(LocalDate.now()); - nonWorkDayPeriod.setEndDate(LocalDate.now()); - nonWorkDayPeriod.setComment(""); + add( + new AjaxLink(ADD) { + @Override + public void onClick(AjaxRequestTarget target) { + modalWindowPlus.setTitle("Add new non work days period"); + NonWorkDayPeriod nonWorkDayPeriod = new NonWorkDayPeriod(); + nonWorkDayPeriod.setStartDate(LocalDate.now()); + nonWorkDayPeriod.setEndDate(LocalDate.now()); + nonWorkDayPeriod.setComment(""); - dialog(new Model<>(nonWorkDayPeriod), target); + dialog(new Model<>(nonWorkDayPeriod), target); + } } - }); + ); } private void addDataTable() { @@ -84,35 +86,41 @@ public class NonWorkDaysPage extends AbstractAdminProjectPage { columns.add(new LambdaColumn<>(Model.of("From"), "startDate", NonWorkDayPeriod::getStartDate)); columns.add(new LambdaColumn<>(Model.of("To"), "endDate", NonWorkDayPeriod::getEndDate)); columns.add(new LambdaColumn<>(Model.of("Comment"), NonWorkDayPeriod::getComment)); - columns.add(new ClickableIconColumn<>(Model.of("Edit"), null, ClickableIconColumn.EDIT) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - modalWindowPlus.setTitle("Edit non work days period"); - dialog(clicked, target); + columns.add( + new ClickableIconColumn<>(Model.of("Edit"), null, ClickableIconColumn.EDIT) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + modalWindowPlus.setTitle("Edit non work days period"); + dialog(clicked, target); + } } - }); - columns.add(new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE) { - @Override - protected void onClick(IModel clicked, AjaxRequestTarget target) { - nonWorkDayPeriodService.delete(clicked.getObject().getId()); - info("Deleted non work days period"); - target.add(dp); - target.add(feedback); + ); + columns.add( + new ClickableIconColumn<>(Model.of("Delete"), null, ClickableIconColumn.DELETE) { + @Override + protected void onClick(IModel clicked, AjaxRequestTarget target) { + nonWorkDayPeriodService.delete(clicked.getObject().getId()); + info("Deleted non work days period"); + target.add(dp); + target.add(feedback); + } } - }); + ); return columns; } public void dialog(IModel model, AjaxRequestTarget target) { - modalWindowPlus.setContent(new NonWorkDaysCRUDPanel(modalWindowPlus.getContentId(), model) { - @Override - public void handleSave(AjaxRequestTarget target) { - modalWindowPlus.close(target); - info("Saved non work days period"); - target.add(dp); - target.add(feedback); + modalWindowPlus.setContent( + new NonWorkDaysCRUDPanel(modalWindowPlus.getContentId(), model) { + @Override + public void handleSave(AjaxRequestTarget target) { + modalWindowPlus.close(target); + info("Saved non work days period"); + target.add(dp); + target.add(feedback); + } } - }); + ); modalWindowPlus.show(target); } } diff --git a/view/src/main/java/se/su/dsv/scipro/notes/NotesPage.java b/view/src/main/java/se/su/dsv/scipro/notes/NotesPage.java index 06e1b87fd0..858744f8cf 100644 --- a/view/src/main/java/se/su/dsv/scipro/notes/NotesPage.java +++ b/view/src/main/java/se/su/dsv/scipro/notes/NotesPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notes; +import jakarta.inject.Inject; +import java.util.Date; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -15,37 +17,46 @@ import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.date.DateService; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.Date; - public class NotesPage extends MenuPage { @Inject private NoteService noteService; + @Inject private DateService dateService; private final FeedbackPanel feedback; - public NotesPage(){ + public NotesPage() { feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); - add(new NoteForm("form", new DetachableServiceModel<>(noteService, noteService.getNote(SciProSession.get().getUser())))); + add( + new NoteForm( + "form", + new DetachableServiceModel<>(noteService, noteService.getNote(SciProSession.get().getUser())) + ) + ); } private class NoteForm extends Form { + public NoteForm(String id, IModel model) { super(id, model); - TextArea contents = new TextArea<>("content", LambdaModel.of(model, Note::getContent, Note::setContent)); - contents.add(new AutoSavingBehaviour() { - @Override - protected void onUpdate(AjaxRequestTarget target) { - noteService.save(getModelObject()); - showSavedNotesFeedback(); - target.add(feedback); + TextArea contents = new TextArea<>( + "content", + LambdaModel.of(model, Note::getContent, Note::setContent) + ); + contents.add( + new AutoSavingBehaviour() { + @Override + protected void onUpdate(AjaxRequestTarget target) { + noteService.save(getModelObject()); + showSavedNotesFeedback(); + target.add(feedback); + } } - }); + ); add(contents); } diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/NotificationLoader.java b/view/src/main/java/se/su/dsv/scipro/notifications/NotificationLoader.java index 0f60a3a99d..156484db01 100755 --- a/view/src/main/java/se/su/dsv/scipro/notifications/NotificationLoader.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/NotificationLoader.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.notifications; +import java.io.IOException; +import java.util.Locale; +import java.util.Properties; import org.apache.wicket.Component; import org.apache.wicket.resource.loader.IStringResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.su.dsv.scipro.util.PropsUtils; -import java.io.IOException; -import java.util.Locale; -import java.util.Properties; - - public class NotificationLoader implements IStringResourceLoader { + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationLoader.class); @Override @@ -34,4 +33,4 @@ public class NotificationLoader implements IStringResourceLoader { } return keyWord; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationLandingPage.java b/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationLandingPage.java index 0fc12af49a..4a999d66f4 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationLandingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationLandingPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.notifications.pages; +import jakarta.inject.Inject; +import java.util.Optional; +import java.util.function.BiConsumer; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -21,8 +24,8 @@ import se.su.dsv.scipro.match.ProjectIdeaStartPage; import se.su.dsv.scipro.match.SupervisorIdeaStartPage; import se.su.dsv.scipro.milestones.pages.ProjectMileStonePage; import se.su.dsv.scipro.milestones.pages.SupervisorMileStonePage; -import se.su.dsv.scipro.notifications.NotificationService; import se.su.dsv.scipro.notifications.NotificationEventService; +import se.su.dsv.scipro.notifications.NotificationService; import se.su.dsv.scipro.notifications.dataobject.*; import se.su.dsv.scipro.peer.*; import se.su.dsv.scipro.project.Project; @@ -39,22 +42,19 @@ import se.su.dsv.scipro.supervisor.pages.*; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Optional; -import java.util.function.BiConsumer; - @Authorization( - authorizedRoles = {Roles.AUTHOR, Roles.SUPERVISOR, Roles.REVIEWER, Roles.EXAMINER, Roles.ADMIN, Roles.SYSADMIN} + authorizedRoles = { Roles.AUTHOR, Roles.SUPERVISOR, Roles.REVIEWER, Roles.EXAMINER, Roles.ADMIN, Roles.SYSADMIN } ) public class NotificationLandingPage extends WebPage { + @Inject private NotificationEventService notificationEventService; + @Inject private NotificationService notificationService; public NotificationLandingPage(PageParameters pp) { super(pp); - Optional optionalNotificationEvent; try { final long id = pp.get("id").toLong(); @@ -88,8 +88,7 @@ public class NotificationLandingPage extends WebPage { case PEER: if (notificationEvent instanceof PeerEvent peerEvent) { redirectToPeerReviewNotificationPage(peerEvent); - } - else if (notificationEvent instanceof PeerRequestEvent peerRequestEvent) { + } else if (notificationEvent instanceof PeerRequestEvent peerRequestEvent) { redirectToPeerRequestNotificationPage(peerRequestEvent); } break; @@ -103,7 +102,7 @@ public class NotificationLandingPage extends WebPage { redirectToForumNotificationPage((ProjectForumEvent) notificationEvent); break; default: - // no specific redirect, will default to start page + // no specific redirect, will default to start page } } @@ -114,14 +113,24 @@ public class NotificationLandingPage extends WebPage { final PageParameters pp = new PageParameters(); pp.set(PageParameterKeys.MAP.get(Project.class), project.getId()); - final BiConsumer, Class> defaultSplit = - (authorPage, supervisorPage) -> - roleSplit(currentUser, project, authorPage, supervisorPage, pp); + final BiConsumer, Class> defaultSplit = ( + authorPage, + supervisorPage + ) -> roleSplit(currentUser, project, authorPage, supervisorPage, pp); switch (projectEvent.getEvent()) { - case CREATED, COMPLETED, AUTHORS_CHANGED, HEAD_SUPERVISOR_CHANGED, REVIEWERS_CHANGED, - CO_SUPERVISOR_CHANGED, STATE_CHANGED, FINAL_THESIS_APPROVED, PROJECT_ACTIVATED, PROJECT_DEACTIVATED, - ONE_YEAR_PASSED_FROM_LATEST_ANNUAL_REVIEW, EXPORTED_SUCCESS: + case CREATED, + COMPLETED, + AUTHORS_CHANGED, + HEAD_SUPERVISOR_CHANGED, + REVIEWERS_CHANGED, + CO_SUPERVISOR_CHANGED, + STATE_CHANGED, + FINAL_THESIS_APPROVED, + PROJECT_ACTIVATED, + PROJECT_DEACTIVATED, + ONE_YEAR_PASSED_FROM_LATEST_ANNUAL_REVIEW, + EXPORTED_SUCCESS: defaultSplit.accept(ProjectDetailsPage.class, SupervisorProjectDetailsPage.class); break; case ACTIVITY_ADDED, ACTIVITY_REMOVED, ACTIVITY_EDITED, CHECKLIST_ADDED, CHECKLIST_ANSWERED: @@ -144,21 +153,21 @@ public class NotificationLandingPage extends WebPage { finalSeminarApprovalPP.set("anchor", "finalSeminarApproval"); if (project.isSupervisor(currentUser)) { setResponsePage(SupervisorInteractWithReviewerPage.class, finalSeminarApprovalPP); - } - else if (project.isReviewer(currentUser)) { + } else if (project.isReviewer(currentUser)) { setResponsePage(ReviewerStartPage.class, finalSeminarApprovalPP); } break; case ROUGH_DRAFT_APPROVAL_REQUESTED, ROUGH_DRAFT_APPROVAL_APPROVED, ROUGH_DRAFT_APPROVAL_REJECTED: if (project.isSupervisor(currentUser)) { setResponsePage(SupervisorInteractWithReviewerPage.class, pp); - } - else if (project.isReviewer(currentUser)) { + } else if (project.isReviewer(currentUser)) { PageParameters reviewerParameters = RoughDraftApprovalDecisionPage.pageParametersFor(project); setResponsePage(RoughDraftApprovalDecisionPage.class, reviewerParameters); } break; - case REVIEWER_GRADING_INITIAL_ASSESSMENT_DONE, REVIEWER_GRADING_REPORT_SUBMITTED, REFLECTION_IMPROVEMENTS_SUBMITTED: + case REVIEWER_GRADING_INITIAL_ASSESSMENT_DONE, + REVIEWER_GRADING_REPORT_SUBMITTED, + REFLECTION_IMPROVEMENTS_SUBMITTED: if (project.isSupervisor(currentUser)) { setResponsePage(SupervisorGradingReportPage.class, pp); } @@ -175,7 +184,7 @@ public class NotificationLandingPage extends WebPage { defaultSplit.accept(ProjectOppositionPage.class, SupervisorProjectDetailsPage.class); break; default: - // no specific redirect, will default to start page + // no specific redirect, will default to start page } } @@ -185,8 +194,11 @@ public class NotificationLandingPage extends WebPage { if (idea.getIdeaParticipations().stream().anyMatch(ip -> ip.getUser().equals(currentUser))) { setResponsePage(ProjectIdeaStartPage.class); - } - else if (idea.getMatch() != null && idea.getMatch().getSupervisor() != null && idea.getMatch().getSupervisor().equals(currentUser)) { + } else if ( + idea.getMatch() != null && + idea.getMatch().getSupervisor() != null && + idea.getMatch().getSupervisor().equals(currentUser) + ) { setResponsePage(SupervisorIdeaStartPage.class); } } @@ -200,11 +212,11 @@ public class NotificationLandingPage extends WebPage { if (seminar.getProject().isParticipant(currentUser)) { setResponsePage(ProjectFinalSeminarPage.class, pp); - } - else if (hasSupervisingRole(seminar.getProject(), currentUser)) { + } else if (hasSupervisingRole(seminar.getProject(), currentUser)) { setResponsePage(SupervisorFinalSeminarPage.class, pp); - } - else if (seminar.getActiveParticipants().contains(currentUser) || seminar.getOpponents().contains(currentUser)) { + } else if ( + seminar.getActiveParticipants().contains(currentUser) || seminar.getOpponents().contains(currentUser) + ) { setResponsePage(ProjectFinalSeminarDetailsPage.class, pp); } } @@ -224,9 +236,21 @@ public class NotificationLandingPage extends WebPage { switch (peerEvent.getEvent()) { case REVIEW_COMPLETED, REVIEW_COMMENT: // Will redirect requester project related - roleSplit(currentUser, requesterProject, ViewPeerReviewPage.class, SupervisorViewPeerReviewPage.class, requesterPP); + roleSplit( + currentUser, + requesterProject, + ViewPeerReviewPage.class, + SupervisorViewPeerReviewPage.class, + requesterPP + ); // Will redirect reviewer project related - roleSplit(currentUser, peerReview.getProject(), ViewPeerReviewPage.class, SupervisorViewPeerReviewPage.class, reviewerPP); + roleSplit( + currentUser, + peerReview.getProject(), + ViewPeerReviewPage.class, + SupervisorViewPeerReviewPage.class, + reviewerPP + ); break; case REVIEW_ACCEPTED: if (currentUser.equals(peerReview.getPeerRequest().getRequester())) { @@ -234,10 +258,8 @@ public class NotificationLandingPage extends WebPage { } break; default: - // no specific redirect, will default to start page + // no specific redirect, will default to start page } - - } private void redirectToPeerRequestNotificationPage(final PeerRequestEvent peerRequestEvent) { @@ -253,7 +275,11 @@ public class NotificationLandingPage extends WebPage { } break; case REQUEST_EXPIRED: - final Optional peerReview = peerRequest.getPeerReviews().stream().filter(pr -> pr.getReviewer().equals(currentUser)).findAny(); + final Optional peerReview = peerRequest + .getPeerReviews() + .stream() + .filter(pr -> pr.getReviewer().equals(currentUser)) + .findAny(); if (peerReview.isPresent()) { final PageParameters pp = new PageParameters(); pp.set(PageParameterKeys.MAP.get(Project.class), peerReview.get().getProject().getId()); @@ -261,14 +287,20 @@ public class NotificationLandingPage extends WebPage { } break; default: - // no specific redirect, will default to start page + // no specific redirect, will default to start page } } private void redirectToMilestoneNotificationPage(final MileStoneEvent mileStoneEvent) { final PageParameters pp = new PageParameters(); pp.set(PageParameterKeys.MAP.get(Project.class), mileStoneEvent.getProject().getId()); - roleSplit(SciProSession.get().getUser(), mileStoneEvent.getProject(), ProjectMileStonePage.class, SupervisorMileStonePage.class, pp); + roleSplit( + SciProSession.get().getUser(), + mileStoneEvent.getProject(), + ProjectMileStonePage.class, + SupervisorMileStonePage.class, + pp + ); } private void redirectToGroupNotificationPage(final GroupEvent groupEvent) { @@ -280,8 +312,7 @@ public class NotificationLandingPage extends WebPage { if (group.getProjects().stream().anyMatch(project -> hasSupervisingRole(project, currentUser))) { setResponsePage(SupervisorGroupPage.class, pp); - } - else if (group.getProjects().stream().anyMatch(project -> project.isParticipant(currentUser))) { + } else if (group.getProjects().stream().anyMatch(project -> project.isParticipant(currentUser))) { setResponsePage(AuthorGroupPage.class, pp); } } @@ -300,32 +331,30 @@ public class NotificationLandingPage extends WebPage { case NEW_REVIEWER_INTERACTION: if (project.isSupervisor(currentUser)) { setResponsePage(SupervisorInteractWithReviewerPage.class, pp); - } - else if (project.isReviewer(currentUser)) { + } else if (project.isReviewer(currentUser)) { setResponsePage(ReviewerInteractionPage.class, pp); } break; default: - // no specific redirect, will default to start page + // no specific redirect, will default to start page } } private void roleSplit( - final User currentUser, - final Project project, - final Class authorPage, - final Class supervisorPage, - final PageParameters pp) - { + final User currentUser, + final Project project, + final Class authorPage, + final Class supervisorPage, + final PageParameters pp + ) { if (project.isParticipant(currentUser)) { setResponsePage(authorPage, pp); - } - else if (hasSupervisingRole(project, currentUser)) { + } else if (hasSupervisingRole(project, currentUser)) { setResponsePage(supervisorPage, pp); } } private boolean hasSupervisingRole(final Project project, final User user) { - return project.isSupervisor(user) || project.isReviewer(user) || project.isCoSupervisor(user); + return (project.isSupervisor(user) || project.isReviewer(user) || project.isCoSupervisor(user)); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationsPage.java b/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationsPage.java index 0a6020e942..36beefb74b 100755 --- a/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/pages/NotificationsPage.java @@ -9,13 +9,13 @@ public class NotificationsPage extends MenuPage { public NotificationsPage(final PageParameters pp) { super(pp); - - add(new NotificationDataPanel("notificationsPanel") { - @Override - public void unreadStateChanged(AjaxRequestTarget target) { - updateHeader(target); + add( + new NotificationDataPanel("notificationsPanel") { + @Override + public void unreadStateChanged(AjaxRequestTarget target) { + updateHeader(target); + } } - }); + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPage.java index 8331079048..af2c9523f5 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notifications.pages; +import static se.su.dsv.scipro.data.dataobjects.Member.Type.SUPERVISOR; + import org.apache.wicket.markup.html.panel.FeedbackPanel; import se.su.dsv.scipro.notifications.panels.NotificationSettingsPanel; import se.su.dsv.scipro.notifications.settings.panels.MemberDeliveryConfigurationPanel; @@ -7,10 +9,9 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.settings.pages.AbstractSettingsPage; -import static se.su.dsv.scipro.data.dataobjects.Member.Type.SUPERVISOR; - -@Authorization(authorizedRoles = {Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) public class SupervisorNotificationSettingsPage extends AbstractSettingsPage { + static final String SETTINGS_PANEL = "settingsPanel"; static final String FEEDBACK = "feedbackPanel"; diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanel.java index d5e132eb9f..7513a65046 100755 --- a/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.notifications.panels; +import jakarta.inject.Inject; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -38,23 +42,18 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.List; - public class NotificationDataPanel extends Panel { @Inject NotificationService notificationService; + @Inject ProjectService projectService; /** * No-op method. Override if you want to. */ - public void unreadStateChanged(AjaxRequestTarget target) { - } + public void unreadStateChanged(AjaxRequestTarget target) {} public NotificationDataPanel(String id) { super(id); @@ -65,18 +64,26 @@ public class NotificationDataPanel extends Panel { } private void addMarkReadLink() { - add(new AjaxConfirmationLink("markRead", "Are you sure you want to mark ALL unread notifications as read? This action can NOT be undone.") { - @Override - public void onClick(AjaxRequestTarget target) { - notificationService.markRead(SciProSession.get().getUser()); - target.add(NotificationDataPanel.this); - unreadStateChanged(target); + add( + new AjaxConfirmationLink( + "markRead", + "Are you sure you want to mark ALL unread notifications as read? This action can NOT be undone." + ) { + @Override + public void onClick(AjaxRequestTarget target) { + notificationService.markRead(SciProSession.get().getUser()); + target.add(NotificationDataPanel.this); + unreadStateChanged(target); + } } - }); + ); } private void addSettingsPageLink() { - BookmarkablePageLink settingsLink = new BookmarkablePageLink<>("settingsLink", SupervisorNotificationSettingsPage.class); + BookmarkablePageLink settingsLink = new BookmarkablePageLink<>( + "settingsLink", + SupervisorNotificationSettingsPage.class + ); add(settingsLink.setVisible(SciProSession.get().getUser().hasRole(Roles.SUPERVISOR))); } @@ -88,16 +95,20 @@ public class NotificationDataPanel extends Panel { private List> columns() { return Arrays.asList( - createColumnUnread(), - new DateColumn<>(new StringResourceModel("column.date", this, null), Notification::getDateCreated, "dateCreated", DateStyle.DATETIME), - createColumnSubject(), - createColumnFrom(), - createColumnRole(), - new ProjectColumn(new StringResourceModel("column.project", NotificationDataPanel.this, null)) + createColumnUnread(), + new DateColumn<>( + new StringResourceModel("column.date", this, null), + Notification::getDateCreated, + "dateCreated", + DateStyle.DATETIME + ), + createColumnSubject(), + createColumnFrom(), + createColumnRole(), + new ProjectColumn(new StringResourceModel("column.project", NotificationDataPanel.this, null)) ); } - private void addNotificationsPanel() { IModel filter = getFilter(); add(new FilterForm("filterForm", filter)); @@ -109,21 +120,27 @@ public class NotificationDataPanel extends Panel { private IColumn createColumnUnread() { return new AbstractColumn<>(new ResourceModel("column.unread"), "unread") { @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(new AbstractReadStatePanel(componentId) { - @Override - protected boolean isRead() { - return !rowModel.getObject().isUnread(); - } + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AbstractReadStatePanel(componentId) { + @Override + protected boolean isRead() { + return !rowModel.getObject().isUnread(); + } - @Override - protected void onFlagClick(final AjaxRequestTarget target) { - Notification notification = rowModel.getObject(); - notification.setUnread(!notification.isUnread()); - notificationService.save(notification); - unreadStateChanged(target); + @Override + protected void onFlagClick(final AjaxRequestTarget target) { + Notification notification = rowModel.getObject(); + notification.setUnread(!notification.isUnread()); + notificationService.save(notification); + unreadStateChanged(target); + } } - }); + ); } }; } @@ -131,17 +148,30 @@ public class NotificationDataPanel extends Panel { private IColumn createColumnRole() { return new AbstractColumn<>(new StringResourceModel("column.role", NotificationDataPanel.this, null)) { @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { User user = rowModel.getObject().getCausedBy(); if (user == null) { - cellItem.add(new Label(componentId, new StringResourceModel("role.SYSTEM", NotificationDataPanel.this, null))); + cellItem.add( + new Label(componentId, new StringResourceModel("role.SYSTEM", NotificationDataPanel.this, null)) + ); } else { Project project = rowModel.getObject().getProject(); Member.Type type = project != null ? projectService.getMemberType(project, user) : null; if (type == null) { - cellItem.add(new Label(componentId, new StringResourceModel("unknown", NotificationDataPanel.this, null))); + cellItem.add( + new Label(componentId, new StringResourceModel("unknown", NotificationDataPanel.this, null)) + ); } else { - cellItem.add(new Label(componentId, new StringResourceModel("role.${name()}", NotificationDataPanel.this, Model.of(type)))); + cellItem.add( + new Label( + componentId, + new StringResourceModel("role.${name()}", NotificationDataPanel.this, Model.of(type)) + ) + ); } } } @@ -151,7 +181,11 @@ public class NotificationDataPanel extends Panel { private IColumn createColumnFrom() { return new AbstractColumn<>(new StringResourceModel("column.from", NotificationDataPanel.this, null)) { @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { User user = rowModel.getObject().getCausedBy(); if (user != null) { @@ -168,16 +202,34 @@ public class NotificationDataPanel extends Panel { @Override public IModel getDataModel(IModel model) { return new StringResourceModel("${type}.${event}.title", NotificationDataPanel.this, model) - .setDefaultValue(MessageFormat.format("Missing property: {0}.{1}.title", model.getObject().getType(), model.getObject().getEvent())) - .setParameters(model.getObject().getTitle(), model.getObject().getSource(), model.getObject().getAdditionalSource()); + .setDefaultValue( + MessageFormat.format( + "Missing property: {0}.{1}.title", + model.getObject().getType(), + model.getObject().getEvent() + ) + ) + .setParameters( + model.getObject().getTitle(), + model.getObject().getSource(), + model.getObject().getAdditionalSource() + ); } @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { final PageParameters parameters = new PageParameters(); parameters.set("id", rowModel.getObject().getNotificationEvent().getId()); - final BookmarkablePageLink link = new BookmarkablePageLink<>("link", NotificationLandingPage.class, parameters); + final BookmarkablePageLink link = new BookmarkablePageLink<>( + "link", + NotificationLandingPage.class, + parameters + ); link.setBody(getDataModel(rowModel)); final Fragment fragment = new Fragment(componentId, "subject", NotificationDataPanel.this); @@ -196,21 +248,26 @@ public class NotificationDataPanel extends Panel { @Override public IModel getDataModel(final IModel rowModel) { - return rowModel - .map(Notification::getProject) - .map(Project::getTitle) - .orElseGet(() -> getString("unknown")); + return rowModel.map(Notification::getProject).map(Project::getTitle).orElseGet(() -> getString("unknown")); } @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { PageParameters pp = new PageParameters(); final Project project = rowModel.getObject().getNotificationEvent().getProject(); if (project != null) { pp.add(PageParameterKeys.MAP.get(Project.class), project.getId()); } Fragment fragment = new Fragment(componentId, "projectTitle", NotificationDataPanel.this); - BookmarkablePageLink link = new BookmarkablePageLink<>("projectLink", getProjectDetailsPageClass(project), pp) { + BookmarkablePageLink link = new BookmarkablePageLink<>( + "projectLink", + getProjectDetailsPageClass(project), + pp + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -228,7 +285,7 @@ public class NotificationDataPanel extends Panel { private boolean shallBeEnable(Project project) { if (project != null) { User user = SciProSession.get().getUser(); - return project.isParticipant(user) || project.isSupervisor(user) || project.isCoSupervisor(user); + return (project.isParticipant(user) || project.isSupervisor(user) || project.isCoSupervisor(user)); } return false; } @@ -243,9 +300,13 @@ public class NotificationDataPanel extends Panel { } private class FilterForm extends Form { + public FilterForm(String id, IModel filter) { super(id, filter); - UserAutoComplete fromUser = new UserAutoComplete("fromUser", LambdaModel.of(filter, NotificationService.Filter::getFromUser, NotificationService.Filter::setFromUser)) { + UserAutoComplete fromUser = new UserAutoComplete( + "fromUser", + LambdaModel.of(filter, NotificationService.Filter::getFromUser, NotificationService.Filter::setFromUser) + ) { @Override protected void action(final AjaxRequestTarget target, final User object) { target.add(NotificationDataPanel.this); diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanel.java index 94654e3f1e..d63e8b04cf 100755 --- a/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.notifications.panels; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.Form; @@ -12,12 +13,8 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.springdata.services.UserProfileService; -import jakarta.inject.Inject; - - public class NotificationSettingsPanel extends Panel { - static final String FORM = "form"; static final String MAIL_COMPILATION = "mailCompilation"; static final String TRUE = "compile"; @@ -33,14 +30,19 @@ public class NotificationSettingsPanel extends Panel { profile = getProfile(); Form form = new Form<>(FORM, profile); - RadioGroup group = new RadioGroup<>(MAIL_COMPILATION, LambdaModel.of(profile, UserProfile::isMailCompilation, UserProfile::setMailCompilation)); + RadioGroup group = new RadioGroup<>( + MAIL_COMPILATION, + LambdaModel.of(profile, UserProfile::isMailCompilation, UserProfile::setMailCompilation) + ); - group.add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - updateProfile(target); + group.add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + updateProfile(target); + } } - }); + ); group.add(new Radio<>(TRUE, Model.of(true)).setOutputMarkupId(true)); group.add(new Radio<>(FALSE, Model.of(false)).setOutputMarkupId(true)); diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPage.java index 8f1f20a0e1..5d9a225e06 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPage.java @@ -5,6 +5,7 @@ import se.su.dsv.scipro.notifications.settings.panels.DeliveryConfigurationPanel import se.su.dsv.scipro.notifications.settings.panels.ReceiverConfigurationPanel; public class AdminNotificationSettingsPage extends AbstractAdminSystemPage { + public AdminNotificationSettingsPage() { add(new ReceiverConfigurationPanel("receiver")); add(new DeliveryConfigurationPanel("general")); diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanel.java index f53c221a00..1c13f0691b 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.notifications.settings.panels; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -18,10 +21,6 @@ import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationService; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public abstract class AbstractReceiverConfigurationPanel extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractReceiverConfigurationPanel.class); @@ -34,7 +33,8 @@ public abstract class AbstractReceiverConfigurationPanel extends Panel { static final String MEMBER = "member"; static final String DESCRIPTION = "description"; - @Inject ReceiverConfigurationService configurationService; + @Inject + ReceiverConfigurationService configurationService; private final Notification.Type group; @@ -42,7 +42,6 @@ public abstract class AbstractReceiverConfigurationPanel extends Panel { public AbstractReceiverConfigurationPanel(final String id, final Notification.Type group, final Enum[] events) { super(id); - this.group = group; this.events = Arrays.asList(events); } @@ -62,21 +61,34 @@ public abstract class AbstractReceiverConfigurationPanel extends Panel { protected void onInitialize() { super.onInitialize(); - add(new ListView<>(MEMBER_LIST, getMemberTypes()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(MEMBER, new StringResourceModel("${name()}", this, item.getModel()))); + add( + new ListView<>(MEMBER_LIST, getMemberTypes()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label(MEMBER, new StringResourceModel("${name()}", this, item.getModel()))); + } } - }); + ); - add(new ListView<>(EVENT_LIST, events) { - @Override - protected void populateItem(final ListItem eventItem) { - eventItem.add(new Label(EVENT, eventItem.getModelObject().name())); - eventItem.add(new Label(DESCRIPTION, getString(eventItem.getModelObject().getClass().getEnclosingClass().getSimpleName() + "." + eventItem.getModelObject().name()))); - eventItem.add(new ConfigurationList(CONFIGURATIONS, getMemberTypes(), eventItem.getModelObject())); + add( + new ListView<>(EVENT_LIST, events) { + @Override + protected void populateItem(final ListItem eventItem) { + eventItem.add(new Label(EVENT, eventItem.getModelObject().name())); + eventItem.add( + new Label( + DESCRIPTION, + getString( + eventItem.getModelObject().getClass().getEnclosingClass().getSimpleName() + + "." + + eventItem.getModelObject().name() + ) + ) + ); + eventItem.add(new ConfigurationList(CONFIGURATIONS, getMemberTypes(), eventItem.getModelObject())); + } } - }); + ); } class ConfigurationList extends ListView { @@ -85,7 +97,6 @@ public abstract class AbstractReceiverConfigurationPanel extends Panel { public ConfigurationList(String id, List model, Enum event) { super(id, model); - this.event = event; } @@ -95,23 +106,22 @@ public abstract class AbstractReceiverConfigurationPanel extends Panel { item.add(new ReceiverSettingCheckbox(CONFIGURATION, Model.of(setting), event, item.getModelObject())); } - - } public class ReceiverSettingCheckbox extends AjaxCheckBox { + private final Enum event; private final Member.Type member; public ReceiverSettingCheckbox(String id, IModel model, Enum event, Member.Type member) { super(id, model); - this.event = event; this.member = member; setOutputMarkupId(true); } + @Override protected void onUpdate(AjaxRequestTarget target) { boolean newSetting = updateSetting(event, member, getModelObject()); diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanel.java index bdfd413487..ef259e3de2 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanel.java @@ -22,7 +22,11 @@ public class DeliveryConfigurationPanel extends Panel { add(createDeliveryPanel(GROUP_EVENTS, Notification.Type.GROUP, GroupEvent.Event.values())); } - protected TypeDeliveryConfigurationPanel createDeliveryPanel(final String id, final Notification.Type type, final Enum[] events) { + protected TypeDeliveryConfigurationPanel createDeliveryPanel( + final String id, + final Notification.Type type, + final Enum[] events + ) { return new TypeDeliveryConfigurationPanel(id, type, events); } diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanel.java index c7e47d6f74..368fe8dd9a 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notifications.settings.panels; +import jakarta.inject.Inject; +import java.util.Optional; import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.settings.entities.DeliveryMethod; @@ -7,9 +9,6 @@ import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationServ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Optional; - public class MemberDeliveryConfigurationPanel extends DeliveryConfigurationPanel { @Inject @@ -19,12 +18,15 @@ public class MemberDeliveryConfigurationPanel extends DeliveryConfigurationPanel public MemberDeliveryConfigurationPanel(final String id, final Member.Type member) { super(id); - this.member = member; } @Override - protected TypeDeliveryConfigurationPanel createDeliveryPanel(final String id, final Notification.Type type, final Enum[] events) { + protected TypeDeliveryConfigurationPanel createDeliveryPanel( + final String id, + final Notification.Type type, + final Enum[] events + ) { return new TypeDeliveryConfigurationPanel(id, type, events) { @Override protected boolean isMethodEnabled(final DeliveryMethod method) { diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/ReceiverConfigurationPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/ReceiverConfigurationPanel.java index 348943b5a3..8815b9f79a 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/ReceiverConfigurationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/ReceiverConfigurationPanel.java @@ -1,60 +1,116 @@ package se.su.dsv.scipro.notifications.settings.panels; -import org.apache.wicket.markup.html.panel.Panel; -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.notifications.dataobject.*; - import java.util.Arrays; import java.util.Collections; import java.util.List; +import org.apache.wicket.markup.html.panel.Panel; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.notifications.dataobject.*; public class ReceiverConfigurationPanel extends Panel { public ReceiverConfigurationPanel(String id) { super(id); - - add(new AbstractReceiverConfigurationPanel(PROJECT_RECEIVERS, Notification.Type.PROJECT, ProjectEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.SUPERVISOR, Member.Type.CO_SUPERVISOR, Member.Type.REVIEWER, Member.Type.AUTHOR); + add( + new AbstractReceiverConfigurationPanel( + PROJECT_RECEIVERS, + Notification.Type.PROJECT, + ProjectEvent.Event.values() + ) { + @Override + protected List getMemberTypes() { + return Arrays.asList( + Member.Type.SUPERVISOR, + Member.Type.CO_SUPERVISOR, + Member.Type.REVIEWER, + Member.Type.AUTHOR + ); + } } - }); - add(new AbstractReceiverConfigurationPanel(FORUM_RECEIVERS, Notification.Type.FORUM, ProjectForumEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.SUPERVISOR, Member.Type.CO_SUPERVISOR, Member.Type.REVIEWER, Member.Type.AUTHOR); + ); + add( + new AbstractReceiverConfigurationPanel( + FORUM_RECEIVERS, + Notification.Type.FORUM, + ProjectForumEvent.Event.values() + ) { + @Override + protected List getMemberTypes() { + return Arrays.asList( + Member.Type.SUPERVISOR, + Member.Type.CO_SUPERVISOR, + Member.Type.REVIEWER, + Member.Type.AUTHOR + ); + } } - }); - add(new AbstractReceiverConfigurationPanel(SEMINAR_RECEIVERS, Notification.Type.FINAL_SEMINAR, SeminarEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.SUPERVISOR, Member.Type.CO_SUPERVISOR, Member.Type.REVIEWER, Member.Type.AUTHOR, Member.Type.OPPONENT, Member.Type.ACTIVE_PARTICIPANT); + ); + add( + new AbstractReceiverConfigurationPanel( + SEMINAR_RECEIVERS, + Notification.Type.FINAL_SEMINAR, + SeminarEvent.Event.values() + ) { + @Override + protected List getMemberTypes() { + return Arrays.asList( + Member.Type.SUPERVISOR, + Member.Type.CO_SUPERVISOR, + Member.Type.REVIEWER, + Member.Type.AUTHOR, + Member.Type.OPPONENT, + Member.Type.ACTIVE_PARTICIPANT + ); + } } - }); - add(new AbstractReceiverConfigurationPanel(IDEA_RECEIVERS, Notification.Type.IDEA, IdeaEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.CREATOR, Member.Type.CO_AUTHOR, Member.Type.SUPERVISOR); + ); + add( + new AbstractReceiverConfigurationPanel(IDEA_RECEIVERS, Notification.Type.IDEA, IdeaEvent.Event.values()) { + @Override + protected List getMemberTypes() { + return Arrays.asList(Member.Type.CREATOR, Member.Type.CO_AUTHOR, Member.Type.SUPERVISOR); + } } - }); - add(new AbstractReceiverConfigurationPanel(PEER_RECEIVERS, Notification.Type.PEER, PeerEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.AUTHOR, Member.Type.SUPERVISOR, Member.Type.REVIEWER, Member.Type.CO_SUPERVISOR, Member.Type.PEER_REQUESTER, Member.Type.PEER_REVIEWER); + ); + add( + new AbstractReceiverConfigurationPanel(PEER_RECEIVERS, Notification.Type.PEER, PeerEvent.Event.values()) { + @Override + protected List getMemberTypes() { + return Arrays.asList( + Member.Type.AUTHOR, + Member.Type.SUPERVISOR, + Member.Type.REVIEWER, + Member.Type.CO_SUPERVISOR, + Member.Type.PEER_REQUESTER, + Member.Type.PEER_REVIEWER + ); + } } - }); - add(new AbstractReceiverConfigurationPanel(MILESTONE_RECEIVERS, Notification.Type.MILESTONE, MileStoneEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Collections.singletonList(Member.Type.MILESTONE_INDIVIDUAL); + ); + add( + new AbstractReceiverConfigurationPanel( + MILESTONE_RECEIVERS, + Notification.Type.MILESTONE, + MileStoneEvent.Event.values() + ) { + @Override + protected List getMemberTypes() { + return Collections.singletonList(Member.Type.MILESTONE_INDIVIDUAL); + } } - }); - add(new AbstractReceiverConfigurationPanel(GROUP_RECEIVERS, Notification.Type.GROUP, GroupEvent.Event.values()) { - @Override - protected List getMemberTypes() { - return Arrays.asList(Member.Type.SUPERVISOR, Member.Type.CO_SUPERVISOR, Member.Type.AUTHOR); + ); + add( + new AbstractReceiverConfigurationPanel( + GROUP_RECEIVERS, + Notification.Type.GROUP, + GroupEvent.Event.values() + ) { + @Override + protected List getMemberTypes() { + return Arrays.asList(Member.Type.SUPERVISOR, Member.Type.CO_SUPERVISOR, Member.Type.AUTHOR); + } } - }); + ); } static final String PROJECT_RECEIVERS = "projectReceivers"; @@ -64,5 +120,4 @@ public class ReceiverConfigurationPanel extends Panel { static final String PEER_RECEIVERS = "peerReceivers"; static final String MILESTONE_RECEIVERS = "mileStoneReceivers"; static final String GROUP_RECEIVERS = "groupReceivers"; - -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanel.java b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanel.java index 40209d1010..ef4ba46141 100644 --- a/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.notifications.settings.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -19,12 +24,6 @@ import se.su.dsv.scipro.notifications.settings.service.DeliveryConfigurationServ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - public class TypeDeliveryConfigurationPanel extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(TypeDeliveryConfigurationPanel.class); @@ -44,10 +43,8 @@ public class TypeDeliveryConfigurationPanel extends Panel { public TypeDeliveryConfigurationPanel(final String id, final Notification.Type type, final Enum[] events) { super(id); - this.type = type; this.eventValues = events.clone(); - } @Override @@ -56,21 +53,39 @@ public class TypeDeliveryConfigurationPanel extends Panel { events = filterEvents(eventValues); - add(new ListView<>(METHODS, deliveryMethods()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label(METHOD, new StringResourceModel("${name()}", TypeDeliveryConfigurationPanel.this, item.getModel()))); + add( + new ListView<>(METHODS, deliveryMethods()) { + @Override + protected void populateItem(ListItem item) { + item.add( + new Label( + METHOD, + new StringResourceModel("${name()}", TypeDeliveryConfigurationPanel.this, item.getModel()) + ) + ); + } } - }); + ); - add(new ListView<>(EVENTS, events) { - @Override - protected void populateItem(ListItem> item) { - item.add(new Label(EVENT, Model.of(item.getModelObject().name()))); - item.add(new Label(DESCRIPTION, getString(item.getModelObject().getClass().getEnclosingClass().getSimpleName() + "." + item.getModelObject().name()))); - item.add(new EventRow(METHODS, item.getModelObject())); + add( + new ListView<>(EVENTS, events) { + @Override + protected void populateItem(ListItem> item) { + item.add(new Label(EVENT, Model.of(item.getModelObject().name()))); + item.add( + new Label( + DESCRIPTION, + getString( + item.getModelObject().getClass().getEnclosingClass().getSimpleName() + + "." + + item.getModelObject().name() + ) + ) + ); + item.add(new EventRow(METHODS, item.getModelObject())); + } } - }); + ); } @Override @@ -124,18 +139,18 @@ public class TypeDeliveryConfigurationPanel extends Panel { EventRow(String id, final Enum event) { super(id, deliveryMethods()); - this.event = event; } + @Override protected void populateItem(final ListItem item) { boolean enabled = getDeliverySetting(event, item.getModelObject()); item.add(new MethodCheckbox(METHOD, Model.of(enabled), event, item.getModelObject())); } - } private final class MethodCheckbox extends AjaxCheckBox { + private final Enum event; private final DeliveryMethod method; @@ -150,6 +165,7 @@ public class TypeDeliveryConfigurationPanel extends Panel { protected void onUpdate(AjaxRequestTarget target) { setDeliverySetting(event, method, getModelObject()); } + @Override protected void onConfigure() { super.onConfigure(); diff --git a/view/src/main/java/se/su/dsv/scipro/oauth/CallbackPage.java b/view/src/main/java/se/su/dsv/scipro/oauth/CallbackPage.java index 823491477d..4781b7ce2b 100644 --- a/view/src/main/java/se/su/dsv/scipro/oauth/CallbackPage.java +++ b/view/src/main/java/se/su/dsv/scipro/oauth/CallbackPage.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.oauth; -import org.apache.wicket.markup.html.WebPage; -import org.apache.wicket.request.flow.RedirectToUrlException; -import org.apache.wicket.request.mapper.parameter.PageParameters; - import jakarta.inject.Inject; import java.time.Instant; import java.util.Objects; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.request.flow.RedirectToUrlException; +import org.apache.wicket.request.mapper.parameter.PageParameters; public class CallbackPage extends WebPage { + @Inject private OAuthService oAuthService; @@ -25,17 +25,14 @@ public class CallbackPage extends WebPage { getSession().setMetaData(OAuth.EXPIRATION, Instant.now().plusSeconds(tokenResponse.expiresIn())); if (returnUrl != null) { throw new RedirectToUrlException(returnUrl); - } - else { + } else { setResponsePage(getApplication().getHomePage()); } - } - else { + } else { getSession().error("Authorization failed"); setResponsePage(getApplication().getHomePage()); } - } - else { + } else { getSession().error("Authorization failed"); setResponsePage(getApplication().getHomePage()); } diff --git a/view/src/main/java/se/su/dsv/scipro/oauth/OAuth.java b/view/src/main/java/se/su/dsv/scipro/oauth/OAuth.java index fff5ad027f..a17c6c623d 100644 --- a/view/src/main/java/se/su/dsv/scipro/oauth/OAuth.java +++ b/view/src/main/java/se/su/dsv/scipro/oauth/OAuth.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.oauth; -import org.apache.wicket.MetaDataKey; - import java.time.Instant; +import org.apache.wicket.MetaDataKey; public final class OAuth { @@ -10,12 +9,8 @@ public final class OAuth { throw new UnsupportedOperationException(); } - public static final MetaDataKey STATE = new MetaDataKey<>() { - }; - public static final MetaDataKey RETURN_URL = new MetaDataKey<>() { - }; - public static final MetaDataKey TOKEN = new MetaDataKey<>() { - }; - public static final MetaDataKey EXPIRATION = new MetaDataKey<>() { - }; + public static final MetaDataKey STATE = new MetaDataKey<>() {}; + public static final MetaDataKey RETURN_URL = new MetaDataKey<>() {}; + public static final MetaDataKey TOKEN = new MetaDataKey<>() {}; + public static final MetaDataKey EXPIRATION = new MetaDataKey<>() {}; } diff --git a/view/src/main/java/se/su/dsv/scipro/panels/CommentThreadPanel.java b/view/src/main/java/se/su/dsv/scipro/panels/CommentThreadPanel.java index 9c7a10dd5f..e33e58686c 100755 --- a/view/src/main/java/se/su/dsv/scipro/panels/CommentThreadPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/panels/CommentThreadPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.panels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; @@ -21,9 +23,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.List; - public class CommentThreadPanel extends GenericPanel { public static final String COMMENTS = "comments"; @@ -38,6 +37,7 @@ public class CommentThreadPanel extends GenericPanel { @Inject private CommentThreadService commentThreadService; + @Inject private CommentService commentService; @@ -45,20 +45,21 @@ public class CommentThreadPanel extends GenericPanel { public CommentThreadPanel(String id, IModel peerReviewIModel) { super(id, peerReviewIModel); - commentThread = commentThreadService.getCommentThread(peerReviewIModel.getObject()); comments = findComments(); - add(new ListView<>(COMMENTS, comments) { - @Override - protected void populateItem(ListItem item) { - final IModel comment = item.getModel(); - item.add(new DateLabel(DATE, comment.map(Comment::getDateCreated), DateStyle.DATETIME)); - item.add(new UserLinkPanel(FROM, comment.map(Comment::getCreator))); - item.add(new MultiLineLabel(MESSAGE, comment.map(Comment::getComment))); - item.add(new DeleteLink(DELETE_LINK, item.getModel())); + add( + new ListView<>(COMMENTS, comments) { + @Override + protected void populateItem(ListItem item) { + final IModel comment = item.getModel(); + item.add(new DateLabel(DATE, comment.map(Comment::getDateCreated), DateStyle.DATETIME)); + item.add(new UserLinkPanel(FROM, comment.map(Comment::getCreator))); + item.add(new MultiLineLabel(MESSAGE, comment.map(Comment::getComment))); + item.add(new DeleteLink(DELETE_LINK, item.getModel())); + } } - }); + ); CommentForm commentForm = new CommentForm(COMMENT_FORM, findComment()); add(commentForm); @@ -68,7 +69,11 @@ public class CommentThreadPanel extends GenericPanel { @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnDomReadyHeaderItem.forScript("var sneaky = new ScrollSneak(location.hostname); $('.scrollSneak').click(sneaky.sneak);")); + response.render( + OnDomReadyHeaderItem.forScript( + "var sneaky = new ScrollSneak(location.hostname); $('.scrollSneak').click(sneaky.sneak);" + ) + ); } @Override @@ -104,12 +109,16 @@ public class CommentThreadPanel extends GenericPanel { public CommentForm(String id, IModel commentIModel) { super(id, commentIModel); - final TextArea comment = new TextArea<>(COMMENT_TEXT_AREA, LambdaModel.of(commentIModel, Comment::getComment, Comment::setComment)); + final TextArea comment = new TextArea<>( + COMMENT_TEXT_AREA, + LambdaModel.of(commentIModel, Comment::getComment, Comment::setComment) + ); add(comment.setRequired(true)); } } private class DeleteLink extends Link { + public DeleteLink(String id, IModel commentIModel) { super(id, commentIModel); add(new JavascriptEventConfirmation("click", new ResourceModel("delete.confirmation"))); @@ -127,5 +136,4 @@ public class CommentThreadPanel extends GenericPanel { setVisibilityAllowed(getModelObject().getCreator().equals(SciProSession.get().getUser())); } } - } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/AbstractPeerPortalPage.java b/view/src/main/java/se/su/dsv/scipro/peer/AbstractPeerPortalPage.java index 1ca1a65b25..be2df00b0d 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/AbstractPeerPortalPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/AbstractPeerPortalPage.java @@ -1,16 +1,17 @@ package se.su.dsv.scipro.peer; +import static se.su.dsv.scipro.security.auth.roles.Roles.AUTHOR; + import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.project.pages.AbstractProjectDetailsPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.system.ProjectModule; -import static se.su.dsv.scipro.security.auth.roles.Roles.AUTHOR; - -@Authorization(authorizedRoles = {AUTHOR}) +@Authorization(authorizedRoles = { AUTHOR }) @ProjectModuleComponent(ProjectModule.PEER) public class AbstractPeerPortalPage extends AbstractProjectDetailsPage { + public static final String PEER_REVIEW_GUIDE_PANEL = "peerReviewGuidePanel"; public static final String MY_REQUEST_AND_REVIEWS_PANEL = "myRequestAndReviewsPanel"; public static final String LATEST_REVIEW_PANEL = "latestReviewPanel"; diff --git a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewPage.java b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewPage.java index c1c5683a66..683a33a6c5 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -9,8 +10,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.statistics.AbstractAdminStatisticsPage; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class AdminPeerReviewPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminPeer { @Inject @@ -20,8 +19,14 @@ public class AdminPeerReviewPage extends AbstractAdminStatisticsPage implements long reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); IModel reviewModel = new DetachableServiceModel<>(peerReviewService, reviewId); add(new DisplayReviewPanel("review", reviewModel)); - add(new ReviewPageRequestDetailsPanel("request", LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest))); - add(new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer))); + add( + new ReviewPageRequestDetailsPanel( + "request", + LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest) + ) + ); + add( + new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer)) + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewStatusStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewStatusStatisticsPage.java index 9b7f723821..33a4ec562a 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewStatusStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerReviewStatusStatisticsPage.java @@ -5,7 +5,7 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.statistics.AbstractAdminStatisticsPage; -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminPeerReviewStatusStatisticsPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminPeer { public static final boolean IS_SUPERVISOR_VIEW = false; diff --git a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerSettingsPage.java index 2adb9c0302..f69280f767 100755 --- a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeerSettingsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.CheckBox; @@ -18,37 +20,37 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.ProjectTypeSettings; -import jakarta.inject.Inject; -import java.util.List; - public class AdminPeerSettingsPage extends AbstractAdminSystemPage { @Inject private ProjectTypeService projectTypeService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; public AdminPeerSettingsPage() { final Form peerSettingsForm = new Form<>("peerSettingsForm") { - @Override public void onSubmit() { info(getString("saved")); } }; - peerSettingsForm.add(new ListView<>("projectTypeList", getProjectTypes()) { - - @Override - protected void populateItem(ListItem item) { - item.add(new Label("projectTypeName", item.getModelObject().getName())); - item.add(new PeerProjectTypeSettingsForm("projectTypeSettingsForm", item.getModel())); - add(item); + peerSettingsForm.add( + new ListView<>("projectTypeList", getProjectTypes()) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("projectTypeName", item.getModelObject().getName())); + item.add(new PeerProjectTypeSettingsForm("projectTypeSettingsForm", item.getModel())); + add(item); + } } + ); - }); - - PeerRatingsSettingsForm peerRatingsSettingsForm = new PeerRatingsSettingsForm("peerRatingsSettingsForm", getSettingsModel()); + PeerRatingsSettingsForm peerRatingsSettingsForm = new PeerRatingsSettingsForm( + "peerRatingsSettingsForm", + getSettingsModel() + ); peerSettingsForm.add(peerRatingsSettingsForm); peerSettingsForm.add(new Button("submit")); @@ -72,33 +74,47 @@ public class AdminPeerSettingsPage extends AbstractAdminSystemPage { public PeerRatingsSettingsForm(String id, IModel model) { super(id, model); - - CheckBox peerDisplayLatestReviews = new CheckBox("peerDisplayLatestReviews", - LambdaModel.of(model, - GeneralSystemSettings::isPeerDisplayLatestReviews, - GeneralSystemSettings::setPeerDisplayLatestReviews)); + CheckBox peerDisplayLatestReviews = new CheckBox( + "peerDisplayLatestReviews", + LambdaModel.of( + model, + GeneralSystemSettings::isPeerDisplayLatestReviews, + GeneralSystemSettings::setPeerDisplayLatestReviews + ) + ); peerDisplayLatestReviews.setOutputMarkupId(true); add(peerDisplayLatestReviews); - TextField numberOfLatestReviewsDisplayed = - new TextField<>("numberOfLatestReviewsDisplayed", - LambdaModel.of(model, - GeneralSystemSettings::getNumberOfLatestReviewsDisplayed, - GeneralSystemSettings::setNumberOfLatestReviewsDisplayed), - Integer.class); + TextField numberOfLatestReviewsDisplayed = new TextField<>( + "numberOfLatestReviewsDisplayed", + LambdaModel.of( + model, + GeneralSystemSettings::getNumberOfLatestReviewsDisplayed, + GeneralSystemSettings::setNumberOfLatestReviewsDisplayed + ), + Integer.class + ); numberOfLatestReviewsDisplayed.setRequired(true); add(numberOfLatestReviewsDisplayed); - CheckBox publicReviewsActivated = new CheckBox("publicReviewsActivated", - LambdaModel.of(model, - GeneralSystemSettings::isPublicReviewsActivated, - GeneralSystemSettings::setPublicReviewsActivated)); + CheckBox publicReviewsActivated = new CheckBox( + "publicReviewsActivated", + LambdaModel.of( + model, + GeneralSystemSettings::isPublicReviewsActivated, + GeneralSystemSettings::setPublicReviewsActivated + ) + ); publicReviewsActivated.setOutputMarkupId(true); add(publicReviewsActivated); - CheckBox peerDownloadEnabled = new CheckBox("peerDownloadEnabled", - LambdaModel.of(model, - GeneralSystemSettings::isPeerDownloadEnabled, - GeneralSystemSettings::setPeerDownloadEnabled)); + CheckBox peerDownloadEnabled = new CheckBox( + "peerDownloadEnabled", + LambdaModel.of( + model, + GeneralSystemSettings::isPeerDownloadEnabled, + GeneralSystemSettings::setPeerDownloadEnabled + ) + ); peerDownloadEnabled.setOutputMarkupId(true); add(peerDownloadEnabled); } @@ -106,7 +122,9 @@ public class AdminPeerSettingsPage extends AbstractAdminSystemPage { @Override public void onSubmit() { if (getModelObject().getNumberOfLatestReviewsDisplayed() == 0) { - warn("Number of reviews to show has been changed to 1. If you don't want to show any reviews, please hide the panel."); + warn( + "Number of reviews to show has been changed to 1. If you don't want to show any reviews, please hide the panel." + ); getModelObject().setNumberOfLatestReviewsDisplayed(1); } generalSystemSettingsService.save(getModelObject()); @@ -117,31 +135,41 @@ public class AdminPeerSettingsPage extends AbstractAdminSystemPage { public PeerProjectTypeSettingsForm(final String id, IModel projectType) { super(id, projectType); - IModel projectTypeSettings = projectType.map(ProjectType::getProjectTypeSettings); - TextField numDaysBetweenPeerReviewsOnSameProject = - new TextField<>("numDaysBetweenPeerReviewsOnSameProject", - LambdaModel.of(projectTypeSettings, - ProjectTypeSettings::getNumDaysBetweenPeerReviewsOnSameProject, - ProjectTypeSettings::setNumDaysBetweenPeerReviewsOnSameProject), - Integer.class); + TextField numDaysBetweenPeerReviewsOnSameProject = new TextField<>( + "numDaysBetweenPeerReviewsOnSameProject", + LambdaModel.of( + projectTypeSettings, + ProjectTypeSettings::getNumDaysBetweenPeerReviewsOnSameProject, + ProjectTypeSettings::setNumDaysBetweenPeerReviewsOnSameProject + ), + Integer.class + ); numDaysBetweenPeerReviewsOnSameProject.setRequired(true); add(numDaysBetweenPeerReviewsOnSameProject); - TextField numDaysToSubmitPeerReview = new TextField<>("numDaysToSubmitPeerReview", - LambdaModel.of(projectTypeSettings, - ProjectTypeSettings::getNumDaysToSubmitPeerReview, - ProjectTypeSettings::setNumDaysToSubmitPeerReview), - Integer.class); + TextField numDaysToSubmitPeerReview = new TextField<>( + "numDaysToSubmitPeerReview", + LambdaModel.of( + projectTypeSettings, + ProjectTypeSettings::getNumDaysToSubmitPeerReview, + ProjectTypeSettings::setNumDaysToSubmitPeerReview + ), + Integer.class + ); numDaysToSubmitPeerReview.setRequired(true); add(numDaysToSubmitPeerReview); - TextField numDaysBeforePeerGetsCancelled = new TextField<>("numDaysBeforePeerGetsCancelled", - LambdaModel.of(projectTypeSettings, - ProjectTypeSettings::getNumDaysBeforePeerGetsCancelled, - ProjectTypeSettings::setNumDaysBeforePeerGetsCancelled), - Integer.class); + TextField numDaysBeforePeerGetsCancelled = new TextField<>( + "numDaysBeforePeerGetsCancelled", + LambdaModel.of( + projectTypeSettings, + ProjectTypeSettings::getNumDaysBeforePeerGetsCancelled, + ProjectTypeSettings::setNumDaysBeforePeerGetsCancelled + ), + Integer.class + ); numDaysBeforePeerGetsCancelled.setRequired(true); add(numDaysBeforePeerGetsCancelled); } @@ -151,5 +179,4 @@ public class AdminPeerSettingsPage extends AbstractAdminSystemPage { projectTypeService.save(getModelObject()); } } - } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeersPage.java b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeersPage.java index 970d7163ee..8c0663d99f 100755 --- a/view/src/main/java/se/su/dsv/scipro/peer/AdminPeersPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/AdminPeersPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.peer; +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import se.su.dsv.scipro.admin.panels.PeerRequestStatsPanel; @@ -7,20 +8,23 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.statistics.AbstractAdminStatisticsPage; -import java.util.Collections; - @Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminPeersPage extends AbstractAdminStatisticsPage { public AdminPeersPage() { - add(new PeerReviewStatisticsPanel("peerReviewList", new PeerReviewStatisticsPanel.PageSupplier() { - @Override - public Page statusPage(IModel model, PeerReviewService.Filter filter) { - filter.setStatuses(Collections.singletonList(model.getObject())); - return new AdminPeerReviewStatusStatisticsPage(filter); - } - })); + add( + new PeerReviewStatisticsPanel( + "peerReviewList", + new PeerReviewStatisticsPanel.PageSupplier() { + @Override + public Page statusPage(IModel model, PeerReviewService.Filter filter) { + filter.setStatuses(Collections.singletonList(model.getObject())); + return new AdminPeerReviewStatusStatisticsPage(filter); + } + } + ) + ); add(new PeerRequestStatsPanel("peerRequestStats")); add(new PeerRequestListPanel("peerRequestList")); - } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/DisplayQuestionPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/DisplayQuestionPanel.java index 7679a75eba..67c274e6e7 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/DisplayQuestionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/DisplayQuestionPanel.java @@ -21,13 +21,15 @@ public class DisplayQuestionPanel extends GenericPanel { private void addMotivation() { final IModel motivation = getModel().map(Answer::getMotivation); add(new MultiLineLabel("motivation", motivation)); - add(new Label("noMotivation", new ResourceModel("no.motivation")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(motivation.getObject() == null); + add( + new Label("noMotivation", new ResourceModel("no.motivation")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(motivation.getObject() == null); + } } - }); + ); } private String getImagePath() { diff --git a/view/src/main/java/se/su/dsv/scipro/peer/DisplayReviewPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/DisplayReviewPanel.java index eae34e27f0..6581fd299a 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/DisplayReviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/DisplayReviewPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.peer; +import java.util.List; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.MultiLineLabel; @@ -11,28 +12,25 @@ import org.apache.wicket.model.LambdaModel; import se.su.dsv.scipro.file.FileReference; import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; -import java.util.List; - public class DisplayReviewPanel extends GenericPanel { private final IModel> answersModel; public DisplayReviewPanel(String id, IModel reviewModel) { super(id, reviewModel); - answersModel = LambdaModel.of(reviewModel, PeerReview::getAnswers, PeerReview::setAnswers); add(new FencedFeedbackPanel("feedback", this)); - add(new WebMarkupContainer("questionsHeading") { - - @Override - public boolean isVisible() { - return !answersModel.getObject().isEmpty(); + add( + new WebMarkupContainer("questionsHeading") { + @Override + public boolean isVisible() { + return !answersModel.getObject().isEmpty(); + } } - }); + ); ListView questionList = new ListView<>("questions", answersModel) { - @Override protected void populateItem(ListItem item) { int index = item.getIndex(); @@ -44,20 +42,24 @@ public class DisplayReviewPanel extends GenericPanel { }; add(questionList); - add(new WebMarkupContainer("commentsHeading") { - - @Override - public boolean isVisible() { - return getModelObject().getComment() != null; + add( + new WebMarkupContainer("commentsHeading") { + @Override + public boolean isVisible() { + return getModelObject().getComment() != null; + } } - }); + ); - final MultiLineLabel reviewComment = new MultiLineLabel("reviewComment", LambdaModel.of(reviewModel, PeerReview::getComment, PeerReview::setComment)); + final MultiLineLabel reviewComment = new MultiLineLabel( + "reviewComment", + LambdaModel.of(reviewModel, PeerReview::getComment, PeerReview::setComment) + ); add(reviewComment); - add(new ViewAttachmentPanel("file", reviewModel.map(PeerReview::getFile).map(FileReference::getFileDescription))); - - + add( + new ViewAttachmentPanel("file", reviewModel.map(PeerReview::getFile).map(FileReference::getFileDescription)) + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/peer/LatestReviewPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/LatestReviewPanel.java index c8611fc665..ed96466d52 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/LatestReviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/LatestReviewPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -8,25 +10,24 @@ import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.components.DateLabel; import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class LatestReviewPanel extends Panel { public static final String NO_REVIEWERS = "noReviewers"; public static final String LIST_VIEW = "listView"; public static final String REVIEW_LINK = "reviewLink"; + @Inject - private PeerReviewService peerReviewService; + private PeerReviewService peerReviewService; + @Inject private GeneralSystemSettingsService settingsService; @@ -39,43 +40,62 @@ public class LatestReviewPanel extends Panel { } public LatestReviewPanel(String id) { - super(id); - setOutputMarkupId(true); + super(id); + setOutputMarkupId(true); settings = settingsService.getGeneralSystemSettingsInstance(); - add(new ListView<>(LIST_VIEW, getReviews()) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("reviewer", item.getModel().map(PeerReview::getReviewer).map(User::getFullName))); - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(PeerReview.class), item.getModelObject().getId()); - BookmarkablePageLink link = new BookmarkablePageLink<>(REVIEW_LINK, ViewPeerReviewPage.class, pp); - link.add(new DateLabel("reviewDate", item.getModel().map(PeerReview::getLastModified), DateStyle.DATETIME)); - link.setEnabled(settings.isPublicReviewsActivated()); - item.add(link); - add(item); + add( + new ListView<>(LIST_VIEW, getReviews()) { + @Override + protected void populateItem(ListItem item) { + item.add( + new Label("reviewer", item.getModel().map(PeerReview::getReviewer).map(User::getFullName)) + ); + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(PeerReview.class), item.getModelObject().getId()); + BookmarkablePageLink link = new BookmarkablePageLink<>( + REVIEW_LINK, + ViewPeerReviewPage.class, + pp + ); + link.add( + new DateLabel( + "reviewDate", + item.getModel().map(PeerReview::getLastModified), + DateStyle.DATETIME + ) + ); + link.setEnabled(settings.isPublicReviewsActivated()); + item.add(link); + add(item); + } } - }); + ); - add(new Label(NO_REVIEWERS, new ResourceModel("noReviewers")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getReviews().getObject().isEmpty()); + add( + new Label(NO_REVIEWERS, new ResourceModel("noReviewers")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getReviews().getObject().isEmpty()); + } } - }); - - } + ); + } private LoadableDetachableModel> getReviews() { return new LoadableDetachableModel<>() { - @Override protected List load() { - return peerReviewService.findAllCompleted(new PageRequest(0, settings.getNumberOfLatestReviewsDisplayed(), new Sort(Sort.Direction.DESC, "lastModified"))); + return peerReviewService.findAllCompleted( + new PageRequest( + 0, + settings.getNumberOfLatestReviewsDisplayed(), + new Sort(Sort.Direction.DESC, "lastModified") + ) + ); } }; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/MyPeerPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/MyPeerPanel.java index 7f72729491..109353d3b7 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/MyPeerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/MyPeerPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.Label; @@ -19,9 +21,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.JavascriptEventConfirmation; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - public class MyPeerPanel extends GenericPanel { public static final String REQUEST_LIST = "requestList"; @@ -39,6 +38,7 @@ public class MyPeerPanel extends GenericPanel { @Inject private PeerRequestService peerRequestService; + @Inject private PeerReviewService peerReviewService; @@ -49,24 +49,50 @@ public class MyPeerPanel extends GenericPanel { } private void addReviewsListView() { - add(new ListView<>(REVIEW_LIST, getPeerReviews()) { - @Override - protected void populateItem(ListItem item) { - item.add(new DateLabel(REVIEW_DATE, LambdaModel.of(item.getModel(), PeerReview::getDateCreated, PeerReview::setDateCreated))); - BookmarkablePageLink link = new BookmarkablePageLink<>(REVIEW_LINK, getReviewPage(item.getModelObject()), - getReviewParameters(item.getModelObject())); - link.add(new Label(PROJECT_TITLE, item.getModel().map(PeerReview::getPeerRequest).map(PeerRequest::getProject).map(Project::getTitle))); - item.add(link); - item.add(new EnumLabel<>(REVIEW_STATUS, LambdaModel.of(item.getModel(), PeerReview::getStatus, PeerReview::setStatus))); + add( + new ListView<>(REVIEW_LIST, getPeerReviews()) { + @Override + protected void populateItem(ListItem item) { + item.add( + new DateLabel( + REVIEW_DATE, + LambdaModel.of(item.getModel(), PeerReview::getDateCreated, PeerReview::setDateCreated) + ) + ); + BookmarkablePageLink link = new BookmarkablePageLink<>( + REVIEW_LINK, + getReviewPage(item.getModelObject()), + getReviewParameters(item.getModelObject()) + ); + link.add( + new Label( + PROJECT_TITLE, + item + .getModel() + .map(PeerReview::getPeerRequest) + .map(PeerRequest::getProject) + .map(Project::getTitle) + ) + ); + item.add(link); + item.add( + new EnumLabel<>( + REVIEW_STATUS, + LambdaModel.of(item.getModel(), PeerReview::getStatus, PeerReview::setStatus) + ) + ); + } } - }); - add(new Label(NO_REVIEWS, new ResourceModel("noReviews")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getPeerReviews().getObject().isEmpty()); + ); + add( + new Label(NO_REVIEWS, new ResourceModel("noReviews")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getPeerReviews().getObject().isEmpty()); + } } - }); + ); } private Class getReviewPage(PeerReview modelObject) { @@ -74,21 +100,25 @@ public class MyPeerPanel extends GenericPanel { } private void addRequestsListView() { - add(new ListView<>(REQUEST_LIST, getPeerRequests()) { - @Override - protected void populateItem(ListItem item) { - item.add(new DateLabel(REQUEST_DATE, item.getModel().map(PeerRequest::getDateCreated))); - item.add(new RequestLink(REQUEST_LINK, item.getModel())); - item.add(new CancelLink(CANCEL, item.getModel())); + add( + new ListView<>(REQUEST_LIST, getPeerRequests()) { + @Override + protected void populateItem(ListItem item) { + item.add(new DateLabel(REQUEST_DATE, item.getModel().map(PeerRequest::getDateCreated))); + item.add(new RequestLink(REQUEST_LINK, item.getModel())); + item.add(new CancelLink(CANCEL, item.getModel())); + } } - }); - add(new Label(NO_REQUESTS, new ResourceModel("noRequests")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getPeerRequests().getObject().isEmpty()); + ); + add( + new Label(NO_REQUESTS, new ResourceModel("noRequests")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getPeerRequests().getObject().isEmpty()); + } } - }); + ); } private PageParameters getReviewParameters(PeerReview review) { @@ -101,7 +131,10 @@ public class MyPeerPanel extends GenericPanel { return new LoadableDetachableModel<>() { @Override protected List load() { - return peerReviewService.findNonExpiredReviewsByProjectAuthor(SciProSession.get().getUser(), getModelObject()); + return peerReviewService.findNonExpiredReviewsByProjectAuthor( + SciProSession.get().getUser(), + getModelObject() + ); } }; } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalHeader.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalHeader.java index d85bab95fd..05b40ec993 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalHeader.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalHeader.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -10,57 +12,67 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.util.Arrays; - public class PeerPortalHeader extends GenericPanel { @Inject private PeerReviewService peerReviewService; + @Inject private PeerRequestService peerRequestService; public PeerPortalHeader(String id, final IModel project) { super(id, project); + add( + new WebMarkupContainer("review") { + { + add( + new BookmarkablePageLink( + "perform", + PeerPortalPage.class, + PeerPortalPage.getPageParameters(getModelObject()) + ).setAutoEnable(true) + ); + } - add(new WebMarkupContainer("review") { - { - add(new BookmarkablePageLink("perform", PeerPortalPage.class, PeerPortalPage.getPageParameters(getModelObject())) - .setAutoEnable(true)); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasMoreRequestsThanReviews() && !hasReviewInProgress()); - } - }); - - add(new WebMarkupContainer("request") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!hasMoreRequestsThanReviews() && !hasReviewInProgress()); - } - }); - - add(new WebMarkupContainer("reviewInProgress") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasReviewInProgress()); - } - }); - - add(new PeerRequestSubmissionPanel("submit", project) { - @Override - protected void onComponentTag(ComponentTag tag) { - super.onComponentTag(tag); - if (submissionStartsCollapsed()) { - tag.append("class", "hidden", " "); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(hasMoreRequestsThanReviews() && !hasReviewInProgress()); } } - }); + ); + + add( + new WebMarkupContainer("request") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!hasMoreRequestsThanReviews() && !hasReviewInProgress()); + } + } + ); + + add( + new WebMarkupContainer("reviewInProgress") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(hasReviewInProgress()); + } + } + ); + + add( + new PeerRequestSubmissionPanel("submit", project) { + @Override + protected void onComponentTag(ComponentTag tag) { + super.onComponentTag(tag); + if (submissionStartsCollapsed()) { + tag.append("class", "hidden", " "); + } + } + } + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalPage.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalPage.java index 7f0e8f9f69..fc4f6e54f0 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerPortalPage.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorMyProjects; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class PeerPortalPage extends AbstractPeerPortalPage implements MenuHighlightAuthorMyProjects { @Inject @@ -25,5 +24,4 @@ public class PeerPortalPage extends AbstractPeerPortalPage implements MenuHighli }; add(new PerformReviewPanel("performReview", peerReview)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestListPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestListPanel.java index 5a26c1a899..6be64d9a11 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestListPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestListPanel.java @@ -1,5 +1,16 @@ package se.su.dsv.scipro.peer; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.sql.Date; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -24,23 +35,13 @@ import se.su.dsv.scipro.date.DatePickerPanel; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.sql.Date; -import java.time.Duration; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import static java.util.Arrays.asList; - public class PeerRequestListPanel extends Panel { private static final int DAYS_IN_YEAR = 365; + @Inject private PeerRequestService peerRequestService; + @Inject private ProjectTypeService projectTypeService; @@ -55,19 +56,34 @@ public class PeerRequestListPanel extends Panel { } private void setupDataTable() { - SortableDataProvider dataProvider = - new FilteredDataProvider<>(peerRequestService, Model.of(filter), "dateCreated", SortOrder.DESCENDING); + SortableDataProvider dataProvider = new FilteredDataProvider<>( + peerRequestService, + Model.of(filter), + "dateCreated", + SortOrder.DESCENDING + ); table = new ExportableDataPanel<>("dataTable", createColumns(), dataProvider); add(table); } private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new DateColumn<>(new ResourceModel("dateHeader"), PeerRequest::getDateCreated, "dateCreated", DateStyle.DATETIME)); + columns.add( + new DateColumn<>( + new ResourceModel("dateHeader"), + PeerRequest::getDateCreated, + "dateCreated", + DateStyle.DATETIME + ) + ); - columns.add(new UserColumn<>(new ResourceModel("authorHeader"), "requester.fullName", PeerRequest::getRequester)); + columns.add( + new UserColumn<>(new ResourceModel("authorHeader"), "requester.fullName", PeerRequest::getRequester) + ); - columns.add(new LambdaColumn<>(new ResourceModel("projectHeader"), "project.title", pr -> pr.getProject().getTitle())); + columns.add( + new LambdaColumn<>(new ResourceModel("projectHeader"), "project.title", pr -> pr.getProject().getTitle()) + ); columns.add(new EnumLambdaColumn<>(new ResourceModel("statusHeader"), "status", PeerRequest::getStatus)); return columns; @@ -79,7 +95,6 @@ public class PeerRequestListPanel extends Panel { super(id); filter = new PeerRequestService.Filter(); final AuthorAutoComplete authorField = new AuthorAutoComplete("filterAuthor") { - @Override protected void action(AjaxRequestTarget pTarget, User newSelection) { filter.setAuthor(newSelection); @@ -90,23 +105,33 @@ public class PeerRequestListPanel extends Panel { java.util.List languages = Arrays.asList(Language.values()); final IModel languagePropertyModel = LambdaModel.of(filter::getLanguage, filter::setLanguage); - final DropDownChoice languageFilter = new DropDownChoice<>("filterLanguage", languagePropertyModel, languages, new EnumChoiceRenderer<>(this)); - languageFilter.add(new AjaxFormComponentUpdatingBehavior("change") { - - @Override - protected void onUpdate(AjaxRequestTarget target) { - filter.setLanguage(languagePropertyModel.getObject()); - target.add(table); + final DropDownChoice languageFilter = new DropDownChoice<>( + "filterLanguage", + languagePropertyModel, + languages, + new EnumChoiceRenderer<>(this) + ); + languageFilter.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + filter.setLanguage(languagePropertyModel.getObject()); + target.add(table); + } } - }); + ); filter.setLanguage(languagePropertyModel.getObject()); add(languageFilter); addProjectTypesFilter(); - AjaxCheckBoxMultipleChoice requestStatus = new AjaxCheckBoxMultipleChoice<>("statusFilter", - getRequestStatusModel(), asList(RequestStatus.values()), new EnumChoiceRenderer<>(this)) { + AjaxCheckBoxMultipleChoice requestStatus = new AjaxCheckBoxMultipleChoice<>( + "statusFilter", + getRequestStatusModel(), + asList(RequestStatus.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onUpdate(AjaxRequestTarget target) { target.add(table); @@ -116,7 +141,6 @@ public class PeerRequestListPanel extends Panel { Instant start = Instant.now().minus(Duration.of(DAYS_IN_YEAR, ChronoUnit.DAYS)); final DatePickerPanel datePanel = new DatePickerPanel("datePanel", Date.from(start)) { - @Override public void updateStartDate(AjaxRequestTarget target) { filter.setCreatedAfter(getStartDate()); @@ -133,7 +157,6 @@ public class PeerRequestListPanel extends Panel { filter.setCreatedBefore(datePanel.getEndDate()); add(datePanel); final AjaxCheckBox supervisorProjects = new AjaxCheckBox("supervisorCheckBox", Model.of(false)) { - @Override protected void onUpdate(AjaxRequestTarget target) { if (this.getModelObject()) { @@ -144,16 +167,17 @@ public class PeerRequestListPanel extends Panel { } target.add(table); } - }; add(supervisorProjects); } private void addProjectTypesFilter() { - AjaxCheckBoxMultipleChoice projectTypeFilter = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - projectTypeService.findWithModule(ProjectModule.PEER), - projectTypeService.findWithModule(ProjectModule.PEER), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectTypeFilter = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + projectTypeService.findWithModule(ProjectModule.PEER), + projectTypeService.findWithModule(ProjectModule.PEER), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { filter.setProjectTypes(getModelObject()); diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanel.java index c45bd486a8..6c5f768924 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Iterator; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.navigation.paging.PagingNavigator; @@ -11,7 +14,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.StringResourceModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.components.ConfirmationLink; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.notifications.NotificationController; @@ -19,14 +21,11 @@ import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.PeerEvent; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Iterator; - public class PeerRequestSelectionPanel extends GenericPanel { public static final int REQUESTS_PER_PAGE = 8; @@ -38,12 +37,16 @@ public class PeerRequestSelectionPanel extends GenericPanel { public static final String REQUEST_DETAILS = "requestDetails"; public static final String ACCEPT = "accept"; private static final Logger LOGGER = LoggerFactory.getLogger(PeerRequestSelectionPanel.class); + @Inject private PeerReviewService peerReviewService; + @Inject private PeerRequestService peerRequestService; + @Inject private PeerPortal peerPortal; + @Inject private NotificationController notificationController; @@ -55,7 +58,11 @@ public class PeerRequestSelectionPanel extends GenericPanel { } private void addRequestList() { - DataView requestList = new DataView<>(AVAILABLE_REQUESTS, new RequestProvider(), REQUESTS_PER_PAGE) { + DataView requestList = new DataView<>( + AVAILABLE_REQUESTS, + new RequestProvider(), + REQUESTS_PER_PAGE + ) { @Override protected void populateItem(Item item) { item.add(new Label(TITLE, item.getModel().map(PeerRequest::getProject).map(Project::getTitle))); @@ -68,9 +75,21 @@ public class PeerRequestSelectionPanel extends GenericPanel { } private void addInfoBox() { - add(new Label(CURRENTLY_AWAITING, new StringResourceModel("currentlyAwaiting").setParameters( - peerRequestService.countAvailableRequests(getUser(), RequestStatus.WAITING, getModelObject().getProjectType())))); - final IModel projectTypeSettingsModel = getModel().map(Project::getProjectType).map(ProjectType::getProjectTypeSettings); + add( + new Label( + CURRENTLY_AWAITING, + new StringResourceModel("currentlyAwaiting").setParameters( + peerRequestService.countAvailableRequests( + getUser(), + RequestStatus.WAITING, + getModelObject().getProjectType() + ) + ) + ) + ); + final IModel projectTypeSettingsModel = getModel() + .map(Project::getProjectType) + .map(ProjectType::getProjectTypeSettings); add(new Label(DAYS_TO_SUBMIT, new StringResourceModel("daysToSubmit", projectTypeSettingsModel))); add(new Label(RECENTLY_REVIEWED, new StringResourceModel("recentlyReviewed", projectTypeSettingsModel))); } @@ -81,7 +100,6 @@ public class PeerRequestSelectionPanel extends GenericPanel { setVisibilityAllowed(noReviewInProgress() && hasMoreRequestsThanReviews()); } - private boolean hasMoreRequestsThanReviews() { return countRequests() > countReviews(); } @@ -119,7 +137,11 @@ public class PeerRequestSelectionPanel extends GenericPanel { @Override public void onClick() { try { - PeerReview review = peerPortal.acceptReview(getModelObject(), getUser(), PeerRequestSelectionPanel.this.getModelObject()); + PeerReview review = peerPortal.acceptReview( + getModelObject(), + getUser(), + PeerRequestSelectionPanel.this.getModelObject() + ); notificationController.notifyPeer(review, PeerEvent.Event.REVIEW_ACCEPTED, new NotificationSource()); } catch (PartOfProjectException ignored) { String partOfProjectException = getString("partOfProjectException"); @@ -143,18 +165,28 @@ public class PeerRequestSelectionPanel extends GenericPanel { @Override public Iterator iterator(long first, long count) { - return peerRequestService.findAvailableRequests(getUser(), RequestStatus.WAITING, getModelObject().getProjectType(), new PageRequest(first, count)).iterator(); + return peerRequestService + .findAvailableRequests( + getUser(), + RequestStatus.WAITING, + getModelObject().getProjectType(), + new PageRequest(first, count) + ) + .iterator(); } @Override public long size() { - return peerRequestService.countAvailableRequests(getUser(), RequestStatus.WAITING, getModelObject().getProjectType()); + return peerRequestService.countAvailableRequests( + getUser(), + RequestStatus.WAITING, + getModelObject().getProjectType() + ); } @Override public IModel model(PeerRequest object) { return new DetachableServiceModel<>(peerRequestService, object); } - } } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanel.java index b6a11697fb..c846ee4673 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanel.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.peer; - +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; @@ -29,17 +31,16 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.util.AjaxConfirmationSubmitLink; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public class PeerRequestSubmissionPanel extends GenericPanel { private final FeedbackPanel feedbackPanel; + @Inject private ChecklistTemplateService checklistTemplateService; + @Inject private PeerPortal peerPortal; + @Inject private PeerRequestService peerRequestService; @@ -47,7 +48,6 @@ public class PeerRequestSubmissionPanel extends GenericPanel { public PeerRequestSubmissionPanel(final String id, final IModel projectModel) { super(id, projectModel); - feedbackPanel = new FeedbackPanel("feedbackPanel"); feedbackPanel.setOutputMarkupId(true); add(feedbackPanel); @@ -72,6 +72,7 @@ public class PeerRequestSubmissionPanel extends GenericPanel { } private final class PeerRequestForm extends Form { + private FileUploadField fileUpload; private PeerRequestForm(final String id) { @@ -89,39 +90,52 @@ public class PeerRequestSubmissionPanel extends GenericPanel { IModel> checklistTemplateModel = new LoadableDetachableModel<>() { @Override protected List load() { - return checklistTemplateService.findPeerRequestChecklists(PeerRequestSubmissionPanel.this.getModelObject()); + return checklistTemplateService.findPeerRequestChecklists( + PeerRequestSubmissionPanel.this.getModelObject() + ); } }; - RadioGroup templateRadios = new RadioGroup<>("radioGroup", LambdaModel.of(getModel(), PeerRequest::getChecklistTemplate, PeerRequest::setChecklistTemplate)); + RadioGroup templateRadios = new RadioGroup<>( + "radioGroup", + LambdaModel.of(getModel(), PeerRequest::getChecklistTemplate, PeerRequest::setChecklistTemplate) + ); listContainer.add(templateRadios); - final PageableListView templateListView = new PageableListView<>("templateList", checklistTemplateModel, 5) { + final PageableListView templateListView = new PageableListView<>( + "templateList", + checklistTemplateModel, + 5 + ) { @Override protected void populateItem(final ListItem item) { - item.add(new Radio<>("radio", item.getModel()) - .setLabel(item.getModel().map(ChecklistTemplate::getName))); + item.add( + new Radio<>("radio", item.getModel()).setLabel(item.getModel().map(ChecklistTemplate::getName)) + ); AjaxLink templateLink = new AjaxLink<>("templateLink", item.getModel()) { @Override public void onClick(AjaxRequestTarget target) { - modalWindowPlus.setContent(new ViewChecklistTemplatePanelPeer(modalWindowPlus.getContentId(), getModel())); + modalWindowPlus.setContent( + new ViewChecklistTemplatePanelPeer(modalWindowPlus.getContentId(), getModel()) + ); modalWindowPlus.setTitle("Preview of chosen checklist template"); modalWindowPlus.show(target); } }; item.add(templateLink); - } }; - listContainer.add(new Label("noTemplatesFoundMsg", "No templates found") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(templateListView.getList().isEmpty()); + listContainer.add( + new Label("noTemplatesFoundMsg", "No templates found") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(templateListView.getList().isEmpty()); + } } - }); + ); Radio noTemplate = new Radio<>("noTemp") { @Override @@ -148,26 +162,40 @@ public class PeerRequestSubmissionPanel extends GenericPanel { listContainer.add(pager); add(listContainer); - add(new TextArea<>("comment", LambdaModel.of(getModel(), PeerRequest::getComment, PeerRequest::setComment))); + add( + new TextArea<>("comment", LambdaModel.of(getModel(), PeerRequest::getComment, PeerRequest::setComment)) + ); fileUpload = new FileUploadField("fileUpload"); fileUpload.setRequired(true); add(fileUpload); java.util.List languages = Arrays.asList(Language.values()); - add(new DropDownChoice<>("language", LambdaModel.of(getModel(), PeerRequest::getLanguage, PeerRequest::setLanguage),languages, new EnumChoiceRenderer<>(this)).setRequired(true)); + add( + new DropDownChoice<>( + "language", + LambdaModel.of(getModel(), PeerRequest::getLanguage, PeerRequest::setLanguage), + languages, + new EnumChoiceRenderer<>(this) + ).setRequired(true) + ); - add(new AjaxConfirmationSubmitLink("submit", "Please confirm your request for peer review. Once it has been accepted by someone, you cannot withdraw it.") { - @Override - protected void onAfterSubmit(AjaxRequestTarget target) { - setResponsePage(getPage()); - } + add( + new AjaxConfirmationSubmitLink( + "submit", + "Please confirm your request for peer review. Once it has been accepted by someone, you cannot withdraw it." + ) { + @Override + protected void onAfterSubmit(AjaxRequestTarget target) { + setResponsePage(getPage()); + } - @Override - protected void onError(AjaxRequestTarget target) { - target.add(feedbackPanel); + @Override + protected void onError(AjaxRequestTarget target) { + target.add(feedbackPanel); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewFilterDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewFilterDetailsPanel.java index 144dd24f30..287a8b5c3a 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewFilterDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewFilterDetailsPanel.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.peer; import jakarta.inject.Inject; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; @@ -12,28 +13,28 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.stream.Collectors; - public class PeerReviewFilterDetailsPanel extends Panel { + private final PeerReviewService.Filter filter; + @Inject DateService dateService; public PeerReviewFilterDetailsPanel(String id, PeerReviewService.Filter filter) { super(id); this.filter = filter; - add(new Label("filterInfo", - new StringResourceModel("filterInfo", - Model.of(new FilterStringFormatter()))).setEscapeModelStrings(false)); + add( + new Label( + "filterInfo", + new StringResourceModel("filterInfo", Model.of(new FilterStringFormatter())) + ).setEscapeModelStrings(false) + ); } protected class FilterStringFormatter implements IClusterable { public String projectTypeNames() { - return filter.getProjectTypes() - .stream() - .map(ProjectType::getName) - .collect(Collectors.joining(", ")); + return filter.getProjectTypes().stream().map(ProjectType::getName).collect(Collectors.joining(", ")); } public String supervisorName() { @@ -50,7 +51,6 @@ public class PeerReviewFilterDetailsPanel extends Panel { return getString("notAvailable"); } return author.getFullName(); - } public String language() { @@ -83,4 +83,3 @@ public class PeerReviewFilterDetailsPanel extends Panel { } } } - diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewGuidePanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewGuidePanel.java index 2543bd4d49..136b231c4d 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewGuidePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewGuidePanel.java @@ -3,7 +3,8 @@ package se.su.dsv.scipro.peer; import org.apache.wicket.markup.html.panel.Panel; public class PeerReviewGuidePanel extends Panel { - public PeerReviewGuidePanel(final String id) { - super(id); - } + + public PeerReviewGuidePanel(final String id) { + super(id); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatisticsPanel.java index bb15955b9f..1d5d3cf571 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatisticsPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.io.Serializable; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; @@ -30,15 +34,11 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.io.Serializable; -import java.time.ZonedDateTime; -import java.util.*; - public class PeerReviewStatisticsPanel extends Panel { @Inject private PeerReviewService peerReviewService; + @Inject private ProjectTypeService projectTypeService; @@ -65,14 +65,17 @@ public class PeerReviewStatisticsPanel extends Panel { } private void prepareDefaultFilter() { - filter.setProjectTypes(projectTypeService.findByDegreeTypes(EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))); + filter.setProjectTypes( + projectTypeService.findByDegreeTypes( + EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ) + ); filter.setCreatedBefore(new Date()); filter.setCreatedAfter(Date.from(ZonedDateTime.now().minusMonths(6).toInstant())); } private void addAuthorFilter() { final AuthorAutoComplete authorField = new AuthorAutoComplete("filterAuthor") { - @Override protected void action(AjaxRequestTarget pTarget, User newSelection) { filter.setAuthor(newSelection); @@ -84,7 +87,6 @@ public class PeerReviewStatisticsPanel extends Panel { private void addOtherFilter() { final AjaxCheckBox supervisorProjects = new AjaxCheckBox("supervisorCheckBox", Model.of(false)) { - @Override protected void onUpdate(AjaxRequestTarget target) { if (this.getModelObject()) { @@ -100,59 +102,80 @@ public class PeerReviewStatisticsPanel extends Panel { } private void addDateFilter() { - add(new DeactivatableDatePickerPanel("datePanel", + add( + new DeactivatableDatePickerPanel( + "datePanel", LambdaModel.of(filter::getCreatedAfter, filter::setCreatedAfter), LambdaModel.of(filter::getCreatedBefore, filter::setCreatedBefore), - Model.of(true)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(wmc); + Model.of(true) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); } private void addLanguageFilter() { List languages = Arrays.asList(Language.values()); final IModel languagePropertyModel = LambdaModel.of(filter::getLanguage, filter::setLanguage); - final DropDownChoice languageFilter = new DropDownChoice<>("filterLanguage", - languagePropertyModel, languages, new EnumChoiceRenderer<>(this)); - languageFilter.add(new AjaxFormComponentUpdatingBehavior("change") { - - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(wmc); + final DropDownChoice languageFilter = new DropDownChoice<>( + "filterLanguage", + languagePropertyModel, + languages, + new EnumChoiceRenderer<>(this) + ); + languageFilter.add( + new AjaxFormComponentUpdatingBehavior("change") { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); filter.setLanguage(languagePropertyModel.getObject()); add(languageFilter); } private void addProjectTypesFilter() { - add(new AjaxCheckBoxMultipleChoice<>("projectTypes", + add( + new AjaxCheckBoxMultipleChoice<>( + "projectTypes", LambdaModel.of(filter::getProjectTypes, filter::setProjectTypes), - projectTypeService.findWithModule(ProjectModule.PEER), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(wmc); + projectTypeService.findWithModule(ProjectModule.PEER), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); } private void setupStatisticDetailsPart() { wmc = new WebMarkupContainer("container"); wmc.setOutputMarkupId(true); add(wmc); - wmc.add(new Label("totalPeerReviews", new LoadableDetachableModel() { - @Override - protected Long load() { - return peerReviewService.count(filter); - } - })); + wmc.add( + new Label( + "totalPeerReviews", + new LoadableDetachableModel() { + @Override + protected Long load() { + return peerReviewService.count(filter); + } + } + ) + ); ListView statusListView = new ListView<>("statusList", Arrays.asList(ReviewStatus.values())) { @Override protected void populateItem(final ListItem item) { - item.add(new Label("numberOfPeerReviews", peerReviewService.countByStatus(item.getModelObject(), filter))); + item.add( + new Label("numberOfPeerReviews", peerReviewService.countByStatus(item.getModelObject(), filter)) + ); Link detailsLink = new Link<>("detailsLink") { @Override public void onClick() { @@ -161,7 +184,12 @@ public class PeerReviewStatisticsPanel extends Panel { }; detailsLink.add(new Label("status", new ResourceModel(item.getModelObject().name()))); item.add(detailsLink); - item.add(new Label("withOutChecklistTmp", peerReviewService.countByStatusAndNoCheckListTemplate(filter, item.getModelObject()))); + item.add( + new Label( + "withOutChecklistTmp", + peerReviewService.countByStatusAndNoCheckListTemplate(filter, item.getModelObject()) + ) + ); } }; wmc.add(statusListView); diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatusStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatusStatisticsPanel.java index 2193555a56..60e563e2e7 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatusStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerReviewStatusStatisticsPanel.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.peer; import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -22,9 +24,6 @@ import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.dataproviders.FilteredDataProvider; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.ArrayList; -import java.util.List; - public class PeerReviewStatusStatisticsPanel extends Panel { @Inject @@ -40,49 +39,75 @@ public class PeerReviewStatusStatisticsPanel extends Panel { add(new PeerReviewFilterDetailsPanel("filterDetails", filter)); setupDataTable(); - } private void setupDataTable() { - SortableDataProvider dataProvider = new FilteredDataProvider<>(peerReviewService, Model.of(filter), "dateCreated", SortOrder.DESCENDING); + SortableDataProvider dataProvider = new FilteredDataProvider<>( + peerReviewService, + Model.of(filter), + "dateCreated", + SortOrder.DESCENDING + ); add(new ExportableDataPanel<>("dataTable", createColumns(), dataProvider)); } private List> createColumns() { List> columns = new ArrayList<>(); - columns.add(new DateColumn<>(Model.of("Commenced"), PeerReview::getDateCreated, "dateCreated", DateStyle.DATETIME)); + columns.add( + new DateColumn<>(Model.of("Commenced"), PeerReview::getDateCreated, "dateCreated", DateStyle.DATETIME) + ); columns.add(new UserColumn<>(Model.of("Reviewing author"), "reviewer.fullName", PeerReview::getReviewer)); - columns.add(new UserColumn<>(Model.of("Requesting author"), "peerRequest.requester.fullName", review -> review.getPeerRequest().getRequester())); + columns.add( + new UserColumn<>(Model.of("Requesting author"), "peerRequest.requester.fullName", review -> + review.getPeerRequest().getRequester() + ) + ); columns.add(new LambdaColumn<>(Model.of("Title"), review -> review.getPeerRequest().getProject().getTitle())); - columns.add(new AbstractColumn<>(Model.of("Status"), "status") { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new AjaxEnumLinkPanel<>(componentId, rowModel, LambdaModel.of(rowModel, PeerReview::getStatus, PeerReview::setStatus)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(PeerReview.class), getModelObject().getId()); - if (isSupervisorView) { - setResponsePage(SupervisorViewPeerReviewAllPeersPage.class, pp); - } else { - setResponsePage(AdminPeerReviewPage.class, pp); - } - } + columns.add( + new AbstractColumn<>(Model.of("Status"), "status") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new AjaxEnumLinkPanel<>( + componentId, + rowModel, + LambdaModel.of(rowModel, PeerReview::getStatus, PeerReview::setStatus) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(PeerReview.class), getModelObject().getId()); + if (isSupervisorView) { + setResponsePage(SupervisorViewPeerReviewAllPeersPage.class, pp); + } else { + setResponsePage(AdminPeerReviewPage.class, pp); + } + } - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(getModelObject().isCompleted()); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(getModelObject().isCompleted()); + } + } + ); + } } - }); + ); if (filter.getStatuses().contains(PeerReview.ReviewStatus.COMPLETED)) { - columns.add(new LambdaColumn<>(Model.of("Number of answered checklists questions"), review -> review.getAnswers().size())); + columns.add( + new LambdaColumn<>(Model.of("Number of answered checklists questions"), review -> + review.getAnswers().size() + ) + ); } return columns; } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PeerSummaryPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PeerSummaryPanel.java index c6215d6f84..73a1f1b10d 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PeerSummaryPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PeerSummaryPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -18,9 +20,6 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.List; - @ProjectModuleComponent(ProjectModule.PEER) public class PeerSummaryPanel extends GenericPanel { @@ -37,7 +36,6 @@ public class PeerSummaryPanel extends GenericPanel { public PeerSummaryPanel(String id, IModel model) { super(id, model); - add(new PeerReviewList(RECEIVED_REVIEWS, getReceivedReviews())); add(new PeerReviewList(PERFORMED_REVIEWS, getPerformedReviews())); add(new NoReviewsLabel(NO_RECEIVED, getReceivedReviews())); @@ -77,12 +75,12 @@ public class PeerSummaryPanel extends GenericPanel { item.add(link); item.add(new Label(REVIEWER, item.getModel().map(PeerReview::getReviewer).map(User::getFullName))); } - } private Class getReviewPage() { - return getModelObject().isParticipant(SciProSession.get().getUser()) ? - ViewPeerReviewPage.class : SupervisorViewPeerReviewPage.class; + return getModelObject().isParticipant(SciProSession.get().getUser()) + ? ViewPeerReviewPage.class + : SupervisorViewPeerReviewPage.class; } private static class NoReviewsLabel extends Label { diff --git a/view/src/main/java/se/su/dsv/scipro/peer/PerformReviewPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/PerformReviewPanel.java index 35bf54d676..3f9af89965 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/PerformReviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/PerformReviewPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; +import java.util.Optional; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; @@ -20,9 +22,6 @@ import se.su.dsv.scipro.files.WicketFileUpload; import se.su.dsv.scipro.grading.ScrollingSaveButtonPanel; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import jakarta.inject.Inject; -import java.util.Optional; - public class PerformReviewPanel extends GenericPanel { public static final String REVIEW_FORM = "reviewForm"; @@ -42,7 +41,6 @@ public class PerformReviewPanel extends GenericPanel { public PerformReviewPanel(String id, IModel peerReview) { super(id, peerReview); - IModel peerRequest = getModel().map(PeerReview::getPeerRequest); add(new ReviewPageRequestDetailsPanel(REQUEST_DETAILS, peerRequest)); add(new PerformReviewForm(REVIEW_FORM, getModel())); @@ -70,42 +68,58 @@ public class PerformReviewPanel extends GenericPanel { add(new DateLabel(DEADLINE, reviewModel.map(PeerReview::getDeadline), DateStyle.DATETIME)); - add(new ListView<>(ANSWERS, reviewModel.map(PeerReview::getAnswers)) { - @Override - protected void populateItem(ListItem item) { - final IModel answer = item.getModel(); - item.add(new Label(QUESTION, answer.map(Answer::getQuestion))); - item.add(new TrafficLightPanel(ANSWER, LambdaModel.of(answer, Answer::getAnswer, Answer::setAnswer))); - item.add(new TextArea<>(MOTIVATION, LambdaModel.of(answer, Answer::getMotivation, Answer::setMotivation)).add(new AutoSavingBehaviour() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - performReviewService.save(PerformReviewForm.this.getModelObject()); - } - })); - } + add( + new ListView<>(ANSWERS, reviewModel.map(PeerReview::getAnswers)) { + @Override + protected void populateItem(ListItem item) { + final IModel answer = item.getModel(); + item.add(new Label(QUESTION, answer.map(Answer::getQuestion))); + item.add( + new TrafficLightPanel(ANSWER, LambdaModel.of(answer, Answer::getAnswer, Answer::setAnswer)) + ); + item.add( + new TextArea<>( + MOTIVATION, + LambdaModel.of(answer, Answer::getMotivation, Answer::setMotivation) + ).add( + new AutoSavingBehaviour() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + performReviewService.save(PerformReviewForm.this.getModelObject()); + } + } + ) + ); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getModelObject().isEmpty()); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getModelObject().isEmpty()); + } } - }); + ); - add(new TextArea<>(COMMENT, LambdaModel.of(reviewModel, PeerReview::getComment, PeerReview::setComment)) { - { - add(new AutoSavingBehaviour() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - performReviewService.save(PerformReviewForm.this.getModelObject()); - } - }); + add( + new TextArea<>(COMMENT, LambdaModel.of(reviewModel, PeerReview::getComment, PeerReview::setComment)) { + { + add( + new AutoSavingBehaviour() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + performReviewService.save(PerformReviewForm.this.getModelObject()); + } + } + ); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(PerformReviewForm.this.getModelObject().getAnswers().isEmpty()); + } } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(PerformReviewForm.this.getModelObject().getAnswers().isEmpty()); - } - }); + ); reviewFileUpload = new FileUploadField(FILE, new ListModel<>()); add(reviewFileUpload); @@ -119,8 +133,9 @@ public class PerformReviewPanel extends GenericPanel { @Override public void onSubmit() { try { - final Optional fileUploadOption = Optional.ofNullable(reviewFileUpload.getFileUpload()) - .map(WicketFileUpload::new); + final Optional fileUploadOption = Optional.ofNullable( + reviewFileUpload.getFileUpload() + ).map(WicketFileUpload::new); performReviewService.submit(PerformReviewForm.this.getModelObject(), fileUploadOption); success(getString("submitted")); PerformReviewForm.this.detach(); @@ -131,8 +146,12 @@ public class PerformReviewPanel extends GenericPanel { } } }; - submitButton.add(new JavascriptEventConfirmation("click", - "Please confirm that you have completed the review and taken care to highlight both strengths and weaknesses.")); + submitButton.add( + new JavascriptEventConfirmation( + "click", + "Please confirm that you have completed the review and taken care to highlight both strengths and weaknesses." + ) + ); add(submitButton); } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/RequestDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/RequestDetailsPanel.java index 54dfb905f6..8dc86a3d3e 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/RequestDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/RequestDetailsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.basic.EnumLabel; @@ -20,8 +21,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.system.Language; -import jakarta.inject.Inject; - public class RequestDetailsPanel extends Panel { public static final String TEMPLATE_LINK = "templateLink"; @@ -36,58 +35,87 @@ public class RequestDetailsPanel extends Panel { public RequestDetailsPanel(String id, IModel peerRequest) { super(id); - modalWindowPlus = new ModalWindowPlus(DIALOG); add(modalWindowPlus); - add(new DateLabel(DATE_REQUESTED, LambdaModel.of(peerRequest, PeerRequest::getDateCreated, PeerRequest::setDateCreated), DateStyle.DATETIME)); - add(new UserLinkPanel(REQUESTER, LambdaModel.of(peerRequest, PeerRequest::getRequester, PeerRequest::setRequester))); + add( + new DateLabel( + DATE_REQUESTED, + LambdaModel.of(peerRequest, PeerRequest::getDateCreated, PeerRequest::setDateCreated), + DateStyle.DATETIME + ) + ); + add( + new UserLinkPanel( + REQUESTER, + LambdaModel.of(peerRequest, PeerRequest::getRequester, PeerRequest::setRequester) + ) + ); - add(new AjaxLink<>(TEMPLATE_LINK, LambdaModel.of(peerRequest, PeerRequest::getChecklistTemplate, PeerRequest::setChecklistTemplate)) { - @Override - public void onClick(AjaxRequestTarget target) { - ViewChecklistTemplatePanelPeer vclPanel = - new ViewChecklistTemplatePanelPeer(modalWindowPlus.getContentId(), getModel()); - modalWindowPlus.setContent(vclPanel); - modalWindowPlus.setTitle("Preview of chosen checklist template"); - modalWindowPlus.show(target); + add( + new AjaxLink<>( + TEMPLATE_LINK, + LambdaModel.of(peerRequest, PeerRequest::getChecklistTemplate, PeerRequest::setChecklistTemplate) + ) { + @Override + public void onClick(AjaxRequestTarget target) { + ViewChecklistTemplatePanelPeer vclPanel = new ViewChecklistTemplatePanelPeer( + modalWindowPlus.getContentId(), + getModel() + ); + modalWindowPlus.setContent(vclPanel); + modalWindowPlus.setTitle("Preview of chosen checklist template"); + modalWindowPlus.show(target); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setEnabled(getModelObject() != null); + setBody(Model.of(getModelObject() != null ? getModelObject().getName() : "No template attached")); + } } + ); - @Override - protected void onConfigure() { - super.onConfigure(); - setEnabled(getModelObject() != null); - setBody(Model.of(getModelObject() != null ? getModelObject().getName() : "No template attached")); - } - }); - - IModel languageModel = LambdaModel.of(peerRequest, PeerRequest::getLanguage, PeerRequest::setLanguage); + IModel languageModel = LambdaModel.of( + peerRequest, + PeerRequest::getLanguage, + PeerRequest::setLanguage + ); if (peerRequest.getObject().getLanguage() != null) { add(new EnumLabel<>("language", languageModel)); } else { add(new Label("language", "No language provided")); } - if (peerRequest.getObject().getComment() != null) { - add(new MultiLineLabel("requestComment", LambdaModel.of(peerRequest, PeerRequest::getComment, PeerRequest::setComment))); + add( + new MultiLineLabel( + "requestComment", + LambdaModel.of(peerRequest, PeerRequest::getComment, PeerRequest::setComment) + ) + ); } else { add(new Label("requestComment", "No comment provided")); } - IModel fileModel = peerRequest.map(PeerRequest::getFile).map(FileReference::getFileDescription); + IModel fileModel = peerRequest + .map(PeerRequest::getFile) + .map(FileReference::getFileDescription); if (fileModel.getObject() != null) { add(new Label("fileName", LambdaModel.of(fileModel, FileDescription::getName, FileDescription::setName))); } else { add(new Label("fileName", "No file provided")); } - add(new ViewAttachmentPanel("download", fileModel) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(generalSystemSettingsService.getGeneralSystemSettingsInstance().isPeerDownloadEnabled()); + add( + new ViewAttachmentPanel("download", fileModel) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(generalSystemSettingsService.getGeneralSystemSettingsInstance().isPeerDownloadEnabled()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanel.java index c33375d935..e972272ef3 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.peer; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.panel.Panel; @@ -12,15 +13,13 @@ import se.su.dsv.scipro.file.FileService; import se.su.dsv.scipro.profile.UserLabel; import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; -import jakarta.inject.Inject; - public class ReviewPageRequestDetailsPanel extends Panel { + @Inject FileService fileDescriptionService; public ReviewPageRequestDetailsPanel(final String id, final IModel request) { super(id, request); - add(new UserLabel("requester", request.map(PeerRequest::getRequester))); add(new DateLabel("dateCreated", request.map(PeerRequest::getDateCreated), DateStyle.DATETIME)); add(new EnumLabel<>("status", request.map(PeerRequest::getStatus))); diff --git a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeerReviewStatusStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeerReviewStatusStatisticsPage.java index 1b037e34a4..935a5a1ecb 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeerReviewStatusStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeerReviewStatusStatisticsPage.java @@ -1,13 +1,15 @@ package se.su.dsv.scipro.peer; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorAllPeers; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) -public class SupervisorPeerReviewStatusStatisticsPage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorAllPeers { +@Authorization(authorizedRoles = { SUPERVISOR }) +public class SupervisorPeerReviewStatusStatisticsPage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorAllPeers { public static final boolean IS_SUPERVISOR_VIEW = true; diff --git a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeersPage.java b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeersPage.java index e413b94953..876933b032 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeersPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorPeersPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.peer; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -7,23 +10,24 @@ import se.su.dsv.scipro.admin.panels.PeerRequestStatsPanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; -import java.util.Collections; - -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) +@Authorization(authorizedRoles = { SUPERVISOR }) public class SupervisorPeersPage extends AbstractSupervisorAllProjectsPage { public SupervisorPeersPage(PageParameters pp) { super(pp); add(new PeerRequestStatsPanel("peerRequestStats")); - add(new PeerReviewStatisticsPanel("peerReviewList", new PeerReviewStatisticsPanel.PageSupplier() { - @Override - public Page statusPage(IModel model, PeerReviewService.Filter filter) { - filter.setStatuses(Collections.singletonList(model.getObject())); - return new SupervisorPeerReviewStatusStatisticsPage(filter); - } - })); + add( + new PeerReviewStatisticsPanel( + "peerReviewList", + new PeerReviewStatisticsPanel.PageSupplier() { + @Override + public Page statusPage(IModel model, PeerReviewService.Filter filter) { + filter.setStatuses(Collections.singletonList(model.getObject())); + return new SupervisorPeerReviewStatusStatisticsPage(filter); + } + } + ) + ); add(new PeerRequestListPanel("peerRequestList")); } } diff --git a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPage.java b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPage.java index 87a17ff2c1..a80fd6b73c 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPage.java @@ -1,27 +1,35 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.LambdaModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorAllPeers; -import se.su.dsv.scipro.data.DetachableServiceModel; -import se.su.dsv.scipro.profile.UserLinkPanel; -import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; -import se.su.dsv.scipro.util.PageParameterKeys; - -import jakarta.inject.Inject; - -public class SupervisorViewPeerReviewAllPeersPage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorAllPeers { - - @Inject - private PeerReviewService peerReviewService; - - public SupervisorViewPeerReviewAllPeersPage(PageParameters pp) { - super(pp); - long reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); - IModel reviewModel = new DetachableServiceModel<>(peerReviewService, reviewId); - add(new DisplayReviewPanel("review", reviewModel)); - add(new ReviewPageRequestDetailsPanel("request", LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest))); - add(new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer))); - } -} +package se.su.dsv.scipro.peer; + +import jakarta.inject.Inject; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.LambdaModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorAllPeers; +import se.su.dsv.scipro.data.DetachableServiceModel; +import se.su.dsv.scipro.profile.UserLinkPanel; +import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorAllProjectsPage; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class SupervisorViewPeerReviewAllPeersPage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorAllPeers { + + @Inject + private PeerReviewService peerReviewService; + + public SupervisorViewPeerReviewAllPeersPage(PageParameters pp) { + super(pp); + long reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); + IModel reviewModel = new DetachableServiceModel<>(peerReviewService, reviewId); + add(new DisplayReviewPanel("review", reviewModel)); + add( + new ReviewPageRequestDetailsPanel( + "request", + LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest) + ) + ); + add( + new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer)) + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPage.java b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPage.java index a72f0b0217..2288cdc3bd 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPage.java @@ -1,28 +1,36 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.LambdaModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyProjects; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorOverview; -import se.su.dsv.scipro.data.DetachableServiceModel; -import se.su.dsv.scipro.profile.UserLinkPanel; -import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; -import se.su.dsv.scipro.util.PageParameterKeys; - -import jakarta.inject.Inject; - -public class SupervisorViewPeerReviewPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorOverview, MenuHighlightSupervisorMyProjects { - - @Inject - private PeerReviewService peerReviewService; - - public SupervisorViewPeerReviewPage(PageParameters pp) { - super(pp); - long reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); - IModel reviewModel = new DetachableServiceModel<>(peerReviewService, reviewId); - add(new DisplayReviewPanel("review", reviewModel)); - add(new ReviewPageRequestDetailsPanel("request", LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest))); - add(new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer))); - } -} +package se.su.dsv.scipro.peer; + +import jakarta.inject.Inject; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.LambdaModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyProjects; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorOverview; +import se.su.dsv.scipro.data.DetachableServiceModel; +import se.su.dsv.scipro.profile.UserLinkPanel; +import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class SupervisorViewPeerReviewPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorOverview, MenuHighlightSupervisorMyProjects { + + @Inject + private PeerReviewService peerReviewService; + + public SupervisorViewPeerReviewPage(PageParameters pp) { + super(pp); + long reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); + IModel reviewModel = new DetachableServiceModel<>(peerReviewService, reviewId); + add(new DisplayReviewPanel("review", reviewModel)); + add( + new ReviewPageRequestDetailsPanel( + "request", + LambdaModel.of(reviewModel, PeerReview::getPeerRequest, PeerReview::setPeerRequest) + ) + ); + add( + new UserLinkPanel("reviewer", LambdaModel.of(reviewModel, PeerReview::getReviewer, PeerReview::setReviewer)) + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/peer/ViewPeerReviewPage.java b/view/src/main/java/se/su/dsv/scipro/peer/ViewPeerReviewPage.java index 6c484de948..a85d56e51d 100644 --- a/view/src/main/java/se/su/dsv/scipro/peer/ViewPeerReviewPage.java +++ b/view/src/main/java/se/su/dsv/scipro/peer/ViewPeerReviewPage.java @@ -1,7 +1,7 @@ package se.su.dsv.scipro.peer; import jakarta.inject.Inject; - +import java.util.Objects; import org.apache.wicket.RestartResponseException; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -17,17 +17,16 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.Objects; - public class ViewPeerReviewPage extends AbstractPeerPortalPage implements MenuHighlightAuthorMyProjects { + @Inject private PeerReviewService peerReviewService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; public ViewPeerReviewPage(PageParameters pp) { super(pp); - long reviewId; try { reviewId = pp.get(PageParameterKeys.MAP.get(PeerReview.class)).toLong(); @@ -40,12 +39,14 @@ public class ViewPeerReviewPage extends AbstractPeerPortalPage implements MenuHi throw new PageNotFoundException(); } - add(new PeerPortalHeader("header", projectModel) { - @Override - protected boolean submissionStartsCollapsed() { - return true; + add( + new PeerPortalHeader("header", projectModel) { + @Override + protected boolean submissionStartsCollapsed() { + return true; + } } - }); + ); if (!checkAccess(SciProSession.get().getUser(), reviewModel.getObject())) { throw new RestartResponseException(AccessDeniedPage.class); diff --git a/view/src/main/java/se/su/dsv/scipro/plagiarism/UrkundSubmissionPanel.java b/view/src/main/java/se/su/dsv/scipro/plagiarism/UrkundSubmissionPanel.java index 38be0ab5fb..36e74cce70 100644 --- a/view/src/main/java/se/su/dsv/scipro/plagiarism/UrkundSubmissionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/plagiarism/UrkundSubmissionPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.plagiarism; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; @@ -10,34 +11,40 @@ import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.plagiarism.PlagiarismControl.Status; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class UrkundSubmissionPanel extends GenericPanel { + @Inject private PlagiarismControl plagiarismControl; public UrkundSubmissionPanel(final String id, final IModel model) { super(id, model); - final IModel submission = model.map(plagiarismControl::getStatus); add(new Details("submissionDetails", submission)); - final WebMarkupContainer notSubmitted = new WebMarkupContainer("notSubmitted", submission.as(Status.NotSubmitted.class)) { + final WebMarkupContainer notSubmitted = new WebMarkupContainer( + "notSubmitted", + submission.as(Status.NotSubmitted.class) + ) { @Override protected void onConfigure() { super.onConfigure(); setVisibilityAllowed(getDefaultModelObject() != null); } }; - notSubmitted.add(new Link<>("submit", model) { - @Override - public void onClick() { - plagiarismControl.submit(getModelObject(), SciProSession.get().getUser()); + notSubmitted.add( + new Link<>("submit", model) { + @Override + public void onClick() { + plagiarismControl.submit(getModelObject(), SciProSession.get().getUser()); + } } - }); + ); add(notSubmitted); - final WebMarkupContainer submitted = new WebMarkupContainer("submitted", submission.as(Status.Submitted.class)) { + final WebMarkupContainer submitted = new WebMarkupContainer( + "submitted", + submission.as(Status.Submitted.class) + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -48,44 +55,56 @@ public class UrkundSubmissionPanel extends GenericPanel { } private class Details extends WebMarkupContainer { + private Details(final String id, final IModel submission) { super(id, submission); final IModel analysed = submission.as(Status.Analysed.class); final IModel error = submission.as(Status.Error.class); - add(new Label("message", error.map(Status.Error::message)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); + add( + new Label("message", error.map(Status.Error::message)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } } - }); - add(new ExternalLink("report", analysed.map(Status.Analysed::url)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null); + ); + add( + new ExternalLink("report", analysed.map(Status.Analysed::url)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getDefaultModelObject() != null); + } } - }); - add(new Label("significance", analysed.map(Status.Analysed::percentMatched)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null); - } - }); - add(new Link<>("resubmit", error) { - @Override - public void onClick() { - plagiarismControl.resubmit(UrkundSubmissionPanel.this.getModelObject(), SciProSession.get().getUser()); + ); + add( + new Label("significance", analysed.map(Status.Analysed::percentMatched)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getDefaultModelObject() != null); + } } + ); + add( + new Link<>("resubmit", error) { + @Override + public void onClick() { + plagiarismControl.resubmit( + UrkundSubmissionPanel.this.getModelObject(), + SciProSession.get().getUser() + ); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject() != null); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject() != null); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/profile/DaisyPicture.java b/view/src/main/java/se/su/dsv/scipro/profile/DaisyPicture.java index 465e62a974..4ed217b535 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/DaisyPicture.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/DaisyPicture.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.profile; +import jakarta.inject.Inject; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.wicket.injection.Injector; import org.apache.wicket.request.resource.AbstractResource; import org.apache.wicket.request.resource.IResource; @@ -14,18 +24,8 @@ import se.su.dsv.scipro.project.ProjectTeamMemberRoles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.io.IOException; -import java.io.InputStream; -import java.time.Duration; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - public class DaisyPicture extends ResourceReference { + public static final String USER_ID = "id"; @Inject @@ -59,38 +59,48 @@ public class DaisyPicture extends ResourceReference { final List projects = projectService.findAll(filter); final Set projectRelations = projects - .stream() - .flatMap(p -> p.getMembers().stream()) - .map(Member::getUser) - .map(User::getIdentifier) - .collect(Collectors.toSet()); + .stream() + .flatMap(p -> p.getMembers().stream()) + .map(Member::getUser) + .map(User::getIdentifier) + .collect(Collectors.toSet()); - final Set seminarRelations = projects.stream() - .map(finalSeminarService::findByProject) - .filter(Objects::nonNull) - .flatMap(fs -> Stream.concat(fs.getOpponents().stream(), fs.getActiveParticipants().stream())) - .map(User::getIdentifier) - .collect(Collectors.toSet()); + final Set seminarRelations = projects + .stream() + .map(finalSeminarService::findByProject) + .filter(Objects::nonNull) + .flatMap(fs -> Stream.concat(fs.getOpponents().stream(), fs.getActiveParticipants().stream())) + .map(User::getIdentifier) + .collect(Collectors.toSet()); final int userId = attributes.getParameters().get(USER_ID).toInt(0); final boolean alwaysShow = projectRelations.contains(userId) || seminarRelations.contains(userId); Integer requesterDaisyId = null; - if(session.getUser() != null){ + if (session.getUser() != null) { requesterDaisyId = session.getUser().getIdentifier(); } - final PhotoResult photo = daisyAPI.getPhoto(userId, requesterDaisyId == null ? -1 : requesterDaisyId, alwaysShow); + final PhotoResult photo = daisyAPI.getPhoto( + userId, + requesterDaisyId == null ? -1 : requesterDaisyId, + alwaysShow + ); return photo.fold(this::noPhoto, this::noPhoto, this::showPhoto); } private ResourceResponse showPhoto(final InputStream inputStream) { final ResourceResponse resourceResponse = new ResourceResponse(); - resourceResponse.setWriteCallback(new WriteCallback() { - @Override - public void writeData(final Attributes attributes) throws IOException { - try { writeStream(attributes, inputStream); } - finally { inputStream.close(); } + resourceResponse.setWriteCallback( + new WriteCallback() { + @Override + public void writeData(final Attributes attributes) throws IOException { + try { + writeStream(attributes, inputStream); + } finally { + inputStream.close(); + } + } } - }); + ); resourceResponse.setCacheDuration(Duration.ofDays(1)); return resourceResponse; } @@ -98,14 +108,16 @@ public class DaisyPicture extends ResourceReference { private ResourceResponse noPhoto() { final ResourceResponse resourceResponse = new ResourceResponse(); resourceResponse.setCacheDuration(Duration.ZERO); - resourceResponse.setWriteCallback(new WriteCallback() { - @Override - public void writeData(final Attributes attributes) throws IOException { - try (InputStream is = DaisyPicture.class.getResourceAsStream("anonymous.png")) { - writeStream(attributes, is); + resourceResponse.setWriteCallback( + new WriteCallback() { + @Override + public void writeData(final Attributes attributes) throws IOException { + try (InputStream is = DaisyPicture.class.getResourceAsStream("anonymous.png")) { + writeStream(attributes, is); + } } } - }); + ); return resourceResponse; } }; diff --git a/view/src/main/java/se/su/dsv/scipro/profile/DisplayUserProfilePanel.java b/view/src/main/java/se/su/dsv/scipro/profile/DisplayUserProfilePanel.java index 9b5f7f8652..9c967c0b66 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/DisplayUserProfilePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/DisplayUserProfilePanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.profile; +import jakarta.inject.Inject; import org.apache.wicket.extensions.markup.html.basic.SmartLinkMultiLineLabel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.EnumLabel; @@ -25,28 +26,52 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class DisplayUserProfilePanel extends GenericPanel { @Inject private UserProfileService userProfileService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; public DisplayUserProfilePanel(String id, final IModel model) { super(id, model); - add(new UserProfileImage("image", model, UserProfileImage.Size.LARGE)); - add(new ExternalLink(MAIL, "mailto:" + model.getObject().getEmailAddress(), model.getObject().getEmailAddress())); + add( + new ExternalLink(MAIL, "mailto:" + model.getObject().getEmailAddress(), model.getObject().getEmailAddress()) + ); final IModel profileModel = getProfile(); - add(new Label(SKYPE, new NullReplacementModel(LambdaModel.of(profileModel, UserProfile::getSkypeId, UserProfile::setSkypeId), "Not entered"))); + add( + new Label( + SKYPE, + new NullReplacementModel( + LambdaModel.of(profileModel, UserProfile::getSkypeId, UserProfile::setSkypeId), + "Not entered" + ) + ) + ); - add(new Label(PHONE, new NullReplacementModel(LambdaModel.of(profileModel, UserProfile::getPhoneNumber, UserProfile::setPhoneNumber), "Not entered"))); + add( + new Label( + PHONE, + new NullReplacementModel( + LambdaModel.of(profileModel, UserProfile::getPhoneNumber, UserProfile::setPhoneNumber), + "Not entered" + ) + ) + ); - add(new SmartLinkMultiLineLabel(OTHER, new NullReplacementModel(LambdaModel.of(profileModel, UserProfile::getOtherInfo, UserProfile::setOtherInfo), "Not entered"))); + add( + new SmartLinkMultiLineLabel( + OTHER, + new NullReplacementModel( + LambdaModel.of(profileModel, UserProfile::getOtherInfo, UserProfile::setOtherInfo), + "Not entered" + ) + ) + ); WebMarkupContainer employeeWMC = new WebMarkupContainer(EMPLOYEE) { @Override @@ -57,42 +82,53 @@ public class DisplayUserProfilePanel extends GenericPanel { }; add(employeeWMC); - employeeWMC.add(new Label(UNIT, new NullReplacementModel(model.map(User::getUnit).map(Unit::getTitle), "None"))); + employeeWMC.add( + new Label(UNIT, new NullReplacementModel(model.map(User::getUnit).map(Unit::getTitle), "None")) + ); - ListView areas = new AutoHidingListView<>(AREAS, - new ListAdapterModel<>(model.map(User::getActiveResearchAreas))) { + ListView areas = new AutoHidingListView<>( + AREAS, + new ListAdapterModel<>(model.map(User::getActiveResearchAreas)) + ) { @Override protected void populateItem(ListItem item) { item.add(new Label(AREA, item.getModelObject().getTitle())); } }; employeeWMC.add(areas); - employeeWMC.add(new Label(NOAREAS, "None") - .add(new OppositeVisibility(areas))); + employeeWMC.add(new Label(NOAREAS, "None").add(new OppositeVisibility(areas))); - ListView languages = new AutoHidingListView<>(LANGUAGES, new ListAdapterModel<>(LambdaModel.of(model, User::getLanguages, User::setLanguages))) { + ListView languages = new AutoHidingListView<>( + LANGUAGES, + new ListAdapterModel<>(LambdaModel.of(model, User::getLanguages, User::setLanguages)) + ) { @Override protected void populateItem(ListItem item) { item.add(new EnumLabel<>(LANGUAGE, item.getModel())); } }; employeeWMC.add(languages); - employeeWMC.add(new Label(NOLANGUAGES, "None") - .add(new OppositeVisibility(languages))); + employeeWMC.add(new Label(NOLANGUAGES, "None").add(new OppositeVisibility(languages))); GeneralSystemSettings generalSystemSettings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); String profile = ""; - if (generalSystemSettings.getDaisyProfileLinkBaseURL() != null && !generalSystemSettings.getDaisyProfileLinkBaseURL().isEmpty() && model.getObject().getIdentifier() != null) { + if ( + generalSystemSettings.getDaisyProfileLinkBaseURL() != null && + !generalSystemSettings.getDaisyProfileLinkBaseURL().isEmpty() && + model.getObject().getIdentifier() != null + ) { profile = generalSystemSettings.getDaisyProfileLinkBaseURL() + model.getObject().getIdentifier(); } final String finalProfile = profile; - employeeWMC.add(new ExternalLink(DAISYPROFILE, finalProfile) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!finalProfile.isEmpty()); + employeeWMC.add( + new ExternalLink(DAISYPROFILE, finalProfile) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!finalProfile.isEmpty()); + } } - }); + ); } public static final String MAIL = "mail"; diff --git a/view/src/main/java/se/su/dsv/scipro/profile/StudentProfileProgramPanel.java b/view/src/main/java/se/su/dsv/scipro/profile/StudentProfileProgramPanel.java index 732683e62f..6b0e65382c 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/StudentProfileProgramPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/StudentProfileProgramPanel.java @@ -8,6 +8,7 @@ import se.su.dsv.scipro.match.IdeaParticipation; import se.su.dsv.scipro.system.Program; public class StudentProfileProgramPanel extends Panel { + public StudentProfileProgramPanel(String id, IModel model, boolean shorten) { super(id, model); add(new UserLinkPanel(USER, LambdaModel.of(model, IdeaParticipation::getUser, IdeaParticipation::setUser))); diff --git a/view/src/main/java/se/su/dsv/scipro/profile/UserLabel.java b/view/src/main/java/se/su/dsv/scipro/profile/UserLabel.java index 2e594a65df..7e582bdc49 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/UserLabel.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/UserLabel.java @@ -14,6 +14,6 @@ public class UserLabel extends GenericPanel { @Override protected void onInitialize() { super.onInitialize(); - add(new Label("fullName",getModel().map(User::getFullName))); + add(new Label("fullName", getModel().map(User::getFullName))); } } diff --git a/view/src/main/java/se/su/dsv/scipro/profile/UserLinkPanel.java b/view/src/main/java/se/su/dsv/scipro/profile/UserLinkPanel.java index fbdca4abf5..de933469f5 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/UserLinkPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/UserLinkPanel.java @@ -42,10 +42,10 @@ public class UserLinkPanel extends GenericPanel { super.onConfigure(); setVisibilityAllowed(getDefaultModelObject() != null); } + public static final String DIALOGLINK = "dialoglink"; public static final String NAME = "name"; public static final String DIALOG = "modalWindowPlus"; public static final String CONTENT = "body"; public static final String MAILLINK = "maillink"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/profile/UserProfileImage.java b/view/src/main/java/se/su/dsv/scipro/profile/UserProfileImage.java index b75e72ddbc..19170c5873 100644 --- a/view/src/main/java/se/su/dsv/scipro/profile/UserProfileImage.java +++ b/view/src/main/java/se/su/dsv/scipro/profile/UserProfileImage.java @@ -8,8 +8,11 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; public class UserProfileImage extends WebComponent { + public enum Size { - TINY(16), MEDIUM(64), LARGE(128); + TINY(16), + MEDIUM(64), + LARGE(128); private final int pixels; @@ -36,11 +39,12 @@ public class UserProfileImage extends WebComponent { checkComponentTag(tag, "img"); super.onComponentTag(tag); tag.put("src", getImageSrc()); - String cssClass = switch (size) { - case TINY -> "profile-picture-sm"; - case MEDIUM -> "profile-picture-md"; - case LARGE -> "profile-picture-lg"; - }; + String cssClass = + switch (size) { + case TINY -> "profile-picture-sm"; + case MEDIUM -> "profile-picture-md"; + case LARGE -> "profile-picture-lg"; + }; tag.append("class", cssClass, " "); tag.put("alt", "photo"); tag.put("loading", "lazy"); diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/AbstractProjectDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/AbstractProjectDetailsPage.java index 76ddd5cebd..4c76305ffd 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/AbstractProjectDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/AbstractProjectDetailsPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.project.pages; +import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.HORIZONTAL; + +import jakarta.inject.Inject; +import jakarta.servlet.http.Cookie; import org.apache.wicket.RestartResponseException; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; @@ -18,11 +22,6 @@ import se.su.dsv.scipro.project.panels.ProjectSubTabMenuPanel; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import jakarta.servlet.http.Cookie; - -import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.HORIZONTAL; - public abstract class AbstractProjectDetailsPage extends ProjectPage { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractProjectDetailsPage.class); @@ -36,20 +35,19 @@ public abstract class AbstractProjectDetailsPage extends ProjectPage { public AbstractProjectDetailsPage(PageParameters pp) { super(pp); - Long projectId = null; StringValue projectValue = pp.get(PageParameterKeys.MAP.get(Project.class)); if (!projectValue.isNull()) { try { projectId = projectValue.toLongObject(); - } catch (StringValueConversionException ignored){ + } catch (StringValueConversionException ignored) { throw new RestartResponseException(NotFoundPage.class); } /* * Cookie is set when the link to visit this details page is clicked but for it to work - * if a URL is entered directly we set it here too - */ + * if a URL is entered directly we set it here too + */ Cookie c = new Cookie(COOKIE_KEY, projectId.toString()); c.setMaxAge(MAX_AGE); c.setPath("/"); @@ -82,12 +80,14 @@ public abstract class AbstractProjectDetailsPage extends ProjectPage { projectModel = new DetachableServiceModel<>(projectService, projectId); setDefaultModel(projectModel); - add(new ProjectSubTabMenuPanel("projectSub", this.getClass(), getPageParameters(project), projectModel) { - @Override - protected MenuType getMenuType() { - return HORIZONTAL; + add( + new ProjectSubTabMenuPanel("projectSub", this.getClass(), getPageParameters(project), projectModel) { + @Override + protected MenuType getMenuType() { + return HORIZONTAL; + } } - }); + ); add(new ProjectHeaderPanel("projectHeader", projectModel)); } @@ -101,4 +101,4 @@ public abstract class AbstractProjectDetailsPage extends ProjectPage { pp.add(PageParameterKeys.MAP.get(Project.class), project.getId()); return pp; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectDetailsPage.java index 33864f187d..5907ab558d 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectDetailsPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.pages; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -29,8 +30,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.survey.SurveyService; import se.su.dsv.scipro.thesislink.ExternalLinkPanel; -import jakarta.inject.Inject; - public class ProjectDetailsPage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects { public static final String FINAL_THESIS_PANEL = "finalThesisPanel"; @@ -52,60 +51,83 @@ public class ProjectDetailsPage extends AbstractProjectDetailsPage implements Me @Inject private FinalThesisService finalThesisService; - public ProjectDetailsPage(PageParameters pp) { super(pp); - FinalThesis finalThesis = finalThesisService.findByProject(getActiveProject()); boolean finalThesisIsRejected = (finalThesis != null && finalThesis.isRejected()); - shouldFillOutSurvey = surveyService.shouldFillOutSurvey(getActiveProject(), SciProSession.get().getUser()) - && !finalThesisIsRejected; + shouldFillOutSurvey = + surveyService.shouldFillOutSurvey(getActiveProject(), SciProSession.get().getUser()) && + !finalThesisIsRejected; - add(new ExternalResourcesPanel(EXTERNAL_RESOURCES, LambdaModel.of(projectModel, se.su.dsv.scipro.project.Project::getProjectType, se.su.dsv.scipro.project.Project::setProjectType))); + add( + new ExternalResourcesPanel( + EXTERNAL_RESOURCES, + LambdaModel.of( + projectModel, + se.su.dsv.scipro.project.Project::getProjectType, + se.su.dsv.scipro.project.Project::setProjectType + ) + ) + ); add(new ExternalLinkPanel(EXTERNAL_LINK, projectModel)); add(new PeerSummaryPanel(PEER_SUMMARY, projectModel)); add(new LatestEventsPanel(LATEST_EVENTS, projectModel)); add(new FinalThesisPanel(FINAL_THESIS_PANEL, projectModel)); - add(new ProjectStatePanel(PROJECT_STATE_PANEL, projectModel) { - @Override - public boolean isAuthorView() { - return true; + add( + new ProjectStatePanel(PROJECT_STATE_PANEL, projectModel) { + @Override + public boolean isAuthorView() { + return true; + } } - }); + ); add(new OverviewSeminarPanel(FINAL_SEMINAR_NEW, projectModel)); - add(new Label(EXTERNAL_ORGANIZATION, projectModel.map(Project::getExternalOrganization).map(ExternalOrganization::getName)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getDefaultModelObject() != null); + add( + new Label( + EXTERNAL_ORGANIZATION, + projectModel.map(Project::getExternalOrganization).map(ExternalOrganization::getName) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getDefaultModelObject() != null); + } } - }); + ); - add(new UpcomingActivitiesPanel(UPCOMING_ACTIVITIES, projectModel) { - @Override - public boolean isAuthorView() { - return true; + add( + new UpcomingActivitiesPanel(UPCOMING_ACTIVITIES, projectModel) { + @Override + public boolean isAuthorView() { + return true; + } } - }); + ); add(new MilestoneSummaryPanel(MILESTONES, projectModel)); - add(new GroupsOverviewPanel("groups", projectModel, (id, pp1) -> new BookmarkablePageLink<>(id, AuthorGroupPage.class, pp1))); + add( + new GroupsOverviewPanel("groups", projectModel, (id, pp1) -> + new BookmarkablePageLink<>(id, AuthorGroupPage.class, pp1) + ) + ); add(new ChecklistOverviewPanel("checklistOverview", projectModel)); - add(new BookmarkablePageLink( + add( + new BookmarkablePageLink( "surveyReminder", ProjectFinalSurveyPage.class, - ProjectFinalSurveyPage.getPageParameters(getActiveProject())) - { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(shouldFillOutSurvey); + ProjectFinalSurveyPage.getPageParameters(getActiveProject()) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(shouldFillOutSurvey); + } } - }); + ); add(new FinalStepsPanel("final_steps", projectModel)); @@ -118,14 +140,17 @@ public class ProjectDetailsPage extends AbstractProjectDetailsPage implements Me if (shouldFillOutSurvey && getSession().getMetaData(ProjectFinalSurveyPage.SURVEY_VISITED) == null) { getFeedbackMessages().forEach(getSession().getFeedbackMessages()::add); throw new RestartResponseException( - ProjectFinalSurveyPage.class, - ProjectFinalSurveyPage.getPageParameters(getActiveProject())); + ProjectFinalSurveyPage.class, + ProjectFinalSurveyPage.getPageParameters(getActiveProject()) + ); } } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("help_groups_toggle", "click", "$('#help_groups').slideToggle()")); + response.render( + OnEventHeaderItem.forMarkupId("help_groups_toggle", "click", "$('#help_groups').slideToggle()") + ); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFilePage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFilePage.java index 7bd94b2f2f..98d5297605 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFilePage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFilePage.java @@ -8,7 +8,7 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectModule; -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) @ProjectModuleComponent(ProjectModule.FILES) public class ProjectFilePage extends AbstractProjectDetailsPage implements MenuHighlightAuthorMyProjects { @@ -16,5 +16,4 @@ public class ProjectFilePage extends AbstractProjectDetailsPage implements MenuH super(pp); add(new ProjectFilePanel("filePanel", projectModel)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFinalSurveyPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFinalSurveyPage.java index 4974bd22ee..0bbf581a45 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFinalSurveyPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFinalSurveyPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.pages; +import jakarta.inject.Inject; import org.apache.wicket.MetaDataKey; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.basic.Label; @@ -16,13 +17,11 @@ import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.BootstrapCheckBoxMultipleChoice; import se.su.dsv.scipro.components.BootstrapRadioChoice; import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.survey.SurveyAnswer; import se.su.dsv.scipro.survey.Question; import se.su.dsv.scipro.survey.Survey; +import se.su.dsv.scipro.survey.SurveyAnswer; import se.su.dsv.scipro.survey.SurveyService; -import jakarta.inject.Inject; - public class ProjectFinalSurveyPage extends AbstractProjectDetailsPage { static final MetaDataKey SURVEY_VISITED = new MetaDataKey<>() {}; @@ -32,9 +31,11 @@ public class ProjectFinalSurveyPage extends AbstractProjectDetailsPage { public ProjectFinalSurveyPage(final PageParameters pp) { super(pp); - if (!surveyService.shouldFillOutSurvey(getActiveProject(), SciProSession.get().getUser())) { - throw new RestartResponseException(ProjectDetailsPage.class, ProjectDetailsPage.getPageParameters(getActiveProject())); + throw new RestartResponseException( + ProjectDetailsPage.class, + ProjectDetailsPage.getPageParameters(getActiveProject()) + ); } getSession().setMetaData(ProjectFinalSurveyPage.SURVEY_VISITED, Boolean.TRUE); @@ -42,7 +43,10 @@ public class ProjectFinalSurveyPage extends AbstractProjectDetailsPage { final IModel surveyModel = getSurvey(); if (surveyModel.getObject().isSubmitted()) { - throw new RestartResponseException(ProjectDetailsPage.class, ProjectDetailsPage.getPageParameters(getActiveProject())); + throw new RestartResponseException( + ProjectDetailsPage.class, + ProjectDetailsPage.getPageParameters(getActiveProject()) + ); } final Form form = new Form<>("form", surveyModel) { @@ -55,69 +59,86 @@ public class ProjectFinalSurveyPage extends AbstractProjectDetailsPage { }; add(form); - form.add(new ListView<>("questions", surveyModel.map(Survey::getAnswers)) { - { - setReuseItems(true); + form.add( + new ListView<>("questions", surveyModel.map(Survey::getAnswers)) { + { + setReuseItems(true); + } + + @Override + protected void populateItem(final ListItem item) { + final IModel questionText = item + .getModel() + .map(SurveyAnswer::getQuestion) + .map(Question::getText); + + item.add( + new Label("information", questionText) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isType(item, Question.Type.GROUP_HEADING)); + } + } + ); + + final TextArea textArea = new TextArea<>( + "freeText", + LambdaModel.of(item.getModel(), SurveyAnswer::getAnswer, SurveyAnswer::setAnswer) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isType(item, Question.Type.TEXT)); + } + }; + textArea.setLabel(questionText); + item.add(new SimpleFormComponentLabel("textF", textArea)); + item.add(textArea); + + item.add(new Label("textM", questionText)); + item.add( + new BootstrapCheckBoxMultipleChoice<>( + "multipleChoices", + item.getModel().map(SurveyAnswer::getMultipleAnswers), + item.getModel().map(SurveyAnswer::getQuestion).map(Question::getChoices), + new ChoiceRenderer<>() + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isType(item, Question.Type.MULTIPLE_CHOICE)); + } + } + ); + + item.add(new Label("textS", questionText)); + item.add( + new BootstrapRadioChoice<>( + "singleChoice", + LambdaModel.of(item.getModel(), SurveyAnswer::getAnswer, SurveyAnswer::setAnswer), + item.getModel().map(SurveyAnswer::getQuestion).map(Question::getChoices), + new ChoiceRenderer<>() + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isType(item, Question.Type.SINGLE_CHOICE)); + } + } + ); + } + + private boolean isType(final ListItem item, final Question.Type type) { + return (item.getModelObject().getQuestion().getType() == type); + } } - - @Override - protected void populateItem(final ListItem item) { - final IModel questionText = item.getModel().map(SurveyAnswer::getQuestion).map(Question::getText); - - item.add(new Label("information", questionText) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isType(item, Question.Type.GROUP_HEADING)); - } - }); - - final TextArea textArea = new TextArea<>("freeText", LambdaModel.of(item.getModel(), SurveyAnswer::getAnswer, SurveyAnswer::setAnswer)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isType(item, Question.Type.TEXT)); - } - }; - textArea.setLabel(questionText); - item.add(new SimpleFormComponentLabel("textF", textArea)); - item.add(textArea); - - item.add(new Label("textM", questionText)); - item.add(new BootstrapCheckBoxMultipleChoice<>( - "multipleChoices", - item.getModel().map(SurveyAnswer::getMultipleAnswers), - item.getModel().map(SurveyAnswer::getQuestion).map(Question::getChoices), - new ChoiceRenderer<>()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isType(item, Question.Type.MULTIPLE_CHOICE)); - } - }); - - item.add(new Label("textS", questionText)); - item.add(new BootstrapRadioChoice<>( - "singleChoice", - LambdaModel.of(item.getModel(), SurveyAnswer::getAnswer, SurveyAnswer::setAnswer), - item.getModel().map(SurveyAnswer::getQuestion).map(Question::getChoices), - new ChoiceRenderer<>()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isType(item, Question.Type.SINGLE_CHOICE)); - } - }); - } - - private boolean isType(final ListItem item, final Question.Type type) { - return item.getModelObject().getQuestion().getType() == type; - } - }); + ); } private IModel getSurvey() { - return LoadableDetachableModel.of(() -> surveyService.getSurvey(getActiveProject(), SciProSession.get().getUser())); + return LoadableDetachableModel.of(() -> + surveyService.getSurvey(getActiveProject(), SciProSession.get().getUser()) + ); } } - diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFirstMeetingPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFirstMeetingPage.java index da3ade68e2..3cbd6e4d98 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFirstMeetingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectFirstMeetingPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.project.pages; +import jakarta.inject.Inject; +import java.util.Optional; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.basic.MultiLineLabel; @@ -10,16 +12,13 @@ import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.firstmeeting.FirstMeetingService; import se.su.dsv.scipro.firstmeeting.ProjectFirstMeeting; -import jakarta.inject.Inject; -import java.util.Optional; - public class ProjectFirstMeetingPage extends AbstractProjectDetailsPage { + @Inject private FirstMeetingService firstMeetingService; public ProjectFirstMeetingPage(final PageParameters pp) { super(pp); - final IModel> model = new LoadableDetachableModel<>() { @Override protected Optional load() { @@ -28,28 +27,31 @@ public class ProjectFirstMeetingPage extends AbstractProjectDetailsPage { }; final IModel model1 = model.map(x -> x.orElse(null)); - add(new WebMarkupContainer("firstMeeting", model1) { - { - add(new DateLabel("date", model1.map(ProjectFirstMeeting::getDate), DateStyle.DATE)); - add(new DateLabel("time", model1.map(ProjectFirstMeeting::getDate), DateStyle.TIME)); - add(new Label("room", model1.map(ProjectFirstMeeting::getRoom))); - add(new MultiLineLabel("description", model1.map(ProjectFirstMeeting::getDescription))); - } + add( + new WebMarkupContainer("firstMeeting", model1) { + { + add(new DateLabel("date", model1.map(ProjectFirstMeeting::getDate), DateStyle.DATE)); + add(new DateLabel("time", model1.map(ProjectFirstMeeting::getDate), DateStyle.TIME)); + add(new Label("room", model1.map(ProjectFirstMeeting::getRoom))); + add(new MultiLineLabel("description", model1.map(ProjectFirstMeeting::getDescription))); + } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(model.getObject().isPresent()); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(model.getObject().isPresent()); + } } - }); + ); - - add(new WebMarkupContainer("none") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!model.getObject().isPresent()); + add( + new WebMarkupContainer("none") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!model.getObject().isPresent()); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectPage.java index 54727ac570..542c79ecc5 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.pages; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; @@ -9,9 +10,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.springdata.services.UserProfileService; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.AUTHOR}) +@Authorization(authorizedRoles = { Roles.AUTHOR }) public abstract class ProjectPage extends MenuPage { public static final String TAB_MENU = "tabMenu"; @@ -28,12 +27,10 @@ public abstract class ProjectPage extends MenuPage { public ProjectPage(PageParameters pp) { super(pp); - userProfileService.setSelectedRole(SciProSession.get().getUser(), Roles.AUTHOR); - SciProSession.get().setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); + SciProSession.get() + .setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); add(new ProjectTabMenuPanel(TAB_MENU, this.getClass())); } - - } diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectStartPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectStartPage.java index 64afd911b6..c4b8309146 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/ProjectStartPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.project.pages; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; @@ -7,10 +10,6 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.panels.ProjectsOverviewPanel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - public class ProjectStartPage extends ProjectPage { public static final String MAIN_MENU_LABEL = "Author"; diff --git a/view/src/main/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPage.java b/view/src/main/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPage.java index 7dbba5349d..7b484ad283 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPage.java +++ b/view/src/main/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPage.java @@ -8,20 +8,22 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorProjectDetailsPage; import se.su.dsv.scipro.system.User; -public class SupervisorEditProjectPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { +public class SupervisorEditProjectPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { - public SupervisorEditProjectPage(PageParameters pp) { - super(pp); - redirectToHomePageIfUserIsNotSupervisor(); - add(new SupervisorEditProjectPanel("editProjectPanel", projectModel)); - } + public SupervisorEditProjectPage(PageParameters pp) { + super(pp); + redirectToHomePageIfUserIsNotSupervisor(); + add(new SupervisorEditProjectPanel("editProjectPanel", projectModel)); + } - private void redirectToHomePageIfUserIsNotSupervisor() { - Project project = projectModel.getObject(); - User headSupervisor = project.getHeadSupervisor(); - User user = SciProSession.get().getUser(); - if (!headSupervisor.equals(user)) { - setResponsePage(getApplication().getHomePage()); - } - } + private void redirectToHomePageIfUserIsNotSupervisor() { + Project project = projectModel.getObject(); + User headSupervisor = project.getHeadSupervisor(); + User user = SciProSession.get().getUser(); + if (!headSupervisor.equals(user)) { + setResponsePage(getApplication().getHomePage()); + } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanel.java index 0e8c493b3a..ae433b041a 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -11,23 +13,28 @@ import se.su.dsv.scipro.system.ExternalResource; import se.su.dsv.scipro.system.ExternalResourceService; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.util.List; - public class ExternalResourcesPanel extends GenericPanel { + @Inject private ExternalResourceService externalResourceService; public ExternalResourcesPanel(final String id, final IModel model) { super(id, model); - - add(new ListView<>("resources", getResources()) { - @Override - protected void populateItem(final ListItem item) { - IModel resource = item.getModel(); - item.add(new ExternalLink("link", LambdaModel.of(resource, ExternalResource::getUrl, ExternalResource::setUrl), LambdaModel.of(resource, ExternalResource::getLabel, ExternalResource::setLabel))); + add( + new ListView<>("resources", getResources()) { + @Override + protected void populateItem(final ListItem item) { + IModel resource = item.getModel(); + item.add( + new ExternalLink( + "link", + LambdaModel.of(resource, ExternalResource::getUrl, ExternalResource::setUrl), + LambdaModel.of(resource, ExternalResource::getLabel, ExternalResource::setLabel) + ) + ); + } } - }); + ); } private LoadableDetachableModel> getResources() { diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/FinalStepsPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/FinalStepsPanel.java index 95d9fb319a..1faccaea0d 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/FinalStepsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/FinalStepsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.MultiLineLabel; @@ -28,36 +29,39 @@ import se.su.dsv.scipro.reflection.Reflection; import se.su.dsv.scipro.reflection.ReflectionService; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class FinalStepsPanel extends GenericPanel { @Inject private PublicationMetadataService publicationMetadataService; + @Inject private ReflectionService reflectionService; + @Inject private PublishingConsentService publishingConsentService; + @Inject private FinalThesisService finalThesisService; public FinalStepsPanel(String id, IModel projectModel) { super(id, projectModel); - add(new FencedFeedbackPanel("feedback", this)); IModel currentReflection = LoadableDetachableModel.of(() -> - reflectionService.getReflection(projectModel.getObject(), SciProSession.get().getUser())); + reflectionService.getReflection(projectModel.getObject(), SciProSession.get().getUser()) + ); IModel reflectionText = currentReflection - .as(Reflection.Submitted.class) - .map(Reflection.Submitted::reflection); - add(new MultiLineLabel("reflection", reflectionText) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!getDefaultModelObjectAsString().isBlank()); + .as(Reflection.Submitted.class) + .map(Reflection.Submitted::reflection); + add( + new MultiLineLabel("reflection", reflectionText) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); add(new FinalStepsForm("submit_reflection", projectModel, currentReflection)); } @@ -69,6 +73,7 @@ public class FinalStepsPanel extends GenericPanel { } private class FinalStepsForm extends Form { + private final FinalThesisUploadComponent thesisFileUpload; private final IModel publicationMetadataModel; private final IModel currentReflection; @@ -77,27 +82,34 @@ public class FinalStepsPanel extends GenericPanel { public FinalStepsForm(String id, IModel projectModel, IModel currentReflection) { super(id, projectModel); - this.currentReflection = currentReflection; - IModel improvementsNeeded = this.currentReflection.as(Reflection.ImprovementsNeeded.class); + IModel improvementsNeeded = + this.currentReflection.as(Reflection.ImprovementsNeeded.class); IModel oldReflection = improvementsNeeded.map(Reflection.ImprovementsNeeded::oldReflection); - add(new MultiLineLabel("old_reflection", oldReflection) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!getDefaultModelObjectAsString().isBlank()); + add( + new MultiLineLabel("old_reflection", oldReflection) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); - add(new MultiLineLabel("supervisor_comment", improvementsNeeded.map(Reflection.ImprovementsNeeded::commentBySupervisor)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!getDefaultModelObjectAsString().isBlank()); + add( + new MultiLineLabel( + "supervisor_comment", + improvementsNeeded.map(Reflection.ImprovementsNeeded::commentBySupervisor) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!getDefaultModelObjectAsString().isBlank()); + } } - }); + ); reflectionModel = new Model<>(); TextArea reflectionTextArea = new TextArea<>("reflection", reflectionModel) { @@ -111,14 +123,16 @@ public class FinalStepsPanel extends GenericPanel { add(reflectionTextArea); IModel publishingConsent = LoadableDetachableModel.of(() -> - publishingConsentService.getPublishingConsent(getModelObject(), SciProSession.get().getUser())); + publishingConsentService.getPublishingConsent(getModelObject(), SciProSession.get().getUser()) + ); levelModel = new Model<>(publishingConsent.getObject().selected()); FormComponent publishingConsentLevel = new BootstrapRadioChoice<>( - "publishingConsentLevel", - levelModel, - publishingConsent.map(PublishingConsentService.PublishingConsent::available), - new EnumChoiceRenderer<>(this)) { + "publishingConsentLevel", + levelModel, + publishingConsent.map(PublishingConsentService.PublishingConsent::available), + new EnumChoiceRenderer<>(this) + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -132,25 +146,35 @@ public class FinalStepsPanel extends GenericPanel { @Override protected void onConfigure() { super.onConfigure(); - setVisible(finalThesisService.isUploadAllowed(FinalStepsPanel.FinalStepsForm.this.getModelObject())); + setVisible( + finalThesisService.isUploadAllowed(FinalStepsPanel.FinalStepsForm.this.getModelObject()) + ); } }; add(thesisFileUpload); - IModel thesisFileModel = LoadableDetachableModel.of(() -> finalThesisService.getFinalThesisFileDescription(getModelObject())); + IModel thesisFileModel = LoadableDetachableModel.of(() -> + finalThesisService.getFinalThesisFileDescription(getModelObject()) + ); FileDescriptionPanel currentThesisFile = new FileDescriptionPanel("current_thesis_file", thesisFileModel); currentThesisFile.add(new OppositeVisibility(thesisFileUpload)); add(currentThesisFile); - publicationMetadataModel = LoadableDetachableModel.of(() -> publicationMetadataService.getByProject(getModelObject())); + publicationMetadataModel = LoadableDetachableModel.of(() -> + publicationMetadataService.getByProject(getModelObject()) + ); WebMarkupContainer publicationMetadata = new WebMarkupContainer("publication_metadata") { @Override protected void onConfigure() { super.onConfigure(); - setEnabled(finalThesisService.isUploadAllowed(FinalStepsPanel.FinalStepsForm.this.getModelObject())); + setEnabled( + finalThesisService.isUploadAllowed(FinalStepsPanel.FinalStepsForm.this.getModelObject()) + ); } }; add(publicationMetadata); - publicationMetadata.add(new PublicationMetadataFormComponentPanel("publication_metadata_components", publicationMetadataModel)); + publicationMetadata.add( + new PublicationMetadataFormComponentPanel("publication_metadata_components", publicationMetadataModel) + ); } @Override @@ -165,15 +189,24 @@ public class FinalStepsPanel extends GenericPanel { FinalThesisUpload finalThesisUpload = thesisFileUpload.getFinalThesisUpload(); if (finalThesisUpload != null) { finalThesisService.upload( - new WicketProjectFileUpload(finalThesisUpload.fileUpload(), FinalStepsPanel.this.getModelObject()), - finalThesisUpload.englishTitle(), - finalThesisUpload.swedishTitle()); + new WicketProjectFileUpload(finalThesisUpload.fileUpload(), FinalStepsPanel.this.getModelObject()), + finalThesisUpload.englishTitle(), + finalThesisUpload.swedishTitle() + ); success(getString("final_thesis_uploaded")); } - reflectionService.submitReflection(getModelObject(), SciProSession.get().getUser(), reflectionModel.getObject()); + reflectionService.submitReflection( + getModelObject(), + SciProSession.get().getUser(), + reflectionModel.getObject() + ); if (levelModel.getObject() != null) { // level might be null if there is no publishing consent service available - publishingConsentService.setPublishingConsent(getModelObject(), SciProSession.get().getUser(), levelModel.getObject()); + publishingConsentService.setPublishingConsent( + getModelObject(), + SciProSession.get().getUser(), + levelModel.getObject() + ); } publicationMetadataService.save(publicationMetadataModel.getObject()); success(getString("reflection_submitted")); diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/FinalThesisReflectionInstructionsPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/FinalThesisReflectionInstructionsPanel.java index c86cb81149..94783e403d 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/FinalThesisReflectionInstructionsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/FinalThesisReflectionInstructionsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; @@ -11,13 +12,14 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.reflection.ReflectionService; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; - public class FinalThesisReflectionInstructionsPanel extends GenericPanel { + @Inject private ReflectionService reflectionService; + @Inject private FinalThesisService finalThesisService; + @Inject private FinalSeminarService finalSeminarService; @@ -27,57 +29,98 @@ public class FinalThesisReflectionInstructionsPanel extends GenericPanel projectModel) { super(id, projectModel); - - hasSubmittedReflection = LoadableDetachableModel.of(() -> - reflectionService.getSubmittedReflection(projectModel.getObject(), SciProSession.get().getUser()) != null); - hasFinalThesis = LoadableDetachableModel.of(() -> - !finalThesisService.isUploadAllowed(projectModel.getObject())); + hasSubmittedReflection = LoadableDetachableModel.of( + () -> + reflectionService.getSubmittedReflection(projectModel.getObject(), SciProSession.get().getUser()) != + null + ); + hasFinalThesis = LoadableDetachableModel.of(() -> !finalThesisService.isUploadAllowed(projectModel.getObject()) + ); hasHadFinalSeminar = LoadableDetachableModel.of(() -> - finalSeminarService.hasHadFinalSeminar(projectModel.getObject())); - add(new WebMarkupContainer("nothing_done") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!hasHadFinalSeminar.getObject() && !hasFinalThesis.getObject() && !hasSubmittedReflection.getObject()); + finalSeminarService.hasHadFinalSeminar(projectModel.getObject()) + ); + add( + new WebMarkupContainer("nothing_done") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + !hasHadFinalSeminar.getObject() && + !hasFinalThesis.getObject() && + !hasSubmittedReflection.getObject() + ); + } } - }); - add(new WebMarkupContainer("final_seminar_done_no_final_thesis_no_reflection") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasHadFinalSeminar.getObject() && !hasFinalThesis.getObject() && !hasSubmittedReflection.getObject()); + ); + add( + new WebMarkupContainer("final_seminar_done_no_final_thesis_no_reflection") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + hasHadFinalSeminar.getObject() && + !hasFinalThesis.getObject() && + !hasSubmittedReflection.getObject() + ); + } } - }); - add(new WebMarkupContainer("final_seminar_done_final_thesis_done_no_reflection") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasHadFinalSeminar.getObject() && hasFinalThesis.getObject() && !hasSubmittedReflection.getObject()); + ); + add( + new WebMarkupContainer("final_seminar_done_final_thesis_done_no_reflection") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + hasHadFinalSeminar.getObject() && + hasFinalThesis.getObject() && + !hasSubmittedReflection.getObject() + ); + } } - }); - add(new WebMarkupContainer("final_seminar_done_no_final_thesis_done_has_reflection") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(hasHadFinalSeminar.getObject() && !hasFinalThesis.getObject() && hasSubmittedReflection.getObject()); + ); + add( + new WebMarkupContainer("final_seminar_done_no_final_thesis_done_has_reflection") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible( + hasHadFinalSeminar.getObject() && + !hasFinalThesis.getObject() && + hasSubmittedReflection.getObject() + ); + } } - }); - add(new WebMarkupContainer("author_done_supervisor_not_done") { - @Override - protected void onConfigure() { - super.onConfigure(); - boolean projectIsCompleted = projectModel.getObject().getProjectStatus() == ProjectStatus.COMPLETED; - setVisible(hasHadFinalSeminar.getObject() && hasFinalThesis.getObject() && hasSubmittedReflection.getObject() && !projectIsCompleted); + ); + add( + new WebMarkupContainer("author_done_supervisor_not_done") { + @Override + protected void onConfigure() { + super.onConfigure(); + boolean projectIsCompleted = projectModel.getObject().getProjectStatus() == ProjectStatus.COMPLETED; + setVisible( + hasHadFinalSeminar.getObject() && + hasFinalThesis.getObject() && + hasSubmittedReflection.getObject() && + !projectIsCompleted + ); + } } - }); - add(new WebMarkupContainer("all_done") { - @Override - protected void onConfigure() { - super.onConfigure(); - boolean projectIsCompleted = projectModel.getObject().getProjectStatus() == ProjectStatus.COMPLETED; - setVisible(hasHadFinalSeminar.getObject() && hasFinalThesis.getObject() && hasSubmittedReflection.getObject() && projectIsCompleted); + ); + add( + new WebMarkupContainer("all_done") { + @Override + protected void onConfigure() { + super.onConfigure(); + boolean projectIsCompleted = projectModel.getObject().getProjectStatus() == ProjectStatus.COMPLETED; + setVisible( + hasHadFinalSeminar.getObject() && + hasFinalThesis.getObject() && + hasSubmittedReflection.getObject() && + projectIsCompleted + ); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/PartnerAdditionPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/PartnerAdditionPanel.java index 1a2be74a69..4113d9ea0b 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/PartnerAdditionPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/PartnerAdditionPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -13,8 +14,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - public class PartnerAdditionPanel extends Panel { public static final String CO_AUTHOR_LABEL = "coAuthorLabel"; @@ -44,7 +43,6 @@ public class PartnerAdditionPanel extends Panel { private void addAutoCompleteField() { coAuthorField = new AuthorAutoComplete("inputField", coAuthor) { - @Override protected void action(AjaxRequestTarget pTarget, User newSelection) { setVisible(false); @@ -62,13 +60,11 @@ public class PartnerAdditionPanel extends Panel { private void addRemoveAuthorIcon() { removeLink = new AjaxLink<>("link") { - @Override public void onClick(AjaxRequestTarget target) { removeCoAuthor(); target.add(coAuthorContainer); } - }; removeLink.setVisible(coAuthorExists()); coAuthorContainer.add(removeLink); diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanel.java index 8a209c320d..27354399bb 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.project.panels; +import java.util.*; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -18,109 +19,132 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.*; - public class ProjectHeaderPanel extends GenericPanel { - static final String TITLE = "title"; - static final String STATUS = "projectStatus"; - static final String PROJECT_TYPE = "projectType"; - static final String START_DATE = "startDate"; - static final String SUPERVISOR = "headSupervisor"; - static final String AUTHOR_LIST = "authorList"; - static final String AUTHOR = "author"; - static final String CO_SUPERVISOR_LIST = "coSupervisorList"; - static final String CO_SUPERVISOR = "coSupervisor"; - static final String REVIEWER_LIST = "reviewerList"; - static final String REVIEWER = "reviewer"; - static final String EDIT_LINK = "editLink"; - static final String CREDITS = "credits"; + static final String TITLE = "title"; + static final String STATUS = "projectStatus"; + static final String PROJECT_TYPE = "projectType"; + static final String START_DATE = "startDate"; + static final String SUPERVISOR = "headSupervisor"; + static final String AUTHOR_LIST = "authorList"; + static final String AUTHOR = "author"; + static final String CO_SUPERVISOR_LIST = "coSupervisorList"; + static final String CO_SUPERVISOR = "coSupervisor"; + static final String REVIEWER_LIST = "reviewerList"; + static final String REVIEWER = "reviewer"; - public ProjectHeaderPanel(String id, IModel model) { - super(id, model); + static final String EDIT_LINK = "editLink"; + static final String CREDITS = "credits"; - add(new Label(TITLE, model.map(Project::getTitle))); - add(new Label(PROJECT_TYPE, model.map(Project::getProjectTypeName))); - add(new Label(CREDITS, model.map(Project::getCredits)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().getCredits() > 0); - } - }); - add(new Label("researchArea", model.map(Project::getResearchArea).map(ResearchArea::getTitle))); + public ProjectHeaderPanel(String id, IModel model) { + super(id, model); + add(new Label(TITLE, model.map(Project::getTitle))); + add(new Label(PROJECT_TYPE, model.map(Project::getProjectTypeName))); + add( + new Label(CREDITS, model.map(Project::getCredits)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject().getCredits() > 0); + } + } + ); + add(new Label("researchArea", model.map(Project::getResearchArea).map(ResearchArea::getTitle))); - addDetails(); - addEditLink(model); - addMisc(model); + addDetails(); + addEditLink(model); + addMisc(model); - addAuthors(model); - addCoSupervisors(model); - addReviewer(model); - } + addAuthors(model); + addCoSupervisors(model); + addReviewer(model); + } - private void addDetails() { + private void addDetails() { add(new Label(STATUS, getModel().map(Project::getProjectStatus))); } - private void addEditLink(final IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), model.getObject().getId()); + private void addEditLink(final IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), model.getObject().getId()); - BookmarkablePageLink editLink = new BookmarkablePageLink<>(EDIT_LINK, SupervisorEditProjectPage.class, pp) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(isHeadSupervisor(model.getObject())); - } - }; - add(editLink); - } + BookmarkablePageLink editLink = new BookmarkablePageLink<>( + EDIT_LINK, + SupervisorEditProjectPage.class, + pp + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(isHeadSupervisor(model.getObject())); + } + }; + add(editLink); + } - private void addMisc(IModel model) { - add(new Label(START_DATE, model.map(Project::getStartDate))); - add(new Label("expected_end_date", model.map(Project::getExpectedEndDate)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(model.getObject().getExpectedEndDate() != null); - } - }); - add(new UserLinkPanel(SUPERVISOR, LambdaModel.of(model, Project::getHeadSupervisor, Project::setHeadSupervisor))); - } + private void addMisc(IModel model) { + add(new Label(START_DATE, model.map(Project::getStartDate))); + add( + new Label("expected_end_date", model.map(Project::getExpectedEndDate)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(model.getObject().getExpectedEndDate() != null); + } + } + ); + add( + new UserLinkPanel(SUPERVISOR, LambdaModel.of(model, Project::getHeadSupervisor, Project::setHeadSupervisor)) + ); + } - private void addAuthors(IModel model) { - add(new ListView<>(AUTHOR_LIST, new ListAdapterModel<>(LambdaModel.of(model, Project::getProjectParticipants, Project::setProjectParticipants))) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(AUTHOR, item.getModel())); - } - }); - } + private void addAuthors(IModel model) { + add( + new ListView<>( + AUTHOR_LIST, + new ListAdapterModel<>( + LambdaModel.of(model, Project::getProjectParticipants, Project::setProjectParticipants) + ) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(AUTHOR, item.getModel())); + } + } + ); + } - private void addCoSupervisors(IModel model) { - IModel> coSupervisorList = - new ListAdapterModel<>(LambdaModel.of(model, Project::getCoSupervisors, Project::setCoSupervisors)); - add(new AutoHidingListView<>(CO_SUPERVISOR_LIST, coSupervisorList) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(CO_SUPERVISOR, item.getModel())); - } - }); - } + private void addCoSupervisors(IModel model) { + IModel> coSupervisorList = new ListAdapterModel<>( + LambdaModel.of(model, Project::getCoSupervisors, Project::setCoSupervisors) + ); + add( + new AutoHidingListView<>(CO_SUPERVISOR_LIST, coSupervisorList) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(CO_SUPERVISOR, item.getModel())); + } + } + ); + } - private void addReviewer(IModel model) { - add(new AutoHidingListView<>(REVIEWER_LIST, new ListAdapterModel<>(LambdaModel.of(model, Project::getReviewers, Project::setReviewers))) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLinkPanel(REVIEWER, item.getModel())); - } - }); - } + private void addReviewer(IModel model) { + add( + new AutoHidingListView<>( + REVIEWER_LIST, + new ListAdapterModel<>(LambdaModel.of(model, Project::getReviewers, Project::setReviewers)) + ) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLinkPanel(REVIEWER, item.getModel())); + } + } + ); + } - private boolean isHeadSupervisor(Project project) { - User headSupervisor = project.getHeadSupervisor(); - User user = SciProSession.get().getUser(); - return headSupervisor.equals(user); - } + private boolean isHeadSupervisor(Project project) { + User headSupervisor = project.getHeadSupervisor(); + User user = SciProSession.get().getUser(); + return headSupervisor.equals(user); + } } diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanel.java index d9b2cb547e..ff85b3365b 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -18,10 +21,6 @@ import se.su.dsv.scipro.peer.PeerPortalPage; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.pages.*; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class ProjectSubTabMenuPanel extends AbstractMenuPanel { public static final String FINAL_SEMINAR = "Final seminar"; @@ -37,13 +36,19 @@ public class ProjectSubTabMenuPanel extends AbstractMenuPanel { @Inject private FinalSeminarService finalSeminarService; + @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; final PageParameters projectParams; final IModel active; - public ProjectSubTabMenuPanel(String id, Class containerClass, PageParameters projectParams, IModel active) { + public ProjectSubTabMenuPanel( + String id, + Class containerClass, + PageParameters projectParams, + IModel active + ) { super(id, AbstractProjectDetailsPage.class, containerClass); this.projectParams = projectParams; this.active = active; @@ -61,7 +66,9 @@ public class ProjectSubTabMenuPanel extends AbstractMenuPanel { if (milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate()) != 0) { itemList.add(new MenuItem(MILESTONES, ProjectMileStonePage.class, projectParams)); } - itemList.add(new MenuItem(ACTIVITY_PLAN, ProjectActivityPlanPage.class, MenuHighlightActivityPlan.class, projectParams)); + itemList.add( + new MenuItem(ACTIVITY_PLAN, ProjectActivityPlanPage.class, MenuHighlightActivityPlan.class, projectParams) + ); itemList.add(new MenuItem(FIRST_MEETING, ProjectFirstMeetingPage.class, projectParams)); itemList.add(new MenuItem(FILES, ProjectFilePage.class, projectParams)); itemList.add(new MenuItem(FORUM, ProjectForumBasePage.class, MenuHighlightForum.class, projectParams)); @@ -69,7 +76,14 @@ public class ProjectSubTabMenuPanel extends AbstractMenuPanel { if (finalSeminarService.findByProject(project) != null) { itemList.add(new MenuItem(FINAL_SEMINAR, ProjectFinalSeminarPage.class, projectParams)); } - itemList.add(new MenuItem(OPPOSITION_ACTIVE_PARTICIPATION, ProjectOppositionPage.class, MenuHighlightAuthorOpposition.class, projectParams)); + itemList.add( + new MenuItem( + OPPOSITION_ACTIVE_PARTICIPATION, + ProjectOppositionPage.class, + MenuHighlightAuthorOpposition.class, + projectParams + ) + ); return itemList; } @@ -77,5 +91,4 @@ public class ProjectSubTabMenuPanel extends AbstractMenuPanel { protected MenuType getMenuType() { return MenuType.TAB_MULTIPLE_ROWS; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanel.java index 2f4456961a..c13cead68d 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.Page; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAuthorFinalSeminars; @@ -18,18 +22,15 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - public class ProjectTabMenuPanel extends AbstractMenuPanel { public static final String ALL_FINAL_SEMINARS = "All Final Seminars"; public static final String IDEAS = "Ideas"; public static final String MY_PROJECT_S = "My projects"; + @Inject private ProjectService projectService; + @Inject private ProjectTypeService projectTypeService; @@ -46,7 +47,13 @@ public class ProjectTabMenuPanel extends AbstractMenuPanel { itemList.add(new MenuItem(IDEAS, ProjectIdeaStartPage.class, MenuHighlightProjectIdeas.class)); } if (studentHasProjectWithDegreeType()) { - itemList.add(new MenuItem(ALL_FINAL_SEMINARS, FinalSeminarProjectListPage.class, MenuHighlightAuthorFinalSeminars.class)); + itemList.add( + new MenuItem( + ALL_FINAL_SEMINARS, + FinalSeminarProjectListPage.class, + MenuHighlightAuthorFinalSeminars.class + ) + ); } return itemList; } @@ -69,5 +76,4 @@ public class ProjectTabMenuPanel extends AbstractMenuPanel { protected MenuType getMenuType() { return MenuType.TAB_MULTIPLE_ROWS; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanel.java index 035e923bd6..872f843c6a 100755 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -23,12 +28,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - public class ProjectsOverviewPanel extends GenericPanel> { public static final String TABLE_CONTAINER = "tableContainer"; @@ -36,6 +35,7 @@ public class ProjectsOverviewPanel extends GenericPanel> { @Inject private ProjectService projectService; + private ProjectService.Filter filter = new ProjectService.Filter(); private WebMarkupContainer container; @@ -55,13 +55,15 @@ public class ProjectsOverviewPanel extends GenericPanel> { } private void setUpNoActiveProjectsLabel() { - container.add(new Label(NO_ACTIVE_PROJECTS_LABEL, "You don't have any active projects") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!hasActiveProject() && !hasCompletedProject()); + container.add( + new Label(NO_ACTIVE_PROJECTS_LABEL, "You don't have any active projects") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!hasActiveProject() && !hasCompletedProject()); + } } - }); + ); } private boolean hasActiveProject() { @@ -93,63 +95,81 @@ public class ProjectsOverviewPanel extends GenericPanel> { } private void setUpStatusFilter() { - add(new AjaxCheckBoxMultipleChoice<>("statuses", LambdaModel.of(filter::getStatuses, filter::setStatuses), Arrays.asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(container); + add( + new AjaxCheckBoxMultipleChoice<>( + "statuses", + LambdaModel.of(filter::getStatuses, filter::setStatuses), + Arrays.asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(container); + } } - }); + ); } private void setUpNoProjectLabel() { - container.add(new Label("emptyLabel", "You don't have any projects with the selected project status.") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().isEmpty() && (hasActiveProject() || hasCompletedProject())); + container.add( + new Label("emptyLabel", "You don't have any projects with the selected project status.") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject().isEmpty() && (hasActiveProject() || hasCompletedProject())); + } } - }); + ); } private void setUpProjectList() { - container.add(new ListView<>("listView", getModel()) { - @Override - protected void populateItem(ListItem item) { - Project p = item.getModelObject(); + container.add( + new ListView<>("listView", getModel()) { + @Override + protected void populateItem(ListItem item) { + Project p = item.getModelObject(); - if (p.getStateOfMind() == StateOfMind.FINE) { - item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_GREEN)); - } else if (p.getStateOfMind() == StateOfMind.NEUTRAL) { - item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_YELLOW)); - } else { - item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_RED)); - } - - item.add(new Label("projectType.name", item.getModel().map(Project::getProjectTypeName))); - - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), p.getId()); - BookmarkablePageLink projectLink = new BookmarkablePageLink<>("projectLink", ProjectDetailsPage.class, pp); - Label title = new Label("title", p.getTitle().length() < 31 ? p.getTitle() : p.getTitle().substring(0, 31) + "..."); - title.add(new AttributeAppender("title", Model.of(p.getTitle()))); - projectLink.add(title); - item.add(projectLink); - - boolean first = true; - StringBuilder authors = new StringBuilder(); - for (User user : p.getProjectParticipants()) { - if (first) { - first = false; - authors.append(user.getFirstName()).append(' ').append(user.getLastName()); + if (p.getStateOfMind() == StateOfMind.FINE) { + item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_GREEN)); + } else if (p.getStateOfMind() == StateOfMind.NEUTRAL) { + item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_YELLOW)); } else { - authors.append(", ").append(user.getFirstName()).append(' ').append(user.getLastName()); + item.add(new ImageObject("state", ImageObject.TWENTYFOUR, ImageObject.LIGHT_RED)); } + + item.add(new Label("projectType.name", item.getModel().map(Project::getProjectTypeName))); + + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), p.getId()); + BookmarkablePageLink projectLink = new BookmarkablePageLink<>( + "projectLink", + ProjectDetailsPage.class, + pp + ); + Label title = new Label( + "title", + p.getTitle().length() < 31 ? p.getTitle() : p.getTitle().substring(0, 31) + "..." + ); + title.add(new AttributeAppender("title", Model.of(p.getTitle()))); + projectLink.add(title); + item.add(projectLink); + + boolean first = true; + StringBuilder authors = new StringBuilder(); + for (User user : p.getProjectParticipants()) { + if (first) { + first = false; + authors.append(user.getFirstName()).append(' ').append(user.getLastName()); + } else { + authors.append(", ").append(user.getFirstName()).append(' ').append(user.getLastName()); + } + } + item.add(new Label("authors", authors)); + item.add(new Label("supervisor", p.getHeadSupervisor().getFullName())); + item.add(new EnumLabel<>("projectStatus", item.getModel().map(Project::getProjectStatus))); + add(item); } - item.add(new Label("authors", authors)); - item.add(new Label("supervisor", p.getHeadSupervisor().getFullName())); - item.add(new EnumLabel<>("projectStatus", item.getModel().map(Project::getProjectStatus))); - add(item); } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanel.java b/view/src/main/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanel.java index ae4659133a..804b79b840 100644 --- a/view/src/main/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.project.panels; +import jakarta.inject.Inject; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; @@ -21,76 +24,85 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.ResearchAreaService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.time.LocalDate; -import java.util.*; - public class SupervisorEditProjectPanel extends GenericPanel { - public static final String TITLE = "title"; + public static final String TITLE = "title"; public static final String CO_SUPERVISORS = "co_supervisors"; public static final String FORM = "form"; public static final String FEEDBACK = "feedback"; - @Inject - private ProjectService projectService; - @Inject - ResearchAreaService researchAreaService; + @Inject + private ProjectService projectService; - private AddUsersPanel coSupervisors; + @Inject + ResearchAreaService researchAreaService; - public SupervisorEditProjectPanel(String id, IModel projectIModel) { - super(id, projectIModel); - Form form = new UpdateProjectForm(FORM, projectIModel); - add(form); + private AddUsersPanel coSupervisors; + + public SupervisorEditProjectPanel(String id, IModel projectIModel) { + super(id, projectIModel); + Form form = new UpdateProjectForm(FORM, projectIModel); + add(form); add(new InfoPanel("infoPanel", new ResourceModel("info.text"))); - } + } - private class UpdateProjectForm extends Form { + private class UpdateProjectForm extends Form { - public UpdateProjectForm(String form, IModel projectIModel) { - super(form, projectIModel); - initComponents(); - } + public UpdateProjectForm(String form, IModel projectIModel) { + super(form, projectIModel); + initComponents(); + } - @Override - public void onSubmit() { - Project project = getModelObject(); - project.setCoSupervisors(updateProjectFollowers()); - project = projectService.save(project); - setModelObject(project); - info(getString("successfully_updated")); - } + @Override + public void onSubmit() { + Project project = getModelObject(); + project.setCoSupervisors(updateProjectFollowers()); + project = projectService.save(project); + setModelObject(project); + info(getString("successfully_updated")); + } - private void initComponents() { - add(new RequiredTextField<>(TITLE, LambdaModel.of(getModel(), Project::getTitle, Project::setTitle))); - TextField startDate = new TextField<>("startDate", LambdaModel.of(getModel(), Project::getStartDate, Project::setStartDate), LocalDate.class); - startDate.add(new BootstrapDatePicker()); - startDate.setRequired(true); - add(startDate); - final TextField expectedEndDate = new TextField<>( - "expected_end_date", - LambdaModel.of(getModel(), Project::getExpectedEndDate, Project::setExpectedEndDate), - LocalDate.class); - expectedEndDate.add(new BootstrapDatePicker()); - add(expectedEndDate); - add(new DatesValidator(startDate, expectedEndDate)); - coSupervisors = new AddUsersPanel(CO_SUPERVISORS, new SetModel<>(new HashSet<>(getModel().getObject().getCoSupervisors())), AddUsersPanel.LookFor.EMPLOYEES); - add(coSupervisors); - add(new DropDownChoice<>( - "researchArea", - LambdaModel.of(getModel(), Project::getResearchArea, Project::setResearchArea), - new ResearchAreasModel(researchAreaService), - new ResearchAreaChoiceRenderer(this))); + private void initComponents() { + add(new RequiredTextField<>(TITLE, LambdaModel.of(getModel(), Project::getTitle, Project::setTitle))); + TextField startDate = new TextField<>( + "startDate", + LambdaModel.of(getModel(), Project::getStartDate, Project::setStartDate), + LocalDate.class + ); + startDate.add(new BootstrapDatePicker()); + startDate.setRequired(true); + add(startDate); + final TextField expectedEndDate = new TextField<>( + "expected_end_date", + LambdaModel.of(getModel(), Project::getExpectedEndDate, Project::setExpectedEndDate), + LocalDate.class + ); + expectedEndDate.add(new BootstrapDatePicker()); + add(expectedEndDate); + add(new DatesValidator(startDate, expectedEndDate)); + coSupervisors = new AddUsersPanel( + CO_SUPERVISORS, + new SetModel<>(new HashSet<>(getModel().getObject().getCoSupervisors())), + AddUsersPanel.LookFor.EMPLOYEES + ); + add(coSupervisors); + add( + new DropDownChoice<>( + "researchArea", + LambdaModel.of(getModel(), Project::getResearchArea, Project::setResearchArea), + new ResearchAreasModel(researchAreaService), + new ResearchAreaChoiceRenderer(this) + ) + ); - FeedbackPanel feedbackPanel = new FeedbackPanel(FEEDBACK); - add(feedbackPanel); + FeedbackPanel feedbackPanel = new FeedbackPanel(FEEDBACK); + add(feedbackPanel); } private SortedSet updateProjectFollowers() { - SortedSet projectFollowers = new TreeSet<>(new User.ByNameComparator()); - projectFollowers.addAll(coSupervisors.getModelObject()); - return projectFollowers; - } - } + SortedSet projectFollowers = new TreeSet<>(new User.ByNameComparator()); + projectFollowers.addAll(coSupervisors.getModelObject()); + return projectFollowers; + } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPage.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPage.java index 76abb64658..64e9aaa4ad 100755 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.projectpartner; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -11,9 +12,7 @@ import se.su.dsv.scipro.match.AbstractAdminMatchPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminProjectPartnerPage extends AbstractAdminMatchPage { @Inject @@ -29,11 +28,19 @@ public class AdminProjectPartnerPage extends AbstractAdminMatchPage { info("Settings saved"); } }; - daysForm.add(new TextField<>("amountOfDaysField", LambdaModel.of(daysForm.getModel(), GeneralSystemSettings::getProjectPartnerDaysToLive, GeneralSystemSettings::setProjectPartnerDaysToLive), Integer.class)); + daysForm.add( + new TextField<>( + "amountOfDaysField", + LambdaModel.of( + daysForm.getModel(), + GeneralSystemSettings::getProjectPartnerDaysToLive, + GeneralSystemSettings::setProjectPartnerDaysToLive + ), + Integer.class + ) + ); add(daysForm); add(new ProjectPartnerPanel("ppanel")); - - } private LoadableDetachableModel getSettings() { @@ -44,5 +51,4 @@ public class AdminProjectPartnerPage extends AbstractAdminMatchPage { } }; } - } diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerDataProvider.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerDataProvider.java index 14be7e30b7..afc21042d4 100755 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerDataProvider.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerDataProvider.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.projectpartner; +import java.util.Iterator; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.match.ApplicationPeriod; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectType; - -import java.util.Iterator; +import se.su.dsv.scipro.system.Sort; public class ProjectPartnerDataProvider implements IDataProvider { @@ -23,7 +22,12 @@ public class ProjectPartnerDataProvider implements IDataProvider model.detach(); } - public ProjectPartnerDataProvider(final ProjectPartnerService projectPartnerService, int days, final IModel applicationPeriod, final IModel model) { + public ProjectPartnerDataProvider( + final ProjectPartnerService projectPartnerService, + int days, + final IModel applicationPeriod, + final IModel model + ) { this.projectPartnerService = projectPartnerService; this.days = days; this.applicationPeriod = applicationPeriod; @@ -33,7 +37,9 @@ public class ProjectPartnerDataProvider implements IDataProvider @Override public Iterator iterator(long first, long count) { final PageRequest pageRequest = new PageRequest(first, count, new Sort(Sort.Direction.DESC, "dateCreated")); - return projectPartnerService.getProjectPartnerInSpan(days, applicationPeriod.getObject(), model.getObject(), pageRequest).iterator(); + return projectPartnerService + .getProjectPartnerInSpan(days, applicationPeriod.getObject(), model.getObject(), pageRequest) + .iterator(); } @Override @@ -45,5 +51,4 @@ public class ProjectPartnerDataProvider implements IDataProvider public IModel model(ProjectPartner object) { return new DetachableServiceModel<>(projectPartnerService, object); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPage.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPage.java index ffb39e325e..a70588801a 100755 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.projectpartner; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -31,9 +33,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; - public class ProjectPartnerPage extends AbstractIdeaProjectPage implements MenuHighlightProjectIdeas { public static final int ITEMS_PER_PAGE = 5; @@ -42,14 +41,15 @@ public class ProjectPartnerPage extends AbstractIdeaProjectPage implements MenuH @Inject private ProjectPartnerService projectPartnerService; + @Inject private GeneralSystemSettingsService generalSystemSettingsService; + @Inject private ApplicationPeriodService applicationPeriodService; public ProjectPartnerPage(PageParameters pp) { super(pp); - final IModel applicationPeriod = new DetachableServiceModel<>(applicationPeriodService); final WebMarkupContainer panelContainer = new WebMarkupContainer("panels") { @Override @@ -62,59 +62,97 @@ public class ProjectPartnerPage extends AbstractIdeaProjectPage implements MenuH add(panelContainer); final GeneralSystemSettings settings = generalSystemSettingsService.getGeneralSystemSettingsInstance(); panelContainer.add(new FeedbackPanel("feedback")); - add(new AjaxDropDownChoice<>("applicationPeriod", applicationPeriod, futureApplicationPeriods(), new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId)) { - @Override - public void onNewSelection(final AjaxRequestTarget target, final ApplicationPeriod objectSelected) { - target.add(panelContainer); - } - }); - final IModel> matchableTypes = getMatchableTypes(new ListAdapterModel<>(LambdaModel.of(applicationPeriod, ApplicationPeriod::getProjectTypes, ApplicationPeriod::setProjectTypes))); - panelContainer.add(new ListView<>("ads", matchableTypes) { - @Override - protected void populateItem(final ListItem item) { - WebMarkupContainer container = new WebMarkupContainer("listContainer"); - ProjectPartnerDataProvider projectPartnerDataProvider = - new ProjectPartnerDataProvider(projectPartnerService, settings.getProjectPartnerDaysToLive(), applicationPeriod, item.getModel()); - final DataView dataView = new DataView<>("list", projectPartnerDataProvider, ITEMS_PER_PAGE) { - @Override - protected void populateItem(Item item) { - item.add(new Label("exname", item.getModel().map(ProjectPartner::getUser).map(User::getFullName))); - item.add(new Label("exmail", item.getModel().map(ProjectPartner::getUser).map(User::getEmailAddress))); - item.add(new DateLabel("exdate", item.getModel().map(ProjectPartner::getDateCreated))); - item.add(new MultiLineLabel("exinfoText", item.getModel().map(ProjectPartner::getInfotext))); - item.add(new AjaxLink<>("remove", item.getModel()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().getUser().equals(loggedInUser())); - } - - @Override - public void onClick(AjaxRequestTarget target) { - projectPartnerService.remove(getModelObject()); - panelContainer.info(getString("partner_ad_removed")); - target.add(panelContainer); - } - }); - } - }; - container.add(dataView); - container.setOutputMarkupId(true); - PagingNavigator pagingNavigator = new AjaxPagingNavigator("navigator", dataView); - container.add(pagingNavigator); - item.add(container); - final String href = item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); - item.add(AttributeModifier.replace("id", href)); - if (item.getIndex() == 0) { - item.add(ACTIVE_CLASS); + add( + new AjaxDropDownChoice<>( + "applicationPeriod", + applicationPeriod, + futureApplicationPeriods(), + new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId) + ) { + @Override + public void onNewSelection(final AjaxRequestTarget target, final ApplicationPeriod objectSelected) { + target.add(panelContainer); } } - }); + ); + final IModel> matchableTypes = getMatchableTypes( + new ListAdapterModel<>( + LambdaModel.of( + applicationPeriod, + ApplicationPeriod::getProjectTypes, + ApplicationPeriod::setProjectTypes + ) + ) + ); + panelContainer.add( + new ListView<>("ads", matchableTypes) { + @Override + protected void populateItem(final ListItem item) { + WebMarkupContainer container = new WebMarkupContainer("listContainer"); + ProjectPartnerDataProvider projectPartnerDataProvider = new ProjectPartnerDataProvider( + projectPartnerService, + settings.getProjectPartnerDaysToLive(), + applicationPeriod, + item.getModel() + ); + final DataView dataView = new DataView<>( + "list", + projectPartnerDataProvider, + ITEMS_PER_PAGE + ) { + @Override + protected void populateItem(Item item) { + item.add( + new Label("exname", item.getModel().map(ProjectPartner::getUser).map(User::getFullName)) + ); + item.add( + new Label( + "exmail", + item.getModel().map(ProjectPartner::getUser).map(User::getEmailAddress) + ) + ); + item.add(new DateLabel("exdate", item.getModel().map(ProjectPartner::getDateCreated))); + item.add( + new MultiLineLabel("exinfoText", item.getModel().map(ProjectPartner::getInfotext)) + ); + item.add( + new AjaxLink<>("remove", item.getModel()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject().getUser().equals(loggedInUser())); + } + + @Override + public void onClick(AjaxRequestTarget target) { + projectPartnerService.remove(getModelObject()); + panelContainer.info(getString("partner_ad_removed")); + target.add(panelContainer); + } + } + ); + } + }; + container.add(dataView); + container.setOutputMarkupId(true); + PagingNavigator pagingNavigator = new AjaxPagingNavigator("navigator", dataView); + container.add(pagingNavigator); + item.add(container); + final String href = item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); + item.add(AttributeModifier.replace("id", href)); + if (item.getIndex() == 0) { + item.add(ACTIVE_CLASS); + } + } + } + ); panelContainer.add(new InfoPanel("infoPanel", new ResourceModel("info.text"))); - Form form = new Form<>("projectPartnerForm", - new DetachableServiceModel<>(projectPartnerService, new ProjectPartner(SciProSession.get().getUser()))) { + Form form = new Form<>( + "projectPartnerForm", + new DetachableServiceModel<>(projectPartnerService, new ProjectPartner(SciProSession.get().getUser())) + ) { @Override protected void onSubmit() { getModelObject().setApplicationPeriod(applicationPeriod.getObject()); @@ -122,27 +160,40 @@ public class ProjectPartnerPage extends AbstractIdeaProjectPage implements MenuH projectPartnerService.save(getModelObject()); } }; - TextArea infoText = new TextArea<>("infotext", LambdaModel.of(form.getModel(), ProjectPartner::getInfotext, ProjectPartner::setInfotext)); + TextArea infoText = new TextArea<>( + "infotext", + LambdaModel.of(form.getModel(), ProjectPartner::getInfotext, ProjectPartner::setInfotext) + ); infoText.setRequired(true); form.add(infoText); - final RadioChoice projectTypeChoice = - new BootstrapRadioChoice<>("projectType",LambdaModel.of(form.getModel(), ProjectPartner::getProjectType, ProjectPartner::setProjectType), matchableTypes, new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)); + final RadioChoice projectTypeChoice = new BootstrapRadioChoice<>( + "projectType", + LambdaModel.of(form.getModel(), ProjectPartner::getProjectType, ProjectPartner::setProjectType), + matchableTypes, + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ); projectTypeChoice.setRequired(true); form.add(projectTypeChoice); panelContainer.add(form); - panelContainer.add(new ListView<>("adChoice", matchableTypes) { - @Override - protected void populateItem(final ListItem item) { - final String href = "#" + item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); - final ExternalLink tab = new ExternalLink("tabLink", Model.of(href), item.getModel().map(ProjectType::getName)); - if (item.getIndex() == 0) { - item.add(AttributeAppender.append("class", "active")); - tab.add(AttributeAppender.append("class", "active")); + panelContainer.add( + new ListView<>("adChoice", matchableTypes) { + @Override + protected void populateItem(final ListItem item) { + final String href = "#" + item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); + final ExternalLink tab = new ExternalLink( + "tabLink", + Model.of(href), + item.getModel().map(ProjectType::getName) + ); + if (item.getIndex() == 0) { + item.add(AttributeAppender.append("class", "active")); + tab.add(AttributeAppender.append("class", "active")); + } + item.add(tab); } - item.add(tab); } - }); + ); } private IModel> futureApplicationPeriods() { @@ -162,4 +213,4 @@ public class ProjectPartnerPage extends AbstractIdeaProjectPage implements MenuH } }; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPanel.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPanel.java index 123f641172..b63621e4ba 100755 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.projectpartner; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; @@ -25,74 +27,101 @@ import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import jakarta.inject.Inject; -import java.util.List; - public class ProjectPartnerPanel extends Panel { public static final int ITEMS_PER_PAGE = 5; @Inject private ProjectPartnerService projectPartnerService; + @Inject private ProjectTypeService projectTypeService; public ProjectPartnerPanel(String id) { super(id); - final IModel> matchableTypes = getMatchableTypes(); - add(new ListView<>("tabs", matchableTypes) { - @Override - protected void populateItem(final ListItem item) { - final String href = "#" + item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); - final ExternalLink tab = new ExternalLink("tabLink", Model.of(href), item.getModel().map(ProjectType::getName)); - if (item.getIndex() == 0) { - item.add(AttributeAppender.append("class", "active")); - tab.add(AttributeAppender.append("class", "active")); - } - item.add(tab); - } - }); - - add(new ListView<>("types", matchableTypes) { - @Override - protected void populateItem(final ListItem item2) { - final IModel applicationPeriod = Model.of((ApplicationPeriod) null); - ProjectPartnerDataProvider projectPartnerDataProvider = new ProjectPartnerDataProvider(projectPartnerService, 0, applicationPeriod, item2.getModel()); - - final WebMarkupContainer wmc = new WebMarkupContainer("listContainer"); - - final DataView dataView = new DataView<>("list", projectPartnerDataProvider, ITEMS_PER_PAGE) { - @Override - protected void populateItem(final Item item) { - item.add(new Label("exname", item.getModel().map(ProjectPartner::getUser).map(User::getFullName))); - item.add(new Label("exmail", item.getModel().map(ProjectPartner::getUser).map(User::getEmailAddress))); - item.add(new DateLabel("exdate", item.getModel().map(ProjectPartner::getDateCreated))); - item.add(new MultiLineLabel("exinfoText", item.getModel().map(ProjectPartner::getInfotext))); - item.add(new AjaxConfirmationLink("delete", "Are you sure you want to remove this project partner application?") { - @Override - public void onClick(AjaxRequestTarget target) { - ProjectPartner temp = item.getModelObject(); - projectPartnerService.delete(temp.getId()); - target.add(wmc); - - } - }); + add( + new ListView<>("tabs", matchableTypes) { + @Override + protected void populateItem(final ListItem item) { + final String href = "#" + item.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); + final ExternalLink tab = new ExternalLink( + "tabLink", + Model.of(href), + item.getModel().map(ProjectType::getName) + ); + if (item.getIndex() == 0) { + item.add(AttributeAppender.append("class", "active")); + tab.add(AttributeAppender.append("class", "active")); } - }; - - wmc.setOutputMarkupId(true); - wmc.add(dataView); - wmc.add(new AjaxPagingNavigator("navigator", dataView)); - item2.add(wmc); - final String href = item2.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); - item2.add(AttributeModifier.replace("id", href)); - if (item2.getIndex() == 0) { - item2.add(AttributeAppender.append("class", "active")); + item.add(tab); } } - }); + ); + + add( + new ListView<>("types", matchableTypes) { + @Override + protected void populateItem(final ListItem item2) { + final IModel applicationPeriod = Model.of((ApplicationPeriod) null); + ProjectPartnerDataProvider projectPartnerDataProvider = new ProjectPartnerDataProvider( + projectPartnerService, + 0, + applicationPeriod, + item2.getModel() + ); + + final WebMarkupContainer wmc = new WebMarkupContainer("listContainer"); + + final DataView dataView = new DataView<>( + "list", + projectPartnerDataProvider, + ITEMS_PER_PAGE + ) { + @Override + protected void populateItem(final Item item) { + item.add( + new Label("exname", item.getModel().map(ProjectPartner::getUser).map(User::getFullName)) + ); + item.add( + new Label( + "exmail", + item.getModel().map(ProjectPartner::getUser).map(User::getEmailAddress) + ) + ); + item.add(new DateLabel("exdate", item.getModel().map(ProjectPartner::getDateCreated))); + item.add( + new MultiLineLabel("exinfoText", item.getModel().map(ProjectPartner::getInfotext)) + ); + item.add( + new AjaxConfirmationLink( + "delete", + "Are you sure you want to remove this project partner application?" + ) { + @Override + public void onClick(AjaxRequestTarget target) { + ProjectPartner temp = item.getModelObject(); + projectPartnerService.delete(temp.getId()); + target.add(wmc); + } + } + ); + } + }; + + wmc.setOutputMarkupId(true); + wmc.add(dataView); + wmc.add(new AjaxPagingNavigator("navigator", dataView)); + item2.add(wmc); + final String href = item2.getModelObject().getName().toLowerCase().replaceAll("[^a-z]", ""); + item2.add(AttributeModifier.replace("id", href)); + if (item2.getIndex() == 0) { + item2.add(AttributeAppender.append("class", "active")); + } + } + } + ); } private IModel> getMatchableTypes() { diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPage.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPage.java index d10654a5d0..836bcdb285 100644 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPage.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.projectpartner; +import jakarta.inject.Inject; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.LambdaChoiceRenderer; @@ -13,12 +16,9 @@ import se.su.dsv.scipro.match.ApplicationPeriodService; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import jakarta.inject.Inject; -import java.util.Comparator; -import java.util.List; - -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class SinglesPage extends AbstractAdminMatchPage { + @Inject private ApplicationPeriodService applicationPeriodService; @@ -36,16 +36,19 @@ public class SinglesPage extends AbstractAdminMatchPage { singles.setOutputMarkupPlaceholderTag(true); add(singles); - add(new AjaxDropDownChoice<>( + add( + new AjaxDropDownChoice<>( "applicationPeriod", applicationPeriod, allPeriods, - new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId)) { - @Override - public void onNewSelection(AjaxRequestTarget target, ApplicationPeriod objectSelected) { - target.add(singles); + new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId) + ) { + @Override + public void onNewSelection(AjaxRequestTarget target, ApplicationPeriod objectSelected) { + target.add(singles); + } } - }); + ); } private IModel> getAllApplicationPeriods() { diff --git a/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPanel.java b/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPanel.java index 929cc15045..4b9965766c 100644 --- a/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/projectpartner/SinglesPanel.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.projectpartner; +import static java.util.Comparator.comparing; +import static java.util.Comparator.reverseOrder; + +import jakarta.inject.Inject; +import java.util.List; +import java.util.Objects; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.list.ListItem; @@ -18,52 +24,54 @@ import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.ProjectType; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Objects; - -import static java.util.Comparator.comparing; -import static java.util.Comparator.reverseOrder; - public class SinglesPanel extends GenericPanel { + @Inject private ProjectPartnerService projectPartnerService; public SinglesPanel(final String id, final IModel model) { super(id, model); - final IModel> singles = getSingles(); - add(new BootstrapTabs<>("tabs", getMatchableTypes()) { - @Override - protected WebMarkupContainer getContent(final String id, final IModel model) { - return new Tab(id, getSinglesForType(singles, model)); - } + add( + new BootstrapTabs<>("tabs", getMatchableTypes()) { + @Override + protected WebMarkupContainer getContent(final String id, final IModel model) { + return new Tab(id, getSinglesForType(singles, model)); + } - @Override - protected IModel getLabelModel(final IModel model) { - return LambdaModel.of(model, ProjectType::getName, ProjectType::setName); + @Override + protected IModel getLabelModel(final IModel model) { + return LambdaModel.of(model, ProjectType::getName, ProjectType::setName); + } } - }); + ); } private class Tab extends Fragment { + public Tab(final String id, final IModel> singles) { super(id, "tab", SinglesPanel.this, singles); - - add(new ListView<>("singles", singles) { - @Override - protected void populateItem(final ListItem item) { - final IModel partner = item.getModel(); - item.add(new UserLinkPanel("user", partner.map(ProjectPartner::getUser))); - item.add(new MultiLineLabel("infotext", partner.map(ProjectPartner::getInfotext))); - item.add(new DateLabel("dateCreated", partner.map(ProjectPartner::getDateCreated), DateStyle.DATE)); + add( + new ListView<>("singles", singles) { + @Override + protected void populateItem(final ListItem item) { + final IModel partner = item.getModel(); + item.add(new UserLinkPanel("user", partner.map(ProjectPartner::getUser))); + item.add(new MultiLineLabel("infotext", partner.map(ProjectPartner::getInfotext))); + item.add( + new DateLabel("dateCreated", partner.map(ProjectPartner::getDateCreated), DateStyle.DATE) + ); + } } - }); + ); } } - private IModel> getSinglesForType(final IModel> singles, final IModel projectType) { + private IModel> getSinglesForType( + final IModel> singles, + final IModel projectType + ) { return new FilteredListModel<>(singles) { @Override protected boolean accept(final ProjectPartner projectPartner) { @@ -76,7 +84,9 @@ public class SinglesPanel extends GenericPanel { return new LoadableDetachableModel<>() { @Override protected List load() { - final List partnersWithoutIdea = projectPartnerService.getPartnersWithoutIdea(getModelObject()); + final List partnersWithoutIdea = projectPartnerService.getPartnersWithoutIdea( + getModelObject() + ); partnersWithoutIdea.sort(comparing(ProjectPartner::getDateCreated, reverseOrder())); return partnersWithoutIdea; } @@ -84,7 +94,9 @@ public class SinglesPanel extends GenericPanel { } private IModel> getMatchableTypes() { - final IModel> matchableTypes = new ListAdapterModel<>(getModel().map(ApplicationPeriod::getProjectTypes)); + final IModel> matchableTypes = new ListAdapterModel<>( + getModel().map(ApplicationPeriod::getProjectTypes) + ); return new FilteredListModel<>(matchableTypes) { @Override protected boolean accept(final ProjectType projectType) { diff --git a/view/src/main/java/se/su/dsv/scipro/projectstate/ProjectStatePanel.java b/view/src/main/java/se/su/dsv/scipro/projectstate/ProjectStatePanel.java index 7b1194cb48..58870f6edc 100644 --- a/view/src/main/java/se/su/dsv/scipro/projectstate/ProjectStatePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/projectstate/ProjectStatePanel.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.projectstate; +import static se.su.dsv.scipro.data.enums.DateStyle.DATETIME; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.html.basic.Label; @@ -21,14 +28,6 @@ import se.su.dsv.scipro.security.auth.ProjectModuleComponent; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; - -import static se.su.dsv.scipro.data.enums.DateStyle.DATETIME; - @ProjectModuleComponent(ProjectModule.PROJECT_STATE) public abstract class ProjectStatePanel extends Panel { @@ -36,6 +35,7 @@ public abstract class ProjectStatePanel extends Panel { @Inject ProjectService projectService; + @Inject ProjectForumService projectForumService; @@ -100,13 +100,15 @@ public abstract class ProjectStatePanel extends Panel { } private void addStateLabel() { - add(new Label(STATE, model.getObject().getStateOfMind().getDescription()) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(!isAuthorView()); + add( + new Label(STATE, model.getObject().getStateOfMind().getDescription()) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(!isAuthorView()); + } } - }); + ); } private void addUpdatedLabel() { @@ -137,33 +139,45 @@ public abstract class ProjectStatePanel extends Panel { reasonArea.setRequired(true); form.add(reasonArea); - form.add(new AjaxButton(SUBMIT) { - @Override - protected void onSubmit(AjaxRequestTarget target) { - model.getObject().setStateOfMind(dropDown.getModelObject()); - model.getObject().setStateOfMindDate(new Date()); - model.getObject().setStateOfMindReason(reasonArea.getModelObject()); - reasonLabel.setDefaultModel(Model.of(model.getObject().getStateOfMindReason())); - model.setObject(projectService.save(model.getObject())); - date = new DateLabel(DATE, new Model<>(model.getObject().getStateOfMindDate()), DATETIME); - getParent().getParent().replace(date); - date.setOutputMarkupId(true); - form.setVisibilityAllowed(false); - if (model.getObject().hasModule(ProjectModule.FORUM)) { - projectForumService.createThread(model.getObject(), SciProSession.get().getUser(), getString("forumSubject"), reasonArea.getModelObject(), new HashSet<>()); + form.add( + new AjaxButton(SUBMIT) { + @Override + protected void onSubmit(AjaxRequestTarget target) { + model.getObject().setStateOfMind(dropDown.getModelObject()); + model.getObject().setStateOfMindDate(new Date()); + model.getObject().setStateOfMindReason(reasonArea.getModelObject()); + reasonLabel.setDefaultModel(Model.of(model.getObject().getStateOfMindReason())); + model.setObject(projectService.save(model.getObject())); + date = new DateLabel(DATE, new Model<>(model.getObject().getStateOfMindDate()), DATETIME); + getParent().getParent().replace(date); + date.setOutputMarkupId(true); + form.setVisibilityAllowed(false); + if (model.getObject().hasModule(ProjectModule.FORUM)) { + projectForumService.createThread( + model.getObject(), + SciProSession.get().getUser(), + getString("forumSubject"), + reasonArea.getModelObject(), + new HashSet<>() + ); + } + addComponents(target); } - addComponents(target); - } - @Override - protected void onError(AjaxRequestTarget target) { - addComponents(target); + @Override + protected void onError(AjaxRequestTarget target) { + addComponents(target); + } } - }); + ); } private void addDropDown() { - dropDown = new AjaxDropDownChoice<>(DROPDOWN, Model.of(model.getObject().getStateOfMind()), new ListModel<>(new ArrayList<>(Arrays.asList(StateOfMind.values())))) { + dropDown = new AjaxDropDownChoice<>( + DROPDOWN, + Model.of(model.getObject().getStateOfMind()), + new ListModel<>(new ArrayList<>(Arrays.asList(StateOfMind.values()))) + ) { @Override public void onNewSelection(AjaxRequestTarget target, StateOfMind objectSelected) { if (objectSelected != StateOfMind.NEEDHELP) { diff --git a/view/src/main/java/se/su/dsv/scipro/repository/LifecycleManagedWebApplication.java b/view/src/main/java/se/su/dsv/scipro/repository/LifecycleManagedWebApplication.java index 2a2fd1d9ef..20554a15d5 100755 --- a/view/src/main/java/se/su/dsv/scipro/repository/LifecycleManagedWebApplication.java +++ b/view/src/main/java/se/su/dsv/scipro/repository/LifecycleManagedWebApplication.java @@ -1,12 +1,10 @@ package se.su.dsv.scipro.repository; - -import org.apache.wicket.protocol.http.WebApplication; -import se.su.dsv.scipro.system.Lifecycle; - import jakarta.inject.Inject; import java.util.Collections; import java.util.Set; +import org.apache.wicket.protocol.http.WebApplication; +import se.su.dsv.scipro.system.Lifecycle; public abstract class LifecycleManagedWebApplication extends WebApplication { diff --git a/view/src/main/java/se/su/dsv/scipro/repository/components/DownloadResource.java b/view/src/main/java/se/su/dsv/scipro/repository/components/DownloadResource.java index 0eb9ac477e..4fd6300d7a 100644 --- a/view/src/main/java/se/su/dsv/scipro/repository/components/DownloadResource.java +++ b/view/src/main/java/se/su/dsv/scipro/repository/components/DownloadResource.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.repository.components; +import java.io.IOException; +import java.io.InputStream; import org.apache.wicket.model.IModel; import org.apache.wicket.request.resource.AbstractResource; import org.apache.wicket.request.resource.ContentDisposition; import org.apache.wicket.util.io.IOUtils; import se.su.dsv.scipro.file.FileDescription; -import java.io.IOException; -import java.io.InputStream; - class DownloadResource extends AbstractResource { + protected final IModel model; public DownloadResource(IModel model) { @@ -26,14 +26,16 @@ class DownloadResource extends AbstractResource { resourceResponse.setFileName(fileDescription.getName().replace(',', ' ')); if (resourceResponse.dataNeedsToBeWritten(attributes)) { - resourceResponse.setWriteCallback(new WriteCallback() { - @Override - public void writeData(Attributes attributes) throws IOException { - try (InputStream data = fileDescription.getData()) { - IOUtils.copy(data, attributes.getResponse().getOutputStream()); + resourceResponse.setWriteCallback( + new WriteCallback() { + @Override + public void writeData(Attributes attributes) throws IOException { + try (InputStream data = fileDescription.getData()) { + IOUtils.copy(data, attributes.getResponse().getOutputStream()); + } } } - }); + ); } resourceResponse.setContentDisposition(ContentDisposition.ATTACHMENT); diff --git a/view/src/main/java/se/su/dsv/scipro/repository/components/FileDownloadLink.java b/view/src/main/java/se/su/dsv/scipro/repository/components/FileDownloadLink.java index 863328fef5..5cc8ac047b 100755 --- a/view/src/main/java/se/su/dsv/scipro/repository/components/FileDownloadLink.java +++ b/view/src/main/java/se/su/dsv/scipro/repository/components/FileDownloadLink.java @@ -5,6 +5,7 @@ import org.apache.wicket.model.IModel; import se.su.dsv.scipro.file.FileDescription; public class FileDownloadLink extends ResourceLink { + public FileDownloadLink(String id, IModel model) { super(id, new DownloadResource(model)); setModel(model); diff --git a/view/src/main/java/se/su/dsv/scipro/repository/panels/ProjectFilePanel.java b/view/src/main/java/se/su/dsv/scipro/repository/panels/ProjectFilePanel.java index bfb6963bf9..e9bade3f60 100755 --- a/view/src/main/java/se/su/dsv/scipro/repository/panels/ProjectFilePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/repository/panels/ProjectFilePanel.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.repository.panels; +import static se.su.dsv.scipro.notifications.dataobject.ProjectEvent.Event.FILE_UPLOADED; +import static se.su.dsv.scipro.security.auth.roles.Roles.AUTHOR; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + +import jakarta.inject.Inject; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -34,18 +44,7 @@ import se.su.dsv.scipro.repository.components.FileDownloadLink; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.session.SciProSession; -import jakarta.inject.Inject; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import static se.su.dsv.scipro.notifications.dataobject.ProjectEvent.Event.FILE_UPLOADED; -import static se.su.dsv.scipro.security.auth.roles.Roles.AUTHOR; -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {AUTHOR, SUPERVISOR}) +@Authorization(authorizedRoles = { AUTHOR, SUPERVISOR }) public class ProjectFilePanel extends GenericPanel { public static final String FEEDBACK_PANEL = "feedbackPanel"; @@ -56,10 +55,13 @@ public class ProjectFilePanel extends GenericPanel { public static final int KILO_BYTE = 1024; private static final Bytes MAX_FILE_SIZE = Bytes.megabytes(100); public static final String TABLE = "table"; + @Inject private NotificationController notificationController; + @Inject private ProjectFileService projectFileService; + private FeedbackPanel feedback; private ExportableDataPanel dp; @@ -86,34 +88,59 @@ public class ProjectFilePanel extends GenericPanel { private List> getColumns() { List> columns = new ArrayList<>(); columns.add(nameColumn()); - columns.add(new DateColumn<>(Model.of("Created"), ProjectFile::getDateCreated, "dateCreated", DateStyle.DATETIME)); - columns.add(new LambdaColumn<>(Model.of("Size"), "fileReference.fileDescription.size", pf -> getFormattedSize(pf.getFileDescription()))); - columns.add(new UserColumn<>(Model.of("Uploader"), "fileReference.fileDescription.uploader.fullName", pf -> pf.getFileDescription().getUploader())); + columns.add( + new DateColumn<>(Model.of("Created"), ProjectFile::getDateCreated, "dateCreated", DateStyle.DATETIME) + ); + columns.add( + new LambdaColumn<>(Model.of("Size"), "fileReference.fileDescription.size", pf -> + getFormattedSize(pf.getFileDescription()) + ) + ); + columns.add( + new UserColumn<>(Model.of("Uploader"), "fileReference.fileDescription.uploader.fullName", pf -> + pf.getFileDescription().getUploader() + ) + ); columns.add(new EnumLambdaColumn<>(Model.of("Source"), "fileSource", ProjectFile::getFileSource)); - columns.add(new AbstractColumn<>(Model.of("Delete")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { + columns.add( + new AbstractColumn<>(Model.of("Delete")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + new AjaxIconLinkPanel<>( + componentId, + rowModel, + Model.of(AjaxIconLinkPanel.DELETE), + "Are you sure you want to delete the file?" + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + projectFileService.delete(rowModel.getObject()); + success(getString("deleted")); + target.add(feedback); + target.add(dp); + } - cellItem.add(new AjaxIconLinkPanel<>(componentId, rowModel, Model.of(AjaxIconLinkPanel.DELETE), "Are you sure you want to delete the file?") { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - projectFileService.delete(rowModel.getObject()); - success(getString("deleted")); - target.add(feedback); - target.add(dp); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - ProjectFile file = rowModel.getObject(); - boolean isUploader = file.getFileDescription().getUploader().equals(SciProSession.get().getUser()); - boolean wasUploadedToFiles = file.getFileSource() == FileSource.FILES; - setVisibilityAllowed(isUploader && wasUploadedToFiles); - } - }); + @Override + protected void onConfigure() { + super.onConfigure(); + ProjectFile file = rowModel.getObject(); + boolean isUploader = file + .getFileDescription() + .getUploader() + .equals(SciProSession.get().getUser()); + boolean wasUploadedToFiles = file.getFileSource() == FileSource.FILES; + setVisibilityAllowed(isUploader && wasUploadedToFiles); + } + } + ); + } } - }); + ); return columns; } @@ -133,8 +160,15 @@ public class ProjectFilePanel extends GenericPanel { private IColumn nameColumn() { return new AbstractColumn<>(Model.of("Name"), "fileReference.fileDescription.name") { @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - FileDownloadLink downloadLink = new FileDownloadLink<>("name", rowModel.map(ProjectFile::getFileDescription)); + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + FileDownloadLink downloadLink = new FileDownloadLink<>( + "name", + rowModel.map(ProjectFile::getFileDescription) + ); downloadLink.setBody(rowModel.map(ProjectFile::getFileDescription).map(FileDescription::getName)); Fragment cell = new Fragment(componentId, "_name", ProjectFilePanel.this); @@ -152,6 +186,7 @@ public class ProjectFilePanel extends GenericPanel { } private class FileUploadForm extends Form { + private FileUploadField fileUploadField; public FileUploadForm(String id) { @@ -168,7 +203,10 @@ public class ProjectFilePanel extends GenericPanel { @Override protected void onSubmit() { final FileUpload upload = fileUploadField.getFileUpload(); - projectFileService.store(new WicketProjectFileUpload(upload, ProjectFilePanel.this.getModelObject()), FileSource.FILES); + projectFileService.store( + new WicketProjectFileUpload(upload, ProjectFilePanel.this.getModelObject()), + FileSource.FILES + ); success(getString("file.uploaded")); notifyUpload(upload.getClientFileName()); } @@ -182,7 +220,9 @@ public class ProjectFilePanel extends GenericPanel { @Override public Iterator iterator(long first, long count) { - return projectFileService.getProjectFiles(getModelObject(), new PageAdapter(first, count, getSort())).iterator(); + return projectFileService + .getProjectFiles(getModelObject(), new PageAdapter(first, count, getSort())) + .iterator(); } @Override @@ -195,6 +235,5 @@ public class ProjectFilePanel extends GenericPanel { final Long id = object.getId(); // to prevent serialization of the entire entity return LoadableDetachableModel.of(() -> projectFileService.findOne(id)); } - } } diff --git a/view/src/main/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanel.java b/view/src/main/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanel.java index 1d22928c24..5f321c0842 100644 --- a/view/src/main/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanel.java @@ -26,13 +26,15 @@ public class ViewAttachmentPanel extends GenericPanel { super.onInitialize(); add(new FileDownloadLink<>(NAME, getModel()).setBody(getModel().map(FileDescription::getName))); - add(new DateLabel(UPLOAD_TIME, getModel().map(DomainObject::getDateCreated), dateStyle) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(dateStyle != null); + add( + new DateLabel(UPLOAD_TIME, getModel().map(DomainObject::getDateCreated), dateStyle) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(dateStyle != null); + } } - }); + ); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanel.java index 7ac0aa3c27..37e981c569 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.reviewer; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -25,11 +29,6 @@ import se.su.dsv.scipro.reviewing.ReviewerApproval; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - public abstract class ApprovalReviewerPanel extends Panel { @Inject @@ -38,17 +37,28 @@ public abstract class ApprovalReviewerPanel extends Panel { public ApprovalReviewerPanel(final String id) { super(id); final IModel filter = getFilter(); - UndecidedReviewerApprovalsProvider undecidedReviewerApprovalsProvider = new UndecidedReviewerApprovalsProvider(filter); + UndecidedReviewerApprovalsProvider undecidedReviewerApprovalsProvider = new UndecidedReviewerApprovalsProvider( + filter + ); undecidedReviewerApprovalsProvider.setSort(MyReviewService.Sort.DEADLINE, SortOrder.ASCENDING); - final DefaultDataPanel table = new DefaultDataPanel<>("undecidedApprovals", createColumns(), undecidedReviewerApprovalsProvider); + final DefaultDataPanel table = new DefaultDataPanel<>( + "undecidedApprovals", + createColumns(), + undecidedReviewerApprovalsProvider + ); table.setOutputMarkupId(true); add(table); - add(new AjaxCheckBox("showAll", LambdaModel.of(filter, MyReviewService.Filter::isShowAll, MyReviewService.Filter::setShowAll)) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(table); + add( + new AjaxCheckBox( + "showAll", + LambdaModel.of(filter, MyReviewService.Filter::isShowAll, MyReviewService.Filter::setShowAll) + ) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(table); + } } - }); + ); } private IModel getFilter() { @@ -60,26 +70,44 @@ public abstract class ApprovalReviewerPanel extends Panel { private List> createColumns() { return Arrays.asList( - new DateColumn<>(Model.of("Requested"), Decision::getRequested, MyReviewService.Sort.REQUESTED), - new DateColumn<>(Model.of("Deadline"), Decision::getDeadline, MyReviewService.Sort.DEADLINE), - new AbstractColumn<>(Model.of("Title"), MyReviewService.Sort.TITLE) { - @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - cellItem.add(LinkWrapper.apply(componentId, id -> { + new DateColumn<>(Model.of("Requested"), Decision::getRequested, MyReviewService.Sort.REQUESTED), + new DateColumn<>(Model.of("Deadline"), Decision::getDeadline, MyReviewService.Sort.DEADLINE), + new AbstractColumn<>(Model.of("Title"), MyReviewService.Sort.TITLE) { + @Override + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + cellItem.add( + LinkWrapper.apply(componentId, id -> { AbstractLink link = newDecisionLink(id, rowModel.map(Decision::getReviewerApproval)); - link.setBody(rowModel.map(Decision::getReviewerApproval).map(ReviewerApproval::getProject).map(Project::getTitle)); + link.setBody( + rowModel + .map(Decision::getReviewerApproval) + .map(ReviewerApproval::getProject) + .map(Project::getTitle) + ); return link; - })); - } - }, - new EnumLambdaColumn<>(Model.of("Current status"), Decision::getStatus), - new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - public IModel> getUsers(final IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Decision::getReviewerApproval).map(ReviewerApproval::getProject).map(Project::getProjectParticipants)); - } - }, - new UserColumn<>(Model.of("Head supervisor"), MyReviewService.Sort.SUPERVISOR, ra -> ra.getReviewerApproval().getProject().getHeadSupervisor()) + }) + ); + } + }, + new EnumLambdaColumn<>(Model.of("Current status"), Decision::getStatus), + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + public IModel> getUsers(final IModel rowModel) { + return new ListAdapterModel<>( + rowModel + .map(Decision::getReviewerApproval) + .map(ReviewerApproval::getProject) + .map(Project::getProjectParticipants) + ); + } + }, + new UserColumn<>(Model.of("Head supervisor"), MyReviewService.Sort.SUPERVISOR, ra -> + ra.getReviewerApproval().getProject().getHeadSupervisor() + ) ); } @@ -87,7 +115,9 @@ public abstract class ApprovalReviewerPanel extends Panel { public abstract ReviewerApproval.Step getStep(); - private final class UndecidedReviewerApprovalsProvider extends SortableDataProvider { + private final class UndecidedReviewerApprovalsProvider + extends SortableDataProvider { + private IModel filter; private UndecidedReviewerApprovalsProvider(IModel filter) { @@ -96,7 +126,9 @@ public abstract class ApprovalReviewerPanel extends Panel { @Override public Iterator iterator(final long first, final long count) { - return myReviewService.findAllDecisions(filter.getObject(), new WicketPage<>(first, count, getSort())).iterator(); + return myReviewService + .findAllDecisions(filter.getObject(), new WicketPage<>(first, count, getSort())) + .iterator(); } @Override @@ -115,5 +147,4 @@ public abstract class ApprovalReviewerPanel extends Panel { }; } } - } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionForumThread.java b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionForumThread.java index 1cd44f60af..c640bc51e2 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionForumThread.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionForumThread.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.reviewer; +import java.util.*; import org.apache.wicket.util.io.IClusterable; import se.su.dsv.scipro.forum.Attachment; import se.su.dsv.scipro.forum.ForumThread; @@ -8,9 +9,8 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.reviewing.ReviewerInteractionService; import se.su.dsv.scipro.system.User; -import java.util.*; - public class ReviewerInteractionForumThread implements ForumThread, IClusterable { + private final ReviewerInteractionService reviewerInteractionService; public ReviewerInteractionForumThread(final ReviewerInteractionService reviewerInteractionService) { @@ -23,7 +23,12 @@ public class ReviewerInteractionForumThread implements ForumThread, ICl } @Override - public ForumPost reply(final Project project, final User poster, final String content, final Set attachments) { + public ForumPost reply( + final Project project, + final User poster, + final String content, + final Set attachments + ) { return reviewerInteractionService.reply(project, poster, content, attachments); } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPage.java b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPage.java index a583f1b6de..8071bb9c74 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.reviewer; +import jakarta.inject.Inject; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -24,16 +25,17 @@ import se.su.dsv.scipro.reviewing.ReviewerInteractionService; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - public class ReviewerInteractionPage extends ReviewerPage { @Inject private ReviewerInteractionService reviewerInteractionService; + @Inject private ProjectService projectService; + @Inject private FileService fileDescriptionService; + @Inject private BasicForumService basicForumService; @@ -50,19 +52,31 @@ public class ReviewerInteractionPage extends ReviewerPage { } basicForumService.setThreadRead(SciProSession.get().getUser(), reviewerThread.getForumThread(), true); - add(new SubmitForumReplyPanel<>("communication", projectModel, new ReviewerInteractionForumThread(reviewerInteractionService))); + add( + new SubmitForumReplyPanel<>( + "communication", + projectModel, + new ReviewerInteractionForumThread(reviewerInteractionService) + ) + ); add(new TimelinePanel("timeline", projectModel)); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("communication_toggle", "click", "$(this).hide(); $('#communication').show();")); + response.render( + OnEventHeaderItem.forMarkupId( + "communication_toggle", + "click", + "$(this).hide(); $('#communication').show();" + ) + ); } private IModel validatePageLoad(PageParameters pp) { final StringValue value = pp.get(PageParameterKeys.MAP.get(Project.class)); - if(value.isNull()) { + if (value.isNull()) { throw new RestartResponseException(getApplication().getHomePage()); } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerPage.java b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerPage.java index 21849493b3..60044023d0 100755 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.reviewer; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; @@ -8,9 +9,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.springdata.services.UserProfileService; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.REVIEWER}) +@Authorization(authorizedRoles = { Roles.REVIEWER }) public abstract class ReviewerPage extends MenuPage { @Inject @@ -26,10 +25,11 @@ public abstract class ReviewerPage extends MenuPage { public ReviewerPage(PageParameters pp) { super(pp); saveSelectedRole(); - SciProSession.get().setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); + SciProSession.get() + .setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); } private void saveSelectedRole() { userProfileService.setSelectedRole(SciProSession.get().getUser(), Roles.REVIEWER); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerStartPage.java b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerStartPage.java index b91ab3cd41..34810dbfe4 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/ReviewerStartPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.reviewer; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -39,25 +45,23 @@ import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static java.util.Arrays.asList; - -@Authorization(authorizedRoles = {Roles.REVIEWER}) +@Authorization(authorizedRoles = { Roles.REVIEWER }) public class ReviewerStartPage extends ReviewerPage { + public static final String MAIN_MENU_LABEL = "Reviewer"; @Inject private MyReviewService myReviewService; + @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; + @Inject private ReviewerInteractionService reviewerInteractionService; + @Inject private BasicForumService basicForumService; @@ -72,10 +76,12 @@ public class ReviewerStartPage extends ReviewerPage { } private void addRoughDraftApprovals() { - add(new Label("undecidedRoughDraftApprovals", () -> { + add( + new Label("undecidedRoughDraftApprovals", () -> { long undecided = myReviewService.countUndecidedRoughDraft(SciProSession.get().getUser()); return undecided == 0 ? "" : undecided; - })); + }) + ); add(new RoughDraftApprovalReviewerPanel("RoughDraftApprovals")); } @@ -87,14 +93,18 @@ public class ReviewerStartPage extends ReviewerPage { filter.setRoles(Collections.singletonList(ProjectTeamMemberRoles.REVIEWER)); filter.setProjectTypes(projectTypeService.findAllActive()); - final SortableDataProvider provider = new FilteredDataProvider<>(projectService, Model.of(filter)); + final SortableDataProvider provider = new FilteredDataProvider<>( + projectService, + Model.of(filter) + ); DefaultDataTable table = new DefaultDataTable<>("dataPanel", createColumns(), provider, 1000); add(table); addFilteringOptions(filter, table); - add(new Label("unreadSupervisorsPosts", () -> { + add( + new Label("unreadSupervisorsPosts", () -> { List projects = projectService.findAll(filter); int totalNumberOfUnreadPosts = 0; for (Project project : projects) { @@ -102,7 +112,8 @@ public class ReviewerStartPage extends ReviewerPage { totalNumberOfUnreadPosts += getUnreadPosts(user, project); } return (totalNumberOfUnreadPosts == 0) ? "" : totalNumberOfUnreadPosts; - })); + }) + ); } private int getUnreadPosts(User user, Project project) { @@ -117,70 +128,101 @@ public class ReviewerStartPage extends ReviewerPage { private void addFilteringOptions(final ProjectService.Filter filter, final Component table) { table.setOutputMarkupId(true); - add(new AjaxCheckBoxMultipleChoice<>("status", + add( + new AjaxCheckBoxMultipleChoice<>( + "status", LambdaModel.of(filter::getStatuses, filter::setStatuses), asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(table); + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(table); + } } - }); - add(new AjaxCheckBoxMultipleChoice<>("type", + ); + add( + new AjaxCheckBoxMultipleChoice<>( + "type", LambdaModel.of(filter::getProjectTypes, filter::setProjectTypes), projectTypeService.findBySupervisorProjects(SciProSession.get().getUser()), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(table); + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(table); + } } - }); + ); } private List> createColumns() { List> columns = new ArrayList<>(); columns.add(new TemporalColumn<>(Model.of("Started"), Project::getStartDate)); columns.add(new LambdaColumn<>(Model.of("Type"), Project::getProjectTypeName)); - columns.add(new AbstractExportableColumn<>(Model.of("Title")) { - @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - cellItem.add(LinkWrapper.apply(componentId, id -> { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Project.class), rowModel.getObject().getId()); - AbstractLink link = new BookmarkablePageLink<>(id, ReviewerInteractionPage.class, pp); - link.setBody(LambdaModel.of(rowModel, Project::getTitle, Project::setTitle)); - return link; - })); - } + columns.add( + new AbstractExportableColumn<>(Model.of("Title")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { + cellItem.add( + LinkWrapper.apply(componentId, id -> { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Project.class), rowModel.getObject().getId()); + AbstractLink link = new BookmarkablePageLink<>(id, ReviewerInteractionPage.class, pp); + link.setBody(LambdaModel.of(rowModel, Project::getTitle, Project::setTitle)); + return link; + }) + ); + } - @Override - public IModel getDataModel(IModel rowModel) { - return LambdaModel.of(rowModel, Project::getTitle, Project::setTitle); + @Override + public IModel getDataModel(IModel rowModel) { + return LambdaModel.of(rowModel, Project::getTitle, Project::setTitle); + } } - }); - columns.add(new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - public IModel> getUsers(final IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); - } - }); - columns.add(new AbstractExportableColumn<>(Model.of("Head supervisor")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new UserLinkPanel(componentId, LambdaModel.of(rowModel, Project::getHeadSupervisor, Project::setHeadSupervisor))); + ); + columns.add( + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + public IModel> getUsers(final IModel rowModel) { + return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + } } + ); + columns.add( + new AbstractExportableColumn<>(Model.of("Head supervisor")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new UserLinkPanel( + componentId, + LambdaModel.of(rowModel, Project::getHeadSupervisor, Project::setHeadSupervisor) + ) + ); + } - @Override - public IModel getDataModel(IModel rowModel) { - return rowModel.map(Project::getHeadSupervisor).map(User::getFullName); + @Override + public IModel getDataModel(IModel rowModel) { + return rowModel.map(Project::getHeadSupervisor).map(User::getFullName); + } } - }); - columns.add(new AbstractExportableColumn<>(Model.of("Unread posts")) { - @Override - public IModel getDataModel(final IModel rowModel) { - return () -> getUnreadPosts(SciProSession.get().getUser(), rowModel.getObject()); + ); + columns.add( + new AbstractExportableColumn<>(Model.of("Unread posts")) { + @Override + public IModel getDataModel(final IModel rowModel) { + return () -> getUnreadPosts(SciProSession.get().getUser(), rowModel.getObject()); + } } - }); + ); return columns; } } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPage.java b/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPage.java index 799a32b3cb..aee867817f 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPage.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPage.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.reviewer; +import jakarta.inject.Inject; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; import org.apache.wicket.RestartResponseException; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.head.IHeaderResponse; @@ -42,31 +51,27 @@ import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; -import jakarta.inject.Inject; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; - public class RoughDraftApprovalDecisionPage extends ReviewerPage { + public static final String PAGE_PARAMETER_ID = "id"; private static final System.Logger LOGGER = System.getLogger(RoughDraftApprovalDecisionPage.class.getSimpleName()); @Inject private ReviewerInteractionService reviewerInteractionService; + @Inject private ReviewerDecisionService reviewerDecisionService; + @Inject private RoughDraftApprovalService roughDraftApprovalService; + @Inject private ProjectService projectService; + @Inject private OAuthService oAuthService; + @Inject private GradingService gradingService; @@ -74,11 +79,10 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { public RoughDraftApprovalDecisionPage(PageParameters pp) { super(pp); - final long id = pp.get(PAGE_PARAMETER_ID).toLong(); approval = LoadableDetachableModel.of(() -> projectService.findOne(id)) - .map(roughDraftApprovalService::findBy) - .map(o -> o.orElse(null)); + .map(roughDraftApprovalService::findBy) + .map(o -> o.orElse(null)); if (approval.getObject() == null || !approval.getObject().getProject().isReviewer(loggedInUser())) { throw new RestartResponseException(getApplication().getHomePage()); } @@ -89,23 +93,31 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { add(new Label("projectTitle", project.map(Project::getTitle))); add(new ProjectHeaderPanel("projectHeader", project)); add(new InfoPanel("info", new ResourceModel("info"))); - add(new SubmitForumReplyPanel<>("communication", project, new ReviewerInteractionForumThread(reviewerInteractionService))); + add( + new SubmitForumReplyPanel<>( + "communication", + project, + new ReviewerInteractionForumThread(reviewerInteractionService) + ) + ); add(new FinalSeminarApprovalProcessPanel("details", approval)); add(new DecisionForm("decision", approval)); add(new EnumLabel<>("title", approval.map(ReviewerApproval::getStep))); add(new TimelinePanel("timeline", project)); add(new FencedFeedbackPanel("feedback", this)); IModel moreInformationUrl = project - .map(Project::getProjectType) - .map(ProjectType::getProjectTypeSettings) - .map(ProjectTypeSettings::getReviewProcessInformationUrl); - add(new ExternalLink("review_process_information", moreInformationUrl) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(moreInformationUrl.getObject() != null); + .map(Project::getProjectType) + .map(ProjectType::getProjectTypeSettings) + .map(ProjectTypeSettings::getReviewProcessInformationUrl); + add( + new ExternalLink("review_process_information", moreInformationUrl) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(moreInformationUrl.getObject() != null); + } } - }); + ); } @Override @@ -118,12 +130,13 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { final Instant expiration = getSession().getMetaData(OAuth.EXPIRATION); final boolean validToken = expiration != null && expiration.isAfter(Instant.now()); if (!validToken) { - final PageParameters pp = RoughDraftApprovalDecisionPage.pageParametersFor(approval.getObject().getProject()); - final String returnUrl = "/" + getRequestCycle().mapUrlFor(RoughDraftApprovalDecisionPage.class, pp).canonical(); + final PageParameters pp = RoughDraftApprovalDecisionPage.pageParametersFor( + approval.getObject().getProject() + ); + final String returnUrl = + "/" + getRequestCycle().mapUrlFor(RoughDraftApprovalDecisionPage.class, pp).canonical(); getSession().setMetaData(OAuth.RETURN_URL, returnUrl); - final String href = oAuthService.authorizeUrl( - null, - Set.of("grade:read", "grade:write")); + final String href = oAuthService.authorizeUrl(null, Set.of("grade:read", "grade:write")); throw new RedirectToUrlException(href); } } @@ -142,47 +155,54 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { attachment = new FileUploadField("attachment"); add(attachment); - add(new Button("reject") { - @Override - public void onSubmit() { - reviewerDecisionService.reject( + add( + new Button("reject") { + @Override + public void onSubmit() { + reviewerDecisionService.reject( DecisionForm.this.getModelObject(), feedback.getModelObject(), - WicketFileUpload.ofOptional(attachment.getFileUpload())); + WicketFileUpload.ofOptional(attachment.getFileUpload()) + ); + } } - }); + ); addExaminationInfo(); - add(new Button("approve") { - @Override - public void onSubmit() { - super.onSubmit(); - Project project = approval.getObject().getProject(); - try { - for (User author : project.getProjectParticipants()) { - if (!reportGrade(author, project)) { - error(getString("error_while_reporting_phase_two_grades")); - return; + add( + new Button("approve") { + @Override + public void onSubmit() { + super.onSubmit(); + Project project = approval.getObject().getProject(); + try { + for (User author : project.getProjectParticipants()) { + if (!reportGrade(author, project)) { + error(getString("error_while_reporting_phase_two_grades")); + return; + } } - } - reviewerDecisionService.approve( + reviewerDecisionService.approve( approval.getObject(), feedback.getModelObject(), - WicketFileUpload.ofOptional(attachment.getFileUpload())); - } catch (RuntimeException e) { - // When the grade service is down - LOGGER.log( + WicketFileUpload.ofOptional(attachment.getFileUpload()) + ); + } catch (RuntimeException e) { + // When the grade service is down + LOGGER.log( System.Logger.Level.ERROR, - "Failed to report phase two grades to Daisy: %s (%d)" - .formatted( - project.getTitle(), - project.getId()), - e); - error(getString("error_while_reporting_phase_two_grades")); + "Failed to report phase two grades to Daisy: %s (%d)".formatted( + project.getTitle(), + project.getId() + ), + e + ); + error(getString("error_while_reporting_phase_two_grades")); + } } } - }); + ); } @Override @@ -192,17 +212,23 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { } private void addExaminationInfo() { - IModel> authors = approval.map(ReviewerApproval::getProject) - .map(Project::getProjectParticipants) - .map(ArrayList::new); - IModel gradingServiceAvailable = LoadableDetachableModel.of(() -> isGradingServiceAvailable(authors)); + IModel> authors = approval + .map(ReviewerApproval::getProject) + .map(Project::getProjectParticipants) + .map(ArrayList::new); + IModel gradingServiceAvailable = LoadableDetachableModel.of(() -> + isGradingServiceAvailable(authors) + ); ListView listView = new ListView<>("authors", authors) { @Override protected void populateItem(ListItem item) { item.add(new UserLabel("name", item.getModel())); IModel> examinations = LoadableDetachableModel.of(() -> - getExaminationsToReport(item.getModelObject())); - WebMarkupContainer gradingServiceAvailableContainer = new WebMarkupContainer("grading_service_available") { + getExaminationsToReport(item.getModelObject()) + ); + WebMarkupContainer gradingServiceAvailableContainer = new WebMarkupContainer( + "grading_service_available" + ) { @Override protected void onConfigure() { super.onConfigure(); @@ -210,28 +236,34 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { } }; item.add(gradingServiceAvailableContainer); - gradingServiceAvailableContainer.add(new AutoHidingListView<>("examinations", examinations) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("name", item.getModel().map(Examination::name).map(Name::english))); - item.add(new Label("points", item.getModel().map(Examination::points))); - item.add(new Label("examination_date", DecisionForm.this::getExaminationDate)); + gradingServiceAvailableContainer.add( + new AutoHidingListView<>("examinations", examinations) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("name", item.getModel().map(Examination::name).map(Name::english))); + item.add(new Label("points", item.getModel().map(Examination::points))); + item.add(new Label("examination_date", DecisionForm.this::getExaminationDate)); + } } - }); - gradingServiceAvailableContainer.add(new WebMarkupContainer("nothing_to_report") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(examinations.getObject().isEmpty()); + ); + gradingServiceAvailableContainer.add( + new WebMarkupContainer("nothing_to_report") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(examinations.getObject().isEmpty()); + } } - }); - item.add(new WebMarkupContainer("grading_service_unavailable") { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(!gradingServiceAvailable.getObject()); + ); + item.add( + new WebMarkupContainer("grading_service_unavailable") { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(!gradingServiceAvailable.getObject()); + } } - }); + ); } }; listView.setReuseItems(true); @@ -255,28 +287,31 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { private List getExaminationsToReport(User author) { return getPassFailExaminations(author) - .stream() - .filter(examination -> hasNoGrade(author, examination)) - .toList(); + .stream() + .filter(examination -> hasNoGrade(author, examination)) + .toList(); } private boolean hasNoGrade(User author, Examination examination) { Either> currentResult = gradingService.getResult( - getSession().getMetaData(OAuth.TOKEN), - approval.getObject().getProject().getIdentifier(), - author.getIdentifier(), - examination.id()); + getSession().getMetaData(OAuth.TOKEN), + approval.getObject().getProject().getIdentifier(), + author.getIdentifier(), + examination.id() + ); return !currentResult.isRight() || currentResult.right().isEmpty(); } private List getPassFailExaminations(User author) { - return gradingService.getExaminations( - getSession().getMetaData(OAuth.TOKEN), - approval.getObject().getProject().getIdentifier(), - author.getIdentifier()) - .stream() - .filter(Predicate.not(Examination::hasManyPassingGrades)) - .toList(); + return gradingService + .getExaminations( + getSession().getMetaData(OAuth.TOKEN), + approval.getObject().getProject().getIdentifier(), + author.getIdentifier() + ) + .stream() + .filter(Predicate.not(Examination::hasManyPassingGrades)) + .toList(); } /** @@ -298,44 +333,49 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { private boolean reportGrade(User author, Project project, Examination examination) { Grade passingGrade = getPassingGrade(examination); Either reported = gradingService.reportGrade( - getSession().getMetaData(OAuth.TOKEN), - project.getIdentifier(), - author.getIdentifier(), - examination.id(), - passingGrade.letter(), - getExaminationDate()); + getSession().getMetaData(OAuth.TOKEN), + project.getIdentifier(), + author.getIdentifier(), + examination.id(), + passingGrade.letter(), + getExaminationDate() + ); if (!reported.isRight()) { LOGGER.log( - System.Logger.Level.WARNING, - """ - Failed to report phase two grade to Daisy: %s, \ - author: %s (%d), project: %s (%d), examination: %s (%d) - """.formatted( - reported.left(), - author.getFullName(), - author.getId(), - project.getTitle(), - project.getId(), - examination.name().swedish(), - examination.id())); + System.Logger.Level.WARNING, + """ + Failed to report phase two grade to Daisy: %s, \ + author: %s (%d), project: %s (%d), examination: %s (%d) + """.formatted( + reported.left(), + author.getFullName(), + author.getId(), + project.getTitle(), + project.getId(), + examination.name().swedish(), + examination.id() + ) + ); } return reported.isRight(); } private LocalDate getExaminationDate() { - return approval.getObject() - .getCurrentDecision() - .getRequested() - .toInstant() - .atZone(ZoneId.of("Europe/Stockholm")) - .toLocalDate(); + return approval + .getObject() + .getCurrentDecision() + .getRequested() + .toInstant() + .atZone(ZoneId.of("Europe/Stockholm")) + .toLocalDate(); } private Grade getPassingGrade(Examination examination) { - Optional passingGrade = examination.grades() - .stream() - .filter(g -> g.type() == Grade.Type.PASSING) - .findFirst(); + Optional passingGrade = examination + .grades() + .stream() + .filter(g -> g.type() == Grade.Type.PASSING) + .findFirst(); assert passingGrade.isPresent(); return passingGrade.get(); } @@ -344,7 +384,13 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("communication_toggle", "click", "$(this).hide(); $('#communication').show();")); + response.render( + OnEventHeaderItem.forMarkupId( + "communication_toggle", + "click", + "$(this).hide(); $('#communication').show();" + ) + ); } public static PageParameters pageParametersFor(Project project) { @@ -352,4 +398,4 @@ public class RoughDraftApprovalDecisionPage extends ReviewerPage { parameters.set(PAGE_PARAMETER_ID, project.getId()); return parameters; } - } \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalReviewerPanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalReviewerPanel.java index 647267e383..30f6dd78fd 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalReviewerPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalReviewerPanel.java @@ -19,7 +19,9 @@ public class RoughDraftApprovalReviewerPanel extends ApprovalReviewerPanel { @Override protected AbstractLink newDecisionLink(final String id, final IModel rowModel) { - PageParameters pageParameters = RoughDraftApprovalDecisionPage.pageParametersFor(rowModel.getObject().getProject()); + PageParameters pageParameters = RoughDraftApprovalDecisionPage.pageParametersFor( + rowModel.getObject().getProject() + ); return new BookmarkablePageLink<>(id, RoughDraftApprovalDecisionPage.class, pageParameters); } } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/ApprovedPanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/ApprovedPanel.java index fb5eda8ee7..cc2049f513 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/ApprovedPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/ApprovedPanel.java @@ -15,11 +15,17 @@ import se.su.dsv.scipro.reviewing.Decision; import se.su.dsv.scipro.reviewing.ReviewerApproval; class ApprovedPanel extends Panel { + public ApprovedPanel(final String id, final IModel decision) { super(id); add(new EnumLabel<>("topic", decision.map(Decision::getReviewerApproval).map(ReviewerApproval::getStep))); add(new DateLabel("when", decision.map(Decision::getDecisionDate), DateStyle.DATETIME)); add(new MultiLineLabel("message", decision.map(Decision::getReason))); - add(new ViewAttachmentPanel("attachment", new OrNullModel<>(decision.map(Decision::getAttachment)).map(FileReference::getFileDescription))); + add( + new ViewAttachmentPanel( + "attachment", + new OrNullModel<>(decision.map(Decision::getAttachment)).map(FileReference::getFileDescription) + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/DeniedPanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/DeniedPanel.java index d83d001a26..cbf9589d4b 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/DeniedPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/DeniedPanel.java @@ -15,11 +15,17 @@ import se.su.dsv.scipro.reviewing.Decision; import se.su.dsv.scipro.reviewing.ReviewerApproval; class DeniedPanel extends Panel { + public DeniedPanel(final String id, final IModel decision) { super(id); add(new EnumLabel<>("topic", decision.map(Decision::getReviewerApproval).map(ReviewerApproval::getStep))); add(new DateLabel("when", decision.map(Decision::getDecisionDate), DateStyle.DATETIME)); add(new MultiLineLabel("message", decision.map(Decision::getReason))); - add(new ViewAttachmentPanel("attachment", new OrNullModel<>(decision.map(Decision::getAttachment)).map(FileReference::getFileDescription))); + add( + new ViewAttachmentPanel( + "attachment", + new OrNullModel<>(decision.map(Decision::getAttachment)).map(FileReference::getFileDescription) + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/Event.java b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/Event.java index d98ba05b60..eb01e900c3 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/Event.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/Event.java @@ -1,19 +1,19 @@ package se.su.dsv.scipro.reviewer.timeline; +import java.util.Date; import org.apache.wicket.Component; import org.apache.wicket.model.*; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.panels.threaded.ForumPostPanel; import se.su.dsv.scipro.reviewing.Decision; -import java.util.Date; - interface Event { Date when(); Component component(String id, IModel model); class Message implements Event { + private final ForumPost forumPost; public Message(ForumPost forumPost) { @@ -32,6 +32,7 @@ interface Event { } class Requested implements Event { + private final Decision decision; public Requested(Decision decision) { @@ -50,6 +51,7 @@ interface Event { } class Denied implements Event { + private final Decision decision; public Denied(Decision decision) { @@ -68,6 +70,7 @@ interface Event { } class Approved implements Event { + private final Decision decision; public Approved(Decision decision) { diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/RequestedPanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/RequestedPanel.java index e90264787d..de013bc979 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/RequestedPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/RequestedPanel.java @@ -14,12 +14,23 @@ import se.su.dsv.scipro.reviewing.Decision; import se.su.dsv.scipro.reviewing.ReviewerApproval; class RequestedPanel extends Panel { + public RequestedPanel(final String id, final IModel decision) { super(id); add(new EnumLabel<>("topic", decision.map(Decision::getReviewerApproval).map(ReviewerApproval::getStep))); add(new DateLabel("when", decision.map(Decision::getRequested), DateStyle.DATETIME)); - add(new UserLinkPanel("supervisor", decision.map(Decision::getReviewerApproval).map(ReviewerApproval::getProject).map(Project::getHeadSupervisor))); + add( + new UserLinkPanel( + "supervisor", + decision + .map(Decision::getReviewerApproval) + .map(ReviewerApproval::getProject) + .map(Project::getHeadSupervisor) + ) + ); add(new MultiLineLabel("message", decision.map(Decision::getComment)).setRenderBodyOnly(true)); - add(new ViewAttachmentPanel("thesis", decision.map(Decision::getThesis).map(FileReference::getFileDescription))); + add( + new ViewAttachmentPanel("thesis", decision.map(Decision::getThesis).map(FileReference::getFileDescription)) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanel.java b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanel.java index 54ad1b4172..be3bb709f9 100644 --- a/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanel.java +++ b/view/src/main/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.reviewer.timeline; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; @@ -8,20 +10,19 @@ import org.apache.wicket.model.LoadableDetachableModel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.reviewing.*; -import jakarta.inject.Inject; -import java.util.*; - public class TimelinePanel extends Panel { + @Inject private ReviewerInteractionService reviewerInteractionService; + @Inject private FinalSeminarApprovalService finalSeminarApprovalService; + @Inject private RoughDraftApprovalService roughDraftApprovalService; public TimelinePanel(final String id, final IModel model) { super(id, model); - IModel> events = new LoadableDetachableModel<>() { @Override protected List load() { @@ -46,12 +47,14 @@ public class TimelinePanel extends Panel { } }; - add(new ListView<>("events", events) { - @Override - protected void populateItem(final ListItem item) { - item.add(item.getModelObject().component("event", item.getModel())); + add( + new ListView<>("events", events) { + @Override + protected void populateItem(final ListItem item) { + item.add(item.getModelObject().component("event", item.getModel())); + } } - }); + ); } private Collection getForumEvents(final Project project) { @@ -59,15 +62,17 @@ public class TimelinePanel extends Panel { } private Collection getFinalSeminarDecisions(final Project project) { - return finalSeminarApprovalService.findBy(project) - .map(FinalSeminarApproval::getHistory) - .orElseGet(Collections::emptyList); + return finalSeminarApprovalService + .findBy(project) + .map(FinalSeminarApproval::getHistory) + .orElseGet(Collections::emptyList); } private Collection getRoughDraftDecisions(final Project project) { - return roughDraftApprovalService.findBy(project) - .map(RoughDraftApproval::getHistory) - .orElseGet(Collections::emptyList); + return roughDraftApprovalService + .findBy(project) + .map(RoughDraftApproval::getHistory) + .orElseGet(Collections::emptyList); } private Collection expandMultiple(final Collection finalSeminarDecisions) { diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/MockRemoteUserFilter.java b/view/src/main/java/se/su/dsv/scipro/security/auth/MockRemoteUserFilter.java index b67ea8916d..c8ab375393 100755 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/MockRemoteUserFilter.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/MockRemoteUserFilter.java @@ -1,70 +1,81 @@ package se.su.dsv.scipro.security.auth; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Throw-away implementation of a servlet filter, main task is to fake the getRemoteUser() call for the request chain. */ public final class MockRemoteUserFilter implements Filter { - private static final Logger LOGGER = LoggerFactory.getLogger(MockRemoteUserFilter.class); - //Default value unless supplied via init parameter - private String fakedUser = "SOME_GUY"; - private FilterConfig cfg = null; + + private static final Logger LOGGER = LoggerFactory.getLogger(MockRemoteUserFilter.class); + //Default value unless supplied via init parameter + private String fakedUser = "SOME_GUY"; + private FilterConfig cfg = null; + /** - * Default constructor. + * Default constructor. */ - public MockRemoteUserFilter() { - } - /** - * @see Filter#destroy() - */ - @Override + public MockRemoteUserFilter() {} + + /** + * @see Filter#destroy() + */ + @Override public void destroy() { - cfg = null; - } - /** - * Wraps the passed request and alters the behavior of getRemoteUser() for later links of the chain. - * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - LOGGER.debug("Faking external authentication user: " + fakedUser); - if(cfg != null){ - HttpServletRequestWrapper wrapper = new ModifiedRemoteUserRequestWrapper((HttpServletRequest)request,fakedUser); - // pass the request along the filter chain - chain.doFilter(wrapper, response); - return; - } - chain.doFilter(request, response); - } - /** - * @see Filter#init(FilterConfig) - */ - @Override + cfg = null; + } + + /** + * Wraps the passed request and alters the behavior of getRemoteUser() for later links of the chain. + * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + LOGGER.debug("Faking external authentication user: " + fakedUser); + if (cfg != null) { + HttpServletRequestWrapper wrapper = new ModifiedRemoteUserRequestWrapper( + (HttpServletRequest) request, + fakedUser + ); + // pass the request along the filter chain + chain.doFilter(wrapper, response); + return; + } + chain.doFilter(request, response); + } + + /** + * @see Filter#init(FilterConfig) + */ + @Override public void init(FilterConfig fConfig) { - cfg = fConfig; - if(cfg!=null){ - fakedUser = cfg.getInitParameter("fakedUser"); - } - } - /** - * Private RequestWrapper, of no interest to anyone outside of this class. - */ - static class ModifiedRemoteUserRequestWrapper extends HttpServletRequestWrapper{ - private final String fakedUser; - ModifiedRemoteUserRequestWrapper(final HttpServletRequest request,final String fakedUser){ - super(request); - this.fakedUser = fakedUser; - } - @Override - public String getRemoteUser(){ - return fakedUser; - } - } + cfg = fConfig; + if (cfg != null) { + fakedUser = cfg.getInitParameter("fakedUser"); + } + } + + /** + * Private RequestWrapper, of no interest to anyone outside of this class. + */ + static class ModifiedRemoteUserRequestWrapper extends HttpServletRequestWrapper { + + private final String fakedUser; + + ModifiedRemoteUserRequestWrapper(final HttpServletRequest request, final String fakedUser) { + super(request); + this.fakedUser = fakedUser; + } + + @Override + public String getRemoteUser() { + return fakedUser; + } + } } diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleBasedAuthorizationStrategy.java b/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleBasedAuthorizationStrategy.java index 56f37288a5..9454c58f24 100644 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleBasedAuthorizationStrategy.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleBasedAuthorizationStrategy.java @@ -47,5 +47,4 @@ public class ProjectModuleBasedAuthorizationStrategy implements IAuthorizationSt ProjectModuleComponent internalGetAnnotation(Class authRequired) { return authRequired.getAnnotation(ProjectModuleComponent.class); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleComponent.java b/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleComponent.java index 59c2f294e8..d47e65206a 100644 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleComponent.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/ProjectModuleComponent.java @@ -1,13 +1,11 @@ package se.su.dsv.scipro.security.auth; -import se.su.dsv.scipro.system.ProjectModule; - import java.lang.annotation.*; +import se.su.dsv.scipro.system.ProjectModule; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface ProjectModuleComponent { - ProjectModule value(); } diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategy.java b/view/src/main/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategy.java index ac10fa0a02..2cba88061e 100755 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategy.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategy.java @@ -17,8 +17,8 @@ public class RoleBasedAuthorizationStrategy implements IAuthorizationStrategy { protected boolean instantiationAuthorized(Authorization annotation, SciProSession session) { //Check the users role for authorization to instantiate the component - for(Roles role : annotation.authorizedRoles()){ - if( session.authorizedForRole(role) ) { + for (Roles role : annotation.authorizedRoles()) { + if (session.authorizedForRole(role)) { return true; } } @@ -30,18 +30,16 @@ public class RoleBasedAuthorizationStrategy implements IAuthorizationStrategy { public boolean isInstantiationAuthorized(Class componentClass) { Authorization annotation = componentClass.getAnnotation(Authorization.class); if (annotation != null) { - if( !annotation.requiresLoggedInUser() ) { + if (!annotation.requiresLoggedInUser()) { return true; } SciProSession session = SciProSession.get(); //If page requires login and user isn't logged in, send them to login page first - if( annotation.requiresLoggedInUser() && !session.isLoggedIn() ){ + if (annotation.requiresLoggedInUser() && !session.isLoggedIn()) { throw new RestartResponseAtInterceptPageException(SSOPage.class); } //We only check pages for instantiation authorization, other components are handled via ActionAuthorization - return !(Page.class.isAssignableFrom(componentClass)) || instantiationAuthorized(annotation, session); - - + return (!(Page.class.isAssignableFrom(componentClass)) || instantiationAuthorized(annotation, session)); } return true; } @@ -50,7 +48,7 @@ public class RoleBasedAuthorizationStrategy implements IAuthorizationStrategy { public boolean isActionAuthorized(Component component, Action action) { Authorization annotation = getAnnotation(component); - if( annotation == null || !annotation.requiresLoggedInUser()) { + if (annotation == null || !annotation.requiresLoggedInUser()) { return true; } @@ -60,7 +58,6 @@ public class RoleBasedAuthorizationStrategy implements IAuthorizationStrategy { } return instantiationAuthorized(annotation, session) || allowed(action); - } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategy.java b/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategy.java index ff1a8cdd1b..660a6a2a85 100644 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategy.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategy.java @@ -47,5 +47,4 @@ public class SystemModuleBasedAuthorizationStrategy implements IAuthorizationStr SystemModuleComponent internalGetAnnotation(Class authRequired) { return authRequired.getAnnotation(SystemModuleComponent.class); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleComponent.java b/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleComponent.java index 79e4e62ee5..e93ec10498 100644 --- a/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleComponent.java +++ b/view/src/main/java/se/su/dsv/scipro/security/auth/SystemModuleComponent.java @@ -1,8 +1,7 @@ package se.su.dsv.scipro.security.auth; -import se.su.dsv.scipro.system.SystemModule; - import java.lang.annotation.*; +import se.su.dsv.scipro.system.SystemModule; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) diff --git a/view/src/main/java/se/su/dsv/scipro/session/SciProSession.java b/view/src/main/java/se/su/dsv/scipro/session/SciProSession.java index 6d7d573de8..75af2b3bff 100755 --- a/view/src/main/java/se/su/dsv/scipro/session/SciProSession.java +++ b/view/src/main/java/se/su/dsv/scipro/session/SciProSession.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.session; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; import org.apache.wicket.MetaDataKey; import org.apache.wicket.Session; import org.apache.wicket.injection.Injector; @@ -12,15 +17,9 @@ import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - public class SciProSession extends WebSession { - private final static MetaDataKey LOGGED_IN_USER_ID = new MetaDataKey<>() {}; + private static final MetaDataKey LOGGED_IN_USER_ID = new MetaDataKey<>() {}; @Inject private UserService userService; diff --git a/view/src/main/java/se/su/dsv/scipro/settings/pages/AbstractSettingsPage.java b/view/src/main/java/se/su/dsv/scipro/settings/pages/AbstractSettingsPage.java index fae9006513..463bc89a04 100755 --- a/view/src/main/java/se/su/dsv/scipro/settings/pages/AbstractSettingsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/settings/pages/AbstractSettingsPage.java @@ -1,36 +1,33 @@ package se.su.dsv.scipro.settings.pages; +import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.TAB_MULTIPLE_ROWS; + +import java.util.ArrayList; +import java.util.List; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.notifications.pages.SupervisorNotificationSettingsPage; import se.su.dsv.scipro.supervisor.pages.SupervisorProfilePage; -import java.util.ArrayList; -import java.util.List; - -import static se.su.dsv.scipro.components.AbstractMenuPanel.MenuType.TAB_MULTIPLE_ROWS; - - public abstract class AbstractSettingsPage extends MenuPage { public AbstractSettingsPage() { - add(new AbstractMenuPanel("menuPanel", AbstractSettingsPage.class, this.getClass()) { + add( + new AbstractMenuPanel("menuPanel", AbstractSettingsPage.class, this.getClass()) { + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("Basic profile", BasicProfilePage.class)); + items.add(new MenuItem("Supervisor profile", SupervisorProfilePage.class)); + items.add(new MenuItem("Notification settings", SupervisorNotificationSettingsPage.class)); + return items; + } - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("Basic profile", BasicProfilePage.class)); - items.add(new MenuItem("Supervisor profile", SupervisorProfilePage.class)); - items.add(new MenuItem("Notification settings", SupervisorNotificationSettingsPage.class)); - return items; + @Override + protected MenuType getMenuType() { + return TAB_MULTIPLE_ROWS; + } } - - @Override - protected MenuType getMenuType() { - return TAB_MULTIPLE_ROWS; - } - - }); + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/settings/pages/BasicProfilePage.java b/view/src/main/java/se/su/dsv/scipro/settings/pages/BasicProfilePage.java index c5bd717e46..6405d4e89a 100755 --- a/view/src/main/java/se/su/dsv/scipro/settings/pages/BasicProfilePage.java +++ b/view/src/main/java/se/su/dsv/scipro/settings/pages/BasicProfilePage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.settings.pages; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextArea; @@ -14,9 +15,8 @@ import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; - public class BasicProfilePage extends AbstractSettingsPage { + static final String FEEDBACK = "feedback"; static final String NAME = "name"; static final String EMAIL = "email"; @@ -38,12 +38,18 @@ public class BasicProfilePage extends AbstractSettingsPage { return profileService.findByUser(loggedInUser()); } }; - add(new UserProfileImage("image", new LoadableDetachableModel<>() { - @Override - public User load() { - return loggedInUser(); - } - }, UserProfileImage.Size.LARGE)); + add( + new UserProfileImage( + "image", + new LoadableDetachableModel<>() { + @Override + public User load() { + return loggedInUser(); + } + }, + UserProfileImage.Size.LARGE + ) + ); add(new ProfileForm(FORM, profile)); } @@ -55,8 +61,14 @@ public class BasicProfilePage extends AbstractSettingsPage { add(new Label(NAME, loggedInUser().getFullName())); add(new Label(EMAIL, loggedInUser().getEmailAddress())); add(new TextField<>(SKYPE, LambdaModel.of(model, UserProfile::getSkypeId, UserProfile::setSkypeId))); - add(new TextField<>(PHONE, LambdaModel.of(model, UserProfile::getPhoneNumber, UserProfile::setPhoneNumber))); - add(new TextArea<>(OTHER, LambdaModel.of(model, UserProfile::getOtherInfo, UserProfile::setOtherInfo)).add(StringValidator.maximumLength(MAX_LENGTH))); + add( + new TextField<>(PHONE, LambdaModel.of(model, UserProfile::getPhoneNumber, UserProfile::setPhoneNumber)) + ); + add( + new TextArea<>(OTHER, LambdaModel.of(model, UserProfile::getOtherInfo, UserProfile::setOtherInfo)).add( + StringValidator.maximumLength(MAX_LENGTH) + ) + ); } @Override @@ -64,6 +76,5 @@ public class BasicProfilePage extends AbstractSettingsPage { profileService.save(getModelObject()); info(getString("profile.saved")); } - } } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AbstractAdminStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AbstractAdminStatisticsPage.java index 249616bbae..23e2637e65 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AbstractAdminStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AbstractAdminStatisticsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.markup.html.panel.FeedbackPanel; import se.su.dsv.scipro.admin.pages.AbstractAdminPage; import se.su.dsv.scipro.admin.pages.AdminSurveyStatisticsPage; @@ -13,40 +15,52 @@ import se.su.dsv.scipro.peer.AdminPeersPage; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import java.util.ArrayList; -import java.util.List; - @Authorization(authorizedRoles = { Roles.ADMIN }) public abstract class AbstractAdminStatisticsPage extends AbstractAdminPage { protected AbstractAdminStatisticsPage() { add(new FeedbackPanel("feedbackPanel").setOutputMarkupId(true)); - add(new AbstractMenuPanel("menuPanel", AbstractAdminStatisticsPage.class, this.getClass()){ - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("Ideas", AdminIdeaStatisticsPage.class)); - items.add(new MenuItem("Idea statuses", AdminIdeaStatusStatisticsPage.class)); - items.add(new MenuItem("Unmet targets", AdminUnmetTargetsStatisticsPage.class)); - items.add(new MenuItem("Peers", AdminPeersPage.class, MenuHighlightAdminPeer.class)); - items.add(new MenuItem("Supervisors commitments", SupervisorStatisticsPage.class)); - items.add(new MenuItem("Projects connected to external org", ProjectExternalStatisticsPage.class)); - items.add(new MenuItem("Units", AdminUnitStatisticsPage.class)); - items.add(new MenuItem("Authors", AdminAuthorsStatisticsPage.class, MenuHighlightAdminAuthorStatistics.class)); - items.add(new MenuItem("Milestones", AdminMilestoneStatisticsPage.class, MenuHighlightAdminMileStoneStatistics.class)); - items.add(new MenuItem("Milestone progress", AdminMilestoneStatisticsProgressPage.class)); - items.add(new MenuItem("Milestone median", AdminMedianMilestonePage.class)); - items.add(new MenuItem("Unfinished final seminars", AdminUnfinishedFinalSeminarsPage.class)); - items.add(new MenuItem("Reviewer deadlines", AdminReviewerDeadlinesPage.class)); - items.add(new MenuItem("People", AdminPeopleStatisticsPage.class)); - items.add(new MenuItem("Final seminars", AdminFinalSeminarStatisticsPage.class)); - items.add(new MenuItem("Survey", AdminSurveyStatisticsPage.class)); - return items; - } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; - } - }); - } -} \ No newline at end of file + add( + new AbstractMenuPanel("menuPanel", AbstractAdminStatisticsPage.class, this.getClass()) { + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("Ideas", AdminIdeaStatisticsPage.class)); + items.add(new MenuItem("Idea statuses", AdminIdeaStatusStatisticsPage.class)); + items.add(new MenuItem("Unmet targets", AdminUnmetTargetsStatisticsPage.class)); + items.add(new MenuItem("Peers", AdminPeersPage.class, MenuHighlightAdminPeer.class)); + items.add(new MenuItem("Supervisors commitments", SupervisorStatisticsPage.class)); + items.add(new MenuItem("Projects connected to external org", ProjectExternalStatisticsPage.class)); + items.add(new MenuItem("Units", AdminUnitStatisticsPage.class)); + items.add( + new MenuItem( + "Authors", + AdminAuthorsStatisticsPage.class, + MenuHighlightAdminAuthorStatistics.class + ) + ); + items.add( + new MenuItem( + "Milestones", + AdminMilestoneStatisticsPage.class, + MenuHighlightAdminMileStoneStatistics.class + ) + ); + items.add(new MenuItem("Milestone progress", AdminMilestoneStatisticsProgressPage.class)); + items.add(new MenuItem("Milestone median", AdminMedianMilestonePage.class)); + items.add(new MenuItem("Unfinished final seminars", AdminUnfinishedFinalSeminarsPage.class)); + items.add(new MenuItem("Reviewer deadlines", AdminReviewerDeadlinesPage.class)); + items.add(new MenuItem("People", AdminPeopleStatisticsPage.class)); + items.add(new MenuItem("Final seminars", AdminFinalSeminarStatisticsPage.class)); + items.add(new MenuItem("Survey", AdminSurveyStatisticsPage.class)); + return items; + } + + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } + } + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AbstractMilestoneDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/AbstractMilestoneDetailsPanel.java index 898868c9bb..633f80b250 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AbstractMilestoneDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AbstractMilestoneDetailsPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; @@ -13,10 +16,6 @@ import se.su.dsv.scipro.milestones.dataobjects.Milestone; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MileStoneService; -import jakarta.inject.Inject; -import java.util.Iterator; -import java.util.List; - public abstract class AbstractMilestoneDetailsPanel extends GenericPanel { public static final String TITLE = "title"; @@ -27,7 +26,11 @@ public abstract class AbstractMilestoneDetailsPanel extends GenericPanel model, MileStoneService.Filter filter) { + public AbstractMilestoneDetailsPanel( + String id, + IModel model, + MileStoneService.Filter filter + ) { super(id, model); this.filter = filter; @@ -39,10 +42,11 @@ public abstract class AbstractMilestoneDetailsPanel extends GenericPanel provider = new SortableDataProvider<>() { - @Override public Iterator iterator(long first, long count) { - return mileStoneService.findCompletedMilestones(getModelObject(), filter, new PageAdapter(first, count, getSort())).iterator(); + return mileStoneService + .findCompletedMilestones(getModelObject(), filter, new PageAdapter(first, count, getSort())) + .iterator(); } @Override @@ -59,6 +63,5 @@ public abstract class AbstractMilestoneDetailsPanel extends GenericPanel(TABLE, createColumns(), provider)); } - protected abstract List> createColumns(); - + protected abstract List> createColumns(); } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPage.java index cbb39b626e..dbc19a540b 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPage.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.statistics; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -17,14 +23,9 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; - -import static java.util.Arrays.asList; - -public class AdminAuthorsStatisticsPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminAuthorStatistics { +public class AdminAuthorsStatisticsPage + extends AbstractAdminStatisticsPage + implements MenuHighlightAdminAuthorStatistics { protected static final String CONTAINER = "container"; protected static final String PROJECT_TYPE_FILTER = "projectTypeFilter"; @@ -36,6 +37,7 @@ public class AdminAuthorsStatisticsPage extends AbstractAdminStatisticsPage impl @Inject private ProjectService projectService; + @Inject private ProjectTypeService projectTypeService; @@ -82,21 +84,29 @@ public class AdminAuthorsStatisticsPage extends AbstractAdminStatisticsPage impl } private void addDateFilter() { - container.add(new DeactivatableDatePickerPanel(DATE_FILTER, + container.add( + new DeactivatableDatePickerPanel( + DATE_FILTER, LambdaModel.of(params::getCreatedAfter, params::setCreatedAfter), - LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(container); + LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(container); + } } - }); + ); } private void addProjectTypeFilter() { - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>(PROJECT_TYPE_FILTER, - projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + PROJECT_TYPE_FILTER, + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -110,10 +120,12 @@ public class AdminAuthorsStatisticsPage extends AbstractAdminStatisticsPage impl } private void addProjectStatusFilter() { - AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>(STATUS_FILTER, - new ArrayList<>(asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED)), - asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this)) { + AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>( + STATUS_FILTER, + new ArrayList<>(asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED)), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onUpdate(AjaxRequestTarget target) { params.setStatuses(new HashSet<>(getModelObject())); @@ -123,4 +135,4 @@ public class AdminAuthorsStatisticsPage extends AbstractAdminStatisticsPage impl container.add(projectStatus); params.setStatuses(new HashSet<>(projectStatus.getModelObject())); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPage.java index c6615908ab..4e9a89764a 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPage.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.statistics; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -17,7 +22,6 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LambdaModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; -import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.components.AjaxCheckBoxMultipleChoice; import se.su.dsv.scipro.components.EnumLambdaColumn; import se.su.dsv.scipro.components.ExportableDataPanel; @@ -34,23 +38,21 @@ import se.su.dsv.scipro.reviewing.FinalSeminarApproval; import se.su.dsv.scipro.reviewing.FinalSeminarApprovalService; import se.su.dsv.scipro.reviewing.ProjectFinalSeminarStatisticsService; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.PageRequest; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - -import static java.util.Arrays.asList; - public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage { @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectFinalSeminarStatisticsService projectFinalSeminarStatisticsService; + @Inject private FinalSeminarApprovalService finalSeminarApprovalService; + @Inject private FinalSeminarService finalSeminarService; @@ -58,7 +60,6 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage private final WebMarkupContainer wmc; public AdminFinalSeminarStatisticsPage() { - add(new FilterForm("filterForm")); wmc = new WebMarkupContainer("wmc"); @@ -69,7 +70,9 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage @Override public Iterator iterator(long first, long count) { PageRequest pageRequest = new PageAdapter(first, count, getSort()); - return projectFinalSeminarStatisticsService.finalSeminarStatisticsNoOkFromReviewer(filter, pageRequest).iterator(); + return projectFinalSeminarStatisticsService + .finalSeminarStatisticsNoOkFromReviewer(filter, pageRequest) + .iterator(); } @Override @@ -84,13 +87,12 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage }; fsNoOkProvider.setSort("dateCreated", SortOrder.DESCENDING); wmc.add(new ExportableDataPanel<>("fsNoOk", createColumns(), fsNoOkProvider)); - + wmc.add(new Label("finalSeminars", getFinalSeminars())); wmc.add(new Label("finalSeminarsOkFromReviewer", getFinalSeminarsOkFromReviewer())); - } - private LoadableDetachableModel getFinalSeminars(){ + private LoadableDetachableModel getFinalSeminars() { return new LoadableDetachableModel<>() { @Override protected Long load() { @@ -99,7 +101,7 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage }; } - private LoadableDetachableModel getFinalSeminarsOkFromReviewer(){ + private LoadableDetachableModel getFinalSeminarsOkFromReviewer() { return new LoadableDetachableModel<>() { @Override protected Long load() { @@ -116,26 +118,49 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage columns.add(new EnumLambdaColumn<>(Model.of("Status"), Project::getProjectStatus)); columns.add(new UserColumn<>(Model.of("Supervisor"), "headSupervisor.fullName", Project::getHeadSupervisor)); - columns.add(new AbstractColumn<>(Model.of("Current final seminar approval request status")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - FinalSeminarApproval byProject = finalSeminarApprovalService.findByProject(rowModel.getObject()); - cellItem.add(new Label(componentId, byProject == null ? "-" : byProject.getCurrentStatus())); + columns.add( + new AbstractColumn<>(Model.of("Current final seminar approval request status")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + FinalSeminarApproval byProject = finalSeminarApprovalService.findByProject(rowModel.getObject()); + cellItem.add(new Label(componentId, byProject == null ? "-" : byProject.getCurrentStatus())); + } } - }); - columns.add(new AbstractColumn<>(Model.of("Current final seminar approval request reason")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - FinalSeminarApproval byProject = finalSeminarApprovalService.findByProject(rowModel.getObject()); - cellItem.add(new Label(componentId, byProject == null ? "-" : byProject.getCurrentReason())); + ); + columns.add( + new AbstractColumn<>(Model.of("Current final seminar approval request reason")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + FinalSeminarApproval byProject = finalSeminarApprovalService.findByProject(rowModel.getObject()); + cellItem.add(new Label(componentId, byProject == null ? "-" : byProject.getCurrentReason())); + } } - }); - columns.add(new AbstractColumn<>(Model.of("Supervisor reason for creating final seminar")) { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new Label(componentId, finalSeminarService.findByProject(rowModel.getObject()).getCreationReason())); + ); + columns.add( + new AbstractColumn<>(Model.of("Supervisor reason for creating final seminar")) { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new Label( + componentId, + finalSeminarService.findByProject(rowModel.getObject()).getCreationReason() + ) + ); + } } - }); + ); return columns; } @@ -143,15 +168,18 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage public FilterForm(String id) { super(id); - filter = new ProjectFinalSeminarStatisticsService.Filter(); filter.setFinalSeminarCreatedBefore(new Date()); filter.setFinalSeminarCreatedAfter(Date.from(ZonedDateTime.now().minusMonths(6).toInstant())); - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -163,33 +191,43 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage filter.setProjectTypes(projectType.getModelObject()); add(projectType); - add(new DeactivatableDatePickerPanel("dateFilter", + add( + new DeactivatableDatePickerPanel( + "dateFilter", LambdaModel.of(filter::getCreatedAfter, filter::setCreatedAfter), - LambdaModel.of(filter::getCreatedBefore, filter::setCreatedBefore)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(wmc); + LambdaModel.of(filter::getCreatedBefore, filter::setCreatedBefore) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); - add(new DatePickerPanel("fsCreatedBetween", + add( + new DatePickerPanel( + "fsCreatedBetween", LambdaModel.of(filter::getFinalSeminarCreatedAfter, filter::setFinalSeminarCreatedAfter), - LambdaModel.of(filter::getFinalSeminarCreatedBefore, filter::setFinalSeminarCreatedBefore)) { - @Override - public void updateStartDate(final AjaxRequestTarget target) { - target.add(wmc); - } + LambdaModel.of(filter::getFinalSeminarCreatedBefore, filter::setFinalSeminarCreatedBefore) + ) { + @Override + public void updateStartDate(final AjaxRequestTarget target) { + target.add(wmc); + } - @Override - public void updateEndDate(final AjaxRequestTarget target) { - target.add(wmc); + @Override + public void updateEndDate(final AjaxRequestTarget target) { + target.add(wmc); + } } - }); + ); - AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>("statusFilter", - asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED), - asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this)) { + AjaxCheckBoxMultipleChoice projectStatus = new AjaxCheckBoxMultipleChoice<>( + "statusFilter", + asList(ProjectStatus.ACTIVE, ProjectStatus.COMPLETED), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { @Override public void onUpdate(AjaxRequestTarget target) { filter.setStatuses(new HashSet<>(getModelObject())); @@ -200,4 +238,4 @@ public class AdminFinalSeminarStatisticsPage extends AbstractAdminStatisticsPage filter.setStatuses(new HashSet<>(projectStatus.getModelObject())); } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPage.java index 7f826b19f1..af9c991e77 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPage.java @@ -5,10 +5,14 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminMileStoneS import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MileStoneService; -public class AdminIndividualMilestoneDetailsPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminMileStoneStatistics { +public class AdminIndividualMilestoneDetailsPage + extends AbstractAdminStatisticsPage + implements MenuHighlightAdminMileStoneStatistics { - public AdminIndividualMilestoneDetailsPage(IModel templateModel, MileStoneService.Filter filter) { + public AdminIndividualMilestoneDetailsPage( + IModel templateModel, + MileStoneService.Filter filter + ) { add(new IndividualMilestoneDetailsPanel("details", templateModel, filter)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePage.java index df9527de1d..cc60c58d42 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePage.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.statistics; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.*; @@ -17,37 +22,34 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.List; - -import static java.util.Arrays.asList; - public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { @Inject private ProjectTypeService projectTypeService; + @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Inject private MilestoneStatisticsService milestoneStatisticsService; private MilestoneStatisticsService.Filter params; public AdminMedianMilestonePage() { - params = new MilestoneStatisticsService.Filter(); - + add(new FilterForm("selection")); WebMarkupContainer wmc = new WebMarkupContainer("wmc") { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(params.getFirstMilestone()!=null && - params.getSecondMilestone()!=null && - getLoadedCount().getObject() != null && - getLoadedCount().getObject() > 0); + setVisibilityAllowed( + params.getFirstMilestone() != null && + params.getSecondMilestone() != null && + getLoadedCount().getObject() != null && + getLoadedCount().getObject() > 0 + ); } }; add(wmc); @@ -55,10 +57,9 @@ public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { wmc.add(new Label("median", getLoadedMedian())); wmc.add(new Label("count", getLoadedCount())); wmc.add(new Label("notCompletedBoth", getLoadedNotCompletedCount())); - } - private LoadableDetachableModel getLoadedNotCompletedCount(){ + private LoadableDetachableModel getLoadedNotCompletedCount() { return new LoadableDetachableModel<>() { @Override protected Long load() { @@ -67,7 +68,7 @@ public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { }; } - private LoadableDetachableModel getLoadedMedian(){ + private LoadableDetachableModel getLoadedMedian() { return new LoadableDetachableModel<>() { @Override protected Long load() { @@ -76,7 +77,7 @@ public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { }; } - private LoadableDetachableModel getLoadedCount(){ + private LoadableDetachableModel getLoadedCount() { return new LoadableDetachableModel<>() { @Override protected Long load() { @@ -89,47 +90,64 @@ public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { public FilterForm(String id) { super(id); + add( + new SupervisorAutoComplete( + "supervisorFilter", + LambdaModel.of(params::getHeadSupervisor, params::setHeadSupervisor) + ) + ); - add(new SupervisorAutoComplete("supervisorFilter", LambdaModel.of(params::getHeadSupervisor, params::setHeadSupervisor))); - - add(new DeactivatableDatePickerPanel("dates", + add( + new DeactivatableDatePickerPanel( + "dates", LambdaModel.of(params::getCreatedAfter, params::setCreatedAfter), - LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore))); + LambdaModel.of(params::getCreatedBefore, params::setCreatedBefore) + ) + ); params.setStatuses(asList(ProjectStatus.values())); - CheckBoxMultipleChoice projectStatus = new BootstrapCheckBoxMultipleChoice<>("statusFilter", - LambdaModel.of(params::getStatuses, params::setStatuses), - asList(ProjectStatus.values()), - new EnumChoiceRenderer<>(this) - ); + CheckBoxMultipleChoice projectStatus = new BootstrapCheckBoxMultipleChoice<>( + "statusFilter", + LambdaModel.of(params::getStatuses, params::setStatuses), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ); projectStatus.setRequired(true); add(projectStatus); - params.setProjectTypes(projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))); - CheckBoxMultipleChoice projectType = new BootstrapCheckBoxMultipleChoice<>("projectTypeFilter", - LambdaModel.of(params::getProjectTypes, params::setProjectTypes), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + params.setProjectTypes( + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ) + ); + CheckBoxMultipleChoice projectType = new BootstrapCheckBoxMultipleChoice<>( + "projectTypeFilter", + LambdaModel.of(params::getProjectTypes, params::setProjectTypes), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) ); projectType.setRequired(true); add(projectType); IModel> templates = getTemplates(); - DropDownChoice first = new DropDownChoice<>("first", - LambdaModel.of(params::getFirstMilestone, params::setFirstMilestone), - templates, - new MilestoneActivityTemplateChoiceRenderer()); + DropDownChoice first = new DropDownChoice<>( + "first", + LambdaModel.of(params::getFirstMilestone, params::setFirstMilestone), + templates, + new MilestoneActivityTemplateChoiceRenderer() + ); first.setRequired(true); add(first); - DropDownChoice second = new DropDownChoice<>("second", - LambdaModel.of(params::getSecondMilestone, params::setSecondMilestone), - templates, - new MilestoneActivityTemplateChoiceRenderer()); + DropDownChoice second = new DropDownChoice<>( + "second", + LambdaModel.of(params::getSecondMilestone, params::setSecondMilestone), + templates, + new MilestoneActivityTemplateChoiceRenderer() + ); second.setRequired(true); add(second); - } } @@ -143,4 +161,4 @@ public class AdminMedianMilestonePage extends AbstractAdminStatisticsPage { } }; } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPage.java index 537429d172..b17208f159 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPage.java @@ -7,19 +7,28 @@ import se.su.dsv.scipro.milestones.service.MileStoneService; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminMilestoneStatisticsPage extends AbstractAdminStatisticsPage { public AdminMilestoneStatisticsPage() { - add(new MilestoneStatisticsPanel("statistics", new MilestoneStatisticsPanel.PageSupplier() { - @Override - public Page individualPage(IModel model, MileStoneService.Filter filter) { - return new AdminIndividualMilestoneDetailsPage(model, filter); - } - @Override - public Page projectPage(IModel model, MileStoneService.Filter filter) { - return new AdminProjectMilestoneDetailsPage(model, filter); - } - })); + add( + new MilestoneStatisticsPanel( + "statistics", + new MilestoneStatisticsPanel.PageSupplier() { + @Override + public Page individualPage( + IModel model, + MileStoneService.Filter filter + ) { + return new AdminIndividualMilestoneDetailsPage(model, filter); + } + + @Override + public Page projectPage(IModel model, MileStoneService.Filter filter) { + return new AdminProjectMilestoneDetailsPage(model, filter); + } + } + ) + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsProgressPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsProgressPage.java index 38b1b9b1ea..cfa772cdcb 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsProgressPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsProgressPage.java @@ -5,6 +5,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; @Authorization(authorizedRoles = Roles.ADMIN) public class AdminMilestoneStatisticsProgressPage extends AbstractAdminStatisticsPage { + public AdminMilestoneStatisticsProgressPage() { add(new MilestoneStatisticsProgressPanel("projectProgress")); } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPage.java index 606d8e4298..7226df99dc 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.List; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -11,11 +14,9 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; -import java.util.stream.Collectors; - -public class AdminMultipleAuthorsStatisticsPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminAuthorStatistics { +public class AdminMultipleAuthorsStatisticsPage + extends AbstractAdminStatisticsPage + implements MenuHighlightAdminAuthorStatistics { public static final String AUTHOR_LIST = "authorList"; public static final String AUTHOR_NAME = "fullName"; @@ -28,21 +29,20 @@ public class AdminMultipleAuthorsStatisticsPage extends AbstractAdminStatisticsP public AdminMultipleAuthorsStatisticsPage(ProjectService.Filter filter) { this.filter = filter; - add(new ListView<>(AUTHOR_LIST, getMultipleAuthors()) { - @Override - protected void populateItem(ListItem item) { - item.add(new UserLabel(AUTHOR_NAME, item.getModel())); - item.add(new Label(PROJECTS, getProjects(item.getModel()))); + add( + new ListView<>(AUTHOR_LIST, getMultipleAuthors()) { + @Override + protected void populateItem(ListItem item) { + item.add(new UserLabel(AUTHOR_NAME, item.getModel())); + item.add(new Label(PROJECTS, getProjects(item.getModel()))); + } } - }); + ); } private String getProjects(IModel model) { filter.setAuthorUser(model.getObject()); - return projectService.findAll(filter) - .stream() - .map(Project::getTitle) - .collect(Collectors.joining(", ")); + return projectService.findAll(filter).stream().map(Project::getTitle).collect(Collectors.joining(", ")); } private LoadableDetachableModel> getMultipleAuthors() { diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPage.java index 3b7b2fac39..145feabd25 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; @@ -15,37 +17,40 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.Arrays; - public class AdminPeopleStatisticsPage extends AbstractAdminStatisticsPage { @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectPeopleStatisticsService projectPeopleStatisticsService; private ProjectService.Filter params; public AdminPeopleStatisticsPage() { - - final WebMarkupContainer container = new WebMarkupContainer("container"){ + final WebMarkupContainer container = new WebMarkupContainer("container") { @Override protected void onConfigure() { super.onConfigure(); - setVisibilityAllowed(params.getProjectTypes()!=null && !params.getProjectTypes().isEmpty()); + setVisibilityAllowed(params.getProjectTypes() != null && !params.getProjectTypes().isEmpty()); } }; container.setOutputMarkupPlaceholderTag(true); add(container); params = new ProjectService.Filter(); - params.setProjectTypes(projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))); + params.setProjectTypes( + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ) + ); - AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - LambdaModel.of(params::getProjectTypes, params::setProjectTypes), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectType = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + LambdaModel.of(params::getProjectTypes, params::setProjectTypes), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { target.add(container); @@ -57,33 +62,52 @@ public class AdminPeopleStatisticsPage extends AbstractAdminStatisticsPage { container.add(new InfoPanel("info", new ResourceModel("info"))); - container.add(new Label("students", new LoadableDetachableModel() { - @Override - protected Long load() { - return projectPeopleStatisticsService.peopleStudents(params); - } - })); + container.add( + new Label( + "students", + new LoadableDetachableModel() { + @Override + protected Long load() { + return projectPeopleStatisticsService.peopleStudents(params); + } + } + ) + ); - container.add(new Label("headSupervisors", new LoadableDetachableModel() { - @Override - protected Long load() { - return projectPeopleStatisticsService.peopleHeadSupervisors(params); - } - })); + container.add( + new Label( + "headSupervisors", + new LoadableDetachableModel() { + @Override + protected Long load() { + return projectPeopleStatisticsService.peopleHeadSupervisors(params); + } + } + ) + ); - container.add(new Label("coSupervisors", new LoadableDetachableModel() { - @Override - protected Long load() { - return projectPeopleStatisticsService.peopleCoSupervisors(params); - } - })); + container.add( + new Label( + "coSupervisors", + new LoadableDetachableModel() { + @Override + protected Long load() { + return projectPeopleStatisticsService.peopleCoSupervisors(params); + } + } + ) + ); - container.add(new Label("reviewers", new LoadableDetachableModel() { - @Override - protected Long load() { - return projectPeopleStatisticsService.peopleReviewers(params); - } - })); + container.add( + new Label( + "reviewers", + new LoadableDetachableModel() { + @Override + protected Long load() { + return projectPeopleStatisticsService.peopleReviewers(params); + } + } + ) + ); } } - diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPage.java index 0828bef55c..8f5f51aa10 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPage.java @@ -5,10 +5,14 @@ import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightAdminMileStoneS import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MileStoneService; -public class AdminProjectMilestoneDetailsPage extends AbstractAdminStatisticsPage implements MenuHighlightAdminMileStoneStatistics { +public class AdminProjectMilestoneDetailsPage + extends AbstractAdminStatisticsPage + implements MenuHighlightAdminMileStoneStatistics { - public AdminProjectMilestoneDetailsPage(IModel templateModel, MileStoneService.Filter filter) { + public AdminProjectMilestoneDetailsPage( + IModel templateModel, + MileStoneService.Filter filter + ) { add(new ProjectMilestoneDetailsPanel("details", templateModel, filter)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPage.java index 8a6c8fe8c0..038617a737 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; @@ -27,14 +30,13 @@ import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Pair; -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { + private DatePickerPanel datePicker; + @Inject private ReviewerDeadlineFollowupService reviewerDeadlineFollowupService; + @Inject private DaysService daysService; @@ -43,7 +45,6 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { private WebMarkupContainer wmc; public AdminReviewerDeadlinesPage() { - addTabs(); addDatePickerForm(); @@ -59,47 +60,56 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { fsContainer.setOutputMarkupId(true); add(fsContainer); - rdContainer.add(new AjaxLink<>("roughDraftLink") { - @Override - public void onClick(AjaxRequestTarget target) { - step = ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL; - rdContainer.add(new AttributeModifier("class", new Model<>("active"))); - fsContainer.add(new AttributeModifier("class", new Model<>(""))); - target.add(rdContainer); - target.add(fsContainer); - target.add(wmc); + rdContainer.add( + new AjaxLink<>("roughDraftLink") { + @Override + public void onClick(AjaxRequestTarget target) { + step = ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL; + rdContainer.add(new AttributeModifier("class", new Model<>("active"))); + fsContainer.add(new AttributeModifier("class", new Model<>(""))); + target.add(rdContainer); + target.add(fsContainer); + target.add(wmc); + } } - }); + ); - fsContainer.add(new AjaxLink<>("finalSeminarLink") { - @Override - public void onClick(AjaxRequestTarget target) { - step = ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL; - rdContainer.add(new AttributeModifier("class", new Model<>(""))); - fsContainer.add(new AttributeModifier("class", new Model<>("active"))); - target.add(rdContainer); - target.add(fsContainer); - target.add(wmc); + fsContainer.add( + new AjaxLink<>("finalSeminarLink") { + @Override + public void onClick(AjaxRequestTarget target) { + step = ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL; + rdContainer.add(new AttributeModifier("class", new Model<>(""))); + fsContainer.add(new AttributeModifier("class", new Model<>("active"))); + target.add(rdContainer); + target.add(fsContainer); + target.add(wmc); + } } - }); + ); } private void addDatePickerForm() { Date startDate = Date.from(ZonedDateTime.now().minusMonths(1).toInstant()); Date endDate = Date.from(ZonedDateTime.now().minusDays(1).toInstant()); datePicker = new DatePickerPanel("filter", startDate, endDate); - add(new Form("form") { - { - add(datePicker); + add( + new Form("form") { + { + add(datePicker); + } } - }); + ); } private void addLateApprovalsList() { wmc = new WebMarkupContainer("container"); wmc.setOutputMarkupId(true); add(wmc); - ListView> listView = new ListView<>("reviewerApprovals", getLateReviewerApprovals()) { + ListView> listView = new ListView<>( + "reviewerApprovals", + getLateReviewerApprovals() + ) { @Override protected void populateItem(ListItem> item) { final IModel reviewerApproval = item.getModel().map(Pair::getHead); @@ -114,7 +124,9 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { item.add(new Label("late", getLateLabel(deadline, decisionDate))); item.add(new DateLabel("tail.requested", decision.map(Decision::getRequested))); item.add(new EnumLabel<>("tail.status", decision.map(Decision::getStatus))); - item.add(new Label("reviewer.unit", project.map(Project::getReviewer).map(User::getUnit).map(Unit::getTitle))); + item.add( + new Label("reviewer.unit", project.map(Project::getReviewer).map(User::getUnit).map(Unit::getTitle)) + ); } }; wmc.add(listView); @@ -130,9 +142,19 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { @Override protected List> load() { if (step == ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL) { - return reviewerDeadlineFollowupService.getLateReviewerApprovals(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL, datePicker.getStartDate(), datePicker.getEndDate(), new Date()); + return reviewerDeadlineFollowupService.getLateReviewerApprovals( + ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL, + datePicker.getStartDate(), + datePicker.getEndDate(), + new Date() + ); } else { - return reviewerDeadlineFollowupService.getLateReviewerApprovals(ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL, datePicker.getStartDate(), datePicker.getEndDate(), new Date()); + return reviewerDeadlineFollowupService.getLateReviewerApprovals( + ReviewerApproval.Step.FINAL_SEMINAR_APPROVAL, + datePicker.getStartDate(), + datePicker.getEndDate(), + new Date() + ); } } }; @@ -142,8 +164,13 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptHeaderItem.forUrl("//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js")); - response.render(JavaScriptHeaderItem.forUrl("//cdn.datatables.net/plug-ins/3cfcc339e89/integration/bootstrap/3/dataTables.bootstrap.js")); - response.render(OnDomReadyHeaderItem.forScript( + response.render( + JavaScriptHeaderItem.forUrl( + "//cdn.datatables.net/plug-ins/3cfcc339e89/integration/bootstrap/3/dataTables.bootstrap.js" + ) + ); + response.render( + OnDomReadyHeaderItem.forScript( "$(\"table.table\").dataTable({\n" + " paging: false,\n" + " filter: true,\n" + @@ -153,7 +180,8 @@ public class AdminReviewerDeadlinesPage extends AbstractAdminStatisticsPage { " language: {\n" + " info: 'Showing _START_ to _END_ of _TOTAL_'\n" + " }\n" + - " });")); + " });" + ) + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminStatisticsPage.java index 3faa36fc98..6844b475df 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminStatisticsPage.java @@ -4,6 +4,4 @@ import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; @Authorization(authorizedRoles = { Roles.ADMIN }) -public class AdminStatisticsPage extends AbstractAdminStatisticsPage { - -} +public class AdminStatisticsPage extends AbstractAdminStatisticsPage {} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPage.java index 50b25612b1..794519ae87 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPage.java @@ -1,117 +1,134 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; -import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.danekja.java.util.function.serializable.SerializableFunction; -import se.su.dsv.scipro.components.DateColumn; -import se.su.dsv.scipro.components.ExportableDataPanel; -import se.su.dsv.scipro.components.ListAdapterModel; -import se.su.dsv.scipro.components.datatables.MultipleUsersColumn; -import se.su.dsv.scipro.data.DetachableServiceModel; -import se.su.dsv.scipro.data.enums.DateStyle; -import se.su.dsv.scipro.dataproviders.PageAdapter; -import se.su.dsv.scipro.date.DatePickerPanel; -import se.su.dsv.scipro.finalseminar.FinalSeminar; -import se.su.dsv.scipro.finalseminar.FinalSeminarService; -import se.su.dsv.scipro.profile.UserLinkPanel; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - -import static java.util.Arrays.asList; - -public class AdminUnfinishedFinalSeminarsPage extends AbstractAdminStatisticsPage { - private static Date SIX_MONTHS_AGO = Date.from(ZonedDateTime.now().minusMonths(6).toInstant()); - private static Date SEVEN_DAYS_AGO = Date.from(ZonedDateTime.now().minusDays(7).toInstant()); - @Inject - private FinalSeminarService finalSeminarService; - - public AdminUnfinishedFinalSeminarsPage() { - final IModel seminarAfter = Model.of(SIX_MONTHS_AGO); - final IModel seminarBefore = Model.of(SEVEN_DAYS_AGO); - add(new Form("form") { { - add(new DatePickerPanel("seminarDate", seminarAfter, seminarBefore)); - }}); - add(new ExportableDataPanel<>("table", columns(), new UnfinishedSeminarProvider(seminarAfter, seminarBefore))); - } - - private List> columns() { - return asList( - new LambdaColumn<>(Model.of("Title"), "project.title", FinalSeminar::getProjectTitle), - new SupervisorColumn(Model.of("Head supervisor"), "project.headSupervisor.firstName"), - new DateColumn<>(Model.of("Seminar date"), FinalSeminar::getStartDate, "startDate", DateStyle.DATETIME), - new ParticipationColumn(Model.of("Not graded respondents"), FinalSeminar::getNotGradedRespondents), - new ParticipationColumn(Model.of("Not graded opponents"), FinalSeminar::getNotGradedOpponents), - new ParticipationColumn(Model.of("Not graded active participants"), FinalSeminar::getNotGradedActiveParticipations) - ); - } - - private static class SupervisorColumn extends AbstractExportableColumn { - - public SupervisorColumn(IModel displayModel, String sortProperty) { - super(displayModel, sortProperty); - } - - @Override - public IModel getDataModel(IModel model) { - User supervisor = model.getObject().getProject().getHeadSupervisor(); - return Model.of(supervisor.getFullName() + " <" + supervisor.getEmailAddress() + ">"); - } - - @Override - public void populateItem(Item> item, String id, IModel model) { - item.add(new UserLinkPanel(id, model.map(FinalSeminar::getProject).map(Project::getHeadSupervisor))); - } - } - private static class ParticipationColumn extends MultipleUsersColumn { - - private final SerializableFunction> property; - - public ParticipationColumn(IModel header, SerializableFunction> property) { - super(header); - this.property = property; - } - - @Override - public IModel> getUsers(final IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(property)); - } - } - - private final class UnfinishedSeminarProvider extends SortableDataProvider { - - private final IModel seminarAfter; - private final IModel seminarBefore; - - private UnfinishedSeminarProvider(IModel seminarAfter, IModel seminarBefore) { - this.seminarAfter = seminarAfter; - this.seminarBefore = seminarBefore; - } - - @Override - public Iterator iterator(long first, long count) { - return finalSeminarService.findUnfinishedSeminars(seminarAfter.getObject(), seminarBefore.getObject(), new PageAdapter(first, count, getSort())).iterator(); - } - - @Override - public long size() { - return finalSeminarService.countUnfinishedSeminars(seminarAfter.getObject(), seminarBefore.getObject()); - } - - @Override - public IModel model(FinalSeminar object) { - return new DetachableServiceModel<>(finalSeminarService, object); - } - - } -} +package se.su.dsv.scipro.statistics; + +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; +import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.danekja.java.util.function.serializable.SerializableFunction; +import se.su.dsv.scipro.components.DateColumn; +import se.su.dsv.scipro.components.ExportableDataPanel; +import se.su.dsv.scipro.components.ListAdapterModel; +import se.su.dsv.scipro.components.datatables.MultipleUsersColumn; +import se.su.dsv.scipro.data.DetachableServiceModel; +import se.su.dsv.scipro.data.enums.DateStyle; +import se.su.dsv.scipro.dataproviders.PageAdapter; +import se.su.dsv.scipro.date.DatePickerPanel; +import se.su.dsv.scipro.finalseminar.FinalSeminar; +import se.su.dsv.scipro.finalseminar.FinalSeminarService; +import se.su.dsv.scipro.profile.UserLinkPanel; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; + +public class AdminUnfinishedFinalSeminarsPage extends AbstractAdminStatisticsPage { + + private static Date SIX_MONTHS_AGO = Date.from(ZonedDateTime.now().minusMonths(6).toInstant()); + private static Date SEVEN_DAYS_AGO = Date.from(ZonedDateTime.now().minusDays(7).toInstant()); + + @Inject + private FinalSeminarService finalSeminarService; + + public AdminUnfinishedFinalSeminarsPage() { + final IModel seminarAfter = Model.of(SIX_MONTHS_AGO); + final IModel seminarBefore = Model.of(SEVEN_DAYS_AGO); + add( + new Form("form") { + { + add(new DatePickerPanel("seminarDate", seminarAfter, seminarBefore)); + } + } + ); + add(new ExportableDataPanel<>("table", columns(), new UnfinishedSeminarProvider(seminarAfter, seminarBefore))); + } + + private List> columns() { + return asList( + new LambdaColumn<>(Model.of("Title"), "project.title", FinalSeminar::getProjectTitle), + new SupervisorColumn(Model.of("Head supervisor"), "project.headSupervisor.firstName"), + new DateColumn<>(Model.of("Seminar date"), FinalSeminar::getStartDate, "startDate", DateStyle.DATETIME), + new ParticipationColumn(Model.of("Not graded respondents"), FinalSeminar::getNotGradedRespondents), + new ParticipationColumn(Model.of("Not graded opponents"), FinalSeminar::getNotGradedOpponents), + new ParticipationColumn( + Model.of("Not graded active participants"), + FinalSeminar::getNotGradedActiveParticipations + ) + ); + } + + private static class SupervisorColumn extends AbstractExportableColumn { + + public SupervisorColumn(IModel displayModel, String sortProperty) { + super(displayModel, sortProperty); + } + + @Override + public IModel getDataModel(IModel model) { + User supervisor = model.getObject().getProject().getHeadSupervisor(); + return Model.of(supervisor.getFullName() + " <" + supervisor.getEmailAddress() + ">"); + } + + @Override + public void populateItem(Item> item, String id, IModel model) { + item.add(new UserLinkPanel(id, model.map(FinalSeminar::getProject).map(Project::getHeadSupervisor))); + } + } + + private static class ParticipationColumn extends MultipleUsersColumn { + + private final SerializableFunction> property; + + public ParticipationColumn( + IModel header, + SerializableFunction> property + ) { + super(header); + this.property = property; + } + + @Override + public IModel> getUsers(final IModel rowModel) { + return new ListAdapterModel<>(rowModel.map(property)); + } + } + + private final class UnfinishedSeminarProvider extends SortableDataProvider { + + private final IModel seminarAfter; + private final IModel seminarBefore; + + private UnfinishedSeminarProvider(IModel seminarAfter, IModel seminarBefore) { + this.seminarAfter = seminarAfter; + this.seminarBefore = seminarBefore; + } + + @Override + public Iterator iterator(long first, long count) { + return finalSeminarService + .findUnfinishedSeminars( + seminarAfter.getObject(), + seminarBefore.getObject(), + new PageAdapter(first, count, getSort()) + ) + .iterator(); + } + + @Override + public long size() { + return finalSeminarService.countUnfinishedSeminars(seminarAfter.getObject(), seminarBefore.getObject()); + } + + @Override + public IModel model(FinalSeminar object) { + return new DetachableServiceModel<>(finalSeminarService, object); + } + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanel.java index 223958b911..db208b447c 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanel.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.statistics; - +import jakarta.inject.Inject; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -29,21 +31,22 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.Unit; -import jakarta.inject.Inject; -import java.time.ZonedDateTime; -import java.util.*; - public class AdminUnitStatisticsPanel extends Panel { public static final int MONTHS = 12; + @Inject UnitService unitService; + @Inject SupervisorService supervisorService; + @Inject ProjectService projectService; + @Inject IdeaService ideaService; + @Inject ProjectTypeService projectTypeService; @@ -51,8 +54,8 @@ public class AdminUnitStatisticsPanel extends Panel { private final IdeaService.Filter ideaParams = new IdeaService.Filter(); private ExportableDataPanel table; - public AdminUnitStatisticsPanel(String id) { - super(id); + public AdminUnitStatisticsPanel(String id) { + super(id); addProjectTypesFilter(); addDateFilter(); addDataTable(); @@ -108,28 +111,34 @@ public class AdminUnitStatisticsPanel extends Panel { private void addDateFilter() { Date countFrom = Date.from(ZonedDateTime.now().minusMonths(MONTHS).toInstant()); initParams(countFrom); - add(new DatePickerPanel("dateFilter", countFrom) { - @Override - public void updateStartDate(AjaxRequestTarget target) { - projectParams.setCreatedAfter(getStartDate()); - ideaParams.setCreatedAfter(getStartDate()); - target.add(table); - } + add( + new DatePickerPanel("dateFilter", countFrom) { + @Override + public void updateStartDate(AjaxRequestTarget target) { + projectParams.setCreatedAfter(getStartDate()); + ideaParams.setCreatedAfter(getStartDate()); + target.add(table); + } - @Override - public void updateEndDate(AjaxRequestTarget target) { - projectParams.setCreatedBefore(getEndDate()); - ideaParams.setCreatedBefore(getEndDate()); - target.add(table); + @Override + public void updateEndDate(AjaxRequestTarget target) { + projectParams.setCreatedBefore(getEndDate()); + ideaParams.setCreatedBefore(getEndDate()); + target.add(table); + } } - }); + ); } private void addProjectTypesFilter() { - AjaxCheckBoxMultipleChoice projectTypeFilter = new AjaxCheckBoxMultipleChoice<>("projectTypeFilter", - projectTypeService.findByDegreeTypes(Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER)), - projectTypeService.findAllActive(), - new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { + AjaxCheckBoxMultipleChoice projectTypeFilter = new AjaxCheckBoxMultipleChoice<>( + "projectTypeFilter", + projectTypeService.findByDegreeTypes( + Arrays.asList(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ), + projectTypeService.findAllActive(), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { @Override public void onUpdate(AjaxRequestTarget target) { if (!getModelObject().isEmpty()) { @@ -145,7 +154,7 @@ public class AdminUnitStatisticsPanel extends Panel { } private void initParams(Date countFrom) { - projectParams = new ProjectService.Filter(); + projectParams = new ProjectService.Filter(); projectParams.setStatuses(new HashSet<>(Collections.singletonList(ProjectStatus.ACTIVE))); projectParams.setCreatedAfter(countFrom); projectParams.setCreatedBefore(new Date()); diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnmetTargetsStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnmetTargetsStatisticsPage.java index 4a443d7c32..03f6f6d889 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnmetTargetsStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/AdminUnmetTargetsStatisticsPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; @@ -13,8 +17,6 @@ import org.apache.wicket.markup.html.form.StatelessForm; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.*; -import se.su.dsv.scipro.system.PageRequest; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.admin.pages.AdminMailPage; import se.su.dsv.scipro.components.AjaxDropDownChoice; import se.su.dsv.scipro.components.ExportableDataPanel; @@ -23,27 +25,25 @@ import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.dataproviders.PageAdapter; import se.su.dsv.scipro.match.*; import se.su.dsv.scipro.profile.UserLinkPanel; +import se.su.dsv.scipro.system.PageRequest; +import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - public class AdminUnmetTargetsStatisticsPage extends AbstractAdminStatisticsPage { @Inject private MatchFollowUpService matchFollowUpService; + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private UserService userService; private final IModel applicationPeriod; public AdminUnmetTargetsStatisticsPage() { - final FeedbackPanel feedback = new FeedbackPanel("feedback"); feedback.setOutputMarkupId(true); add(feedback); @@ -52,92 +52,132 @@ public class AdminUnmetTargetsStatisticsPage extends AbstractAdminStatisticsPage final IModel> applicationPeriodChoices = new LoadableDetachableModel<>() { @Override protected List load() { - return applicationPeriodService.findAll(new PageRequest(0, Integer.MAX_VALUE, new Sort(Sort.Direction.DESC, "startDate"))); + return applicationPeriodService.findAll( + new PageRequest(0, Integer.MAX_VALUE, new Sort(Sort.Direction.DESC, "startDate")) + ); } }; if (!applicationPeriodChoices.getObject().isEmpty()) { applicationPeriod.setObject(applicationPeriodChoices.getObject().get(0)); } - add(new StatelessForm("filter") { - { - add(new AjaxDropDownChoice<>("applicationPeriod", applicationPeriod, applicationPeriodChoices, new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId)) { - { - setNullValid(false); - setRequired(true); - } + add( + new StatelessForm("filter") { + { + add( + new AjaxDropDownChoice<>( + "applicationPeriod", + applicationPeriod, + applicationPeriodChoices, + new LambdaChoiceRenderer<>(ApplicationPeriod::getName, ApplicationPeriod::getId) + ) { + { + setNullValid(false); + setRequired(true); + } - @Override - public void onNewSelection(final AjaxRequestTarget target, final ApplicationPeriod objectSelected) { - target.add(getPage().get("table"), getPage().get("mailLink")); - } - }); + @Override + public void onNewSelection( + final AjaxRequestTarget target, + final ApplicationPeriod objectSelected + ) { + target.add(getPage().get("table"), getPage().get("mailLink")); + } + } + ); - add(new InfoPanel("info", new ResourceModel("info"))); + add(new InfoPanel("info", new ResourceModel("info"))); + } } - }); + ); UnmetTargetsProvider unmetTargetsProvider = new UnmetTargetsProvider(); unmetTargetsProvider.setSort("user.lastName", SortOrder.ASCENDING); - add(new AjaxLink("mailLink") { - { - setOutputMarkupPlaceholderTag(true); - } + add( + new AjaxLink("mailLink") { + { + setOutputMarkupPlaceholderTag(true); + } - @Override - public void onClick(AjaxRequestTarget target) { - setResponsePage( - new AdminMailPage(matchFollowUpService.findSupervisorsWithUnmetTargets(applicationPeriod.getObject()), - "Add ideas in SciPro", - "You don't have enough ideas to meet your targets for application period " + applicationPeriod.getObject().getName())); - } - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(applicationPeriod.getObject()!=null); - } - }); + @Override + public void onClick(AjaxRequestTarget target) { + setResponsePage( + new AdminMailPage( + matchFollowUpService.findSupervisorsWithUnmetTargets(applicationPeriod.getObject()), + "Add ideas in SciPro", + "You don't have enough ideas to meet your targets for application period " + + applicationPeriod.getObject().getName() + ) + ); + } - add(new ExportableDataPanel<>("table", columns(), unmetTargetsProvider) { - { - setOutputMarkupPlaceholderTag(true); + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(applicationPeriod.getObject() != null); + } } + ); - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(applicationPeriod.getObject() != null); + add( + new ExportableDataPanel<>("table", columns(), unmetTargetsProvider) { + { + setOutputMarkupPlaceholderTag(true); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(applicationPeriod.getObject() != null); + } } - }); + ); } private List> columns() { return Arrays.asList( - new AbstractExportableColumn<>(new StringResourceModel("th.supervisor", this), "user.fullName") { - @Override - public void populateItem(final Item> cellItem, final String componentId, final IModel rowModel) { - cellItem.add(new UserLinkPanel(componentId, new DetachableServiceModel<>(userService, rowModel.getObject().getTarget().getUser()))); - } + new AbstractExportableColumn<>(new StringResourceModel("th.supervisor", this), "user.fullName") { + @Override + public void populateItem( + final Item> cellItem, + final String componentId, + final IModel rowModel + ) { + cellItem.add( + new UserLinkPanel( + componentId, + new DetachableServiceModel<>(userService, rowModel.getObject().getTarget().getUser()) + ) + ); + } - @Override - public IModel getDataModel(final IModel rowModel) { - return rowModel.map(TargetResult::getTarget).map(Target::getUser).map(User::getFullName); - } - }, - new LambdaColumn<>(new StringResourceModel("th.projectType", this), "projectType.name", tr -> tr.getTarget().getProjectType().getName()), - new LambdaColumn<>(new StringResourceModel("th.target", this), "target", tr -> tr.getTarget().getTarget()), - new LambdaColumn<>(new StringResourceModel("th.submittedAndTaken", this), TargetResult::getSubmittedAndTaken), - new LambdaColumn<>(Model.of("Left"), - targetResult -> - String.valueOf(targetResult.getTarget().getTarget() - targetResult.getSubmittedAndTaken())) + @Override + public IModel getDataModel(final IModel rowModel) { + return rowModel.map(TargetResult::getTarget).map(Target::getUser).map(User::getFullName); + } + }, + new LambdaColumn<>(new StringResourceModel("th.projectType", this), "projectType.name", tr -> + tr.getTarget().getProjectType().getName() + ), + new LambdaColumn<>(new StringResourceModel("th.target", this), "target", tr -> tr.getTarget().getTarget()), + new LambdaColumn<>( + new StringResourceModel("th.submittedAndTaken", this), + TargetResult::getSubmittedAndTaken + ), + new LambdaColumn<>(Model.of("Left"), targetResult -> + String.valueOf(targetResult.getTarget().getTarget() - targetResult.getSubmittedAndTaken()) + ) ); } private class UnmetTargetsProvider extends SortableDataProvider { + @Override public Iterator iterator(final long first, final long count) { - return matchFollowUpService.findUnmetTargets(applicationPeriod.getObject(), new PageAdapter(first, count, getSort())).iterator(); + return matchFollowUpService + .findUnmetTargets(applicationPeriod.getObject(), new PageAdapter(first, count, getSort())) + .iterator(); } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanel.java index f52eef9065..86ac308c45 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanel.java @@ -1,36 +1,57 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.ResourceModel; -import se.su.dsv.scipro.components.DateColumn; -import se.su.dsv.scipro.components.EnumLambdaColumn; -import se.su.dsv.scipro.components.TemporalColumn; -import se.su.dsv.scipro.components.datatables.UserColumn; -import se.su.dsv.scipro.milestones.dataobjects.Milestone; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; - -import java.util.ArrayList; -import java.util.List; - -public class IndividualMilestoneDetailsPanel extends AbstractMilestoneDetailsPanel { - - public IndividualMilestoneDetailsPanel(String id, IModel model, MileStoneService.Filter filter) { - super(id, model, filter); - } - - @Override - protected List> createColumns() { - List> columns = new ArrayList<>(); - columns.add(new TemporalColumn<>(new ResourceModel("project.creation.date"), "project.startDate", m -> m.getProject().getStartDate())); - columns.add(new LambdaColumn<>(new ResourceModel("project.title"), "project.title", m -> m.getProject().getTitle())); - columns.add(new LambdaColumn<>(new ResourceModel("project.type"), "project.projectType.name", m -> m.getProject().getProjectTypeName())); - columns.add(new UserColumn<>(new ResourceModel("author"), "user.fullName", Milestone::getUser)); - columns.add(new EnumLambdaColumn<>(new ResourceModel("project.status"), m -> m.getProject().getProjectStatus())); - columns.add(new UserColumn<>(new ResourceModel("project.supervisor"), "project.headSupervisor.fullName", m -> m.getProject().getHeadSupervisor())); - columns.add(new DateColumn<>(new ResourceModel("milestone.completion.date"), Milestone::getLastModified, "lastModified")); - return columns; - } -} +package se.su.dsv.scipro.statistics; + +import java.util.ArrayList; +import java.util.List; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.ResourceModel; +import se.su.dsv.scipro.components.DateColumn; +import se.su.dsv.scipro.components.EnumLambdaColumn; +import se.su.dsv.scipro.components.TemporalColumn; +import se.su.dsv.scipro.components.datatables.UserColumn; +import se.su.dsv.scipro.milestones.dataobjects.Milestone; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; + +public class IndividualMilestoneDetailsPanel extends AbstractMilestoneDetailsPanel { + + public IndividualMilestoneDetailsPanel( + String id, + IModel model, + MileStoneService.Filter filter + ) { + super(id, model, filter); + } + + @Override + protected List> createColumns() { + List> columns = new ArrayList<>(); + columns.add( + new TemporalColumn<>(new ResourceModel("project.creation.date"), "project.startDate", m -> + m.getProject().getStartDate() + ) + ); + columns.add( + new LambdaColumn<>(new ResourceModel("project.title"), "project.title", m -> m.getProject().getTitle()) + ); + columns.add( + new LambdaColumn<>(new ResourceModel("project.type"), "project.projectType.name", m -> + m.getProject().getProjectTypeName() + ) + ); + columns.add(new UserColumn<>(new ResourceModel("author"), "user.fullName", Milestone::getUser)); + columns.add( + new EnumLambdaColumn<>(new ResourceModel("project.status"), m -> m.getProject().getProjectStatus()) + ); + columns.add( + new UserColumn<>(new ResourceModel("project.supervisor"), "project.headSupervisor.fullName", m -> + m.getProject().getHeadSupervisor() + ) + ); + columns.add( + new DateColumn<>(new ResourceModel("milestone.completion.date"), Milestone::getLastModified, "lastModified") + ); + return columns; + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneActivityTemplateChoiceRenderer.java b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneActivityTemplateChoiceRenderer.java index 59ff075cd8..3c4d85673c 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneActivityTemplateChoiceRenderer.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneActivityTemplateChoiceRenderer.java @@ -4,6 +4,7 @@ import org.apache.wicket.markup.html.form.LambdaChoiceRenderer; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; class MilestoneActivityTemplateChoiceRenderer extends LambdaChoiceRenderer { + public MilestoneActivityTemplateChoiceRenderer() { super(MilestoneActivityTemplateChoiceRenderer::getDisplayValue_, MilestoneActivityTemplate::getId); } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanel.java index 31851de7e1..ed9e0fcc6a 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanel.java @@ -1,61 +1,56 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.util.io.IClusterable; -import se.su.dsv.scipro.data.enums.DateStyle; -import se.su.dsv.scipro.date.DateService; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.system.ProjectType; - -import jakarta.inject.Inject; -import java.util.stream.Collectors; - -public class MilestoneFilterDetailsPanel extends Panel { - - @Inject - private DateService dateService; - - private final MileStoneService.Filter filter; - - public MilestoneFilterDetailsPanel(String id, MileStoneService.Filter filter) { - super(id); - this.filter = filter; - add(new Label("filterInfo", - new StringResourceModel("filterInfo", - Model.of(new FilterStringFormatter()))).setEscapeModelStrings(false)); - - } - - protected class FilterStringFormatter implements IClusterable { - - public String projectTypeNames() { - return filter.getProjectTypes() - .stream() - .map(ProjectType::getName) - .collect(Collectors.joining(", ")); - } - - public String projectStatusNames() { - return filter.getProjectStatuses() - .stream() - .map(String::valueOf) - .collect(Collectors.joining(" ,")); - } - - public String startedBetween() { - if (filter.getProjectStartedAfter() == null) { - return getString("notAvailable"); - } - String startedAfter = dateService.format(filter.getProjectStartedAfter(), DateStyle.DATE); - String startedBefore = dateService.format(filter.getProjectStartedBefore(), DateStyle.DATE); - return startedAfter + " and " + startedBefore; - } - - public String completedBefore() { - return dateService.format(filter.getMileStoneCompletedBefore(), DateStyle.DATE); - } - } -} +package se.su.dsv.scipro.statistics; + +import jakarta.inject.Inject; +import java.util.stream.Collectors; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.util.io.IClusterable; +import se.su.dsv.scipro.data.enums.DateStyle; +import se.su.dsv.scipro.date.DateService; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.system.ProjectType; + +public class MilestoneFilterDetailsPanel extends Panel { + + @Inject + private DateService dateService; + + private final MileStoneService.Filter filter; + + public MilestoneFilterDetailsPanel(String id, MileStoneService.Filter filter) { + super(id); + this.filter = filter; + add( + new Label( + "filterInfo", + new StringResourceModel("filterInfo", Model.of(new FilterStringFormatter())) + ).setEscapeModelStrings(false) + ); + } + + protected class FilterStringFormatter implements IClusterable { + + public String projectTypeNames() { + return filter.getProjectTypes().stream().map(ProjectType::getName).collect(Collectors.joining(", ")); + } + + public String projectStatusNames() { + return filter.getProjectStatuses().stream().map(String::valueOf).collect(Collectors.joining(" ,")); + } + + public String startedBetween() { + if (filter.getProjectStartedAfter() == null) { + return getString("notAvailable"); + } + String startedAfter = dateService.format(filter.getProjectStartedAfter(), DateStyle.DATE); + String startedBefore = dateService.format(filter.getProjectStartedBefore(), DateStyle.DATE); + return startedAfter + " and " + startedBefore; + } + + public String completedBefore() { + return dateService.format(filter.getMileStoneCompletedBefore(), DateStyle.DATE); + } + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanel.java index bd744e40f4..575f79d526 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanel.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.io.Serializable; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; @@ -28,11 +32,6 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.io.Serializable; -import java.time.ZonedDateTime; -import java.util.*; - public class MilestoneStatisticsPanel extends Panel { public static final String PROJECT_ACTIVITY_LIST = "projectActivityList"; @@ -52,10 +51,13 @@ public class MilestoneStatisticsPanel extends Panel { @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Inject private MileStoneService mileStoneService; + @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; @@ -84,7 +86,11 @@ public class MilestoneStatisticsPanel extends Panel { } private void prepareDefaultFilter() { - filter.setProjectTypes(projectTypeService.findByDegreeTypes(EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))); + filter.setProjectTypes( + projectTypeService.findByDegreeTypes( + EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ) + ); filter.setProjectStatuses(EnumSet.of(ProjectStatus.ACTIVE)); filter.setMileStoneCompletedBefore(new Date()); filter.setProjectStartedBefore(new Date()); @@ -92,83 +98,108 @@ public class MilestoneStatisticsPanel extends Panel { } private void addProjectTypeFilter() { - add(new AjaxCheckBoxMultipleChoice<>(PROJECT_TYPE_FILTER, + add( + new AjaxCheckBoxMultipleChoice<>( + PROJECT_TYPE_FILTER, LambdaModel.of(filter::getProjectTypes, filter::setProjectTypes), - projectTypeService.findWithModule(ProjectModule.MILESTONES), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(container); + projectTypeService.findWithModule(ProjectModule.MILESTONES), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(container); + } } - }); + ); } private void addProjectDateFilter() { - add(new DeactivatableDatePickerPanel(DATE_FILTER, + add( + new DeactivatableDatePickerPanel( + DATE_FILTER, LambdaModel.of(filter::getProjectStartedAfter, filter::setProjectStartedAfter), LambdaModel.of(filter::getProjectStartedBefore, filter::setProjectStartedBefore), - Model.of(true)) { - @Override - protected void datesChanged(AjaxRequestTarget target) { - target.add(container); + Model.of(true) + ) { + @Override + protected void datesChanged(AjaxRequestTarget target) { + target.add(container); + } } - }); + ); } private void addProjectStatusFilter() { - add(new AjaxCheckBoxMultipleChoice<>(PROJECT_STATUSES, + add( + new AjaxCheckBoxMultipleChoice<>( + PROJECT_STATUSES, LambdaModel.of(filter::getProjectStatuses, filter::setProjectStatuses), - Arrays.asList(ProjectStatus.values()), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(container); + Arrays.asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(container); + } } - }); + ); } private void addMileStoneDateFilter() { - BootstrapDateField mileStoneCompletedBefore = new BootstrapDateField(MILESTONE_DATE_FILTER, LambdaModel.of(filter::getMileStoneCompletedBefore, filter::setMileStoneCompletedBefore)); - mileStoneCompletedBefore.add(new OnChangeAjaxBehavior() { - @Override - protected void onUpdate(final AjaxRequestTarget target) { - target.add(container); + BootstrapDateField mileStoneCompletedBefore = new BootstrapDateField( + MILESTONE_DATE_FILTER, + LambdaModel.of(filter::getMileStoneCompletedBefore, filter::setMileStoneCompletedBefore) + ); + mileStoneCompletedBefore.add( + new OnChangeAjaxBehavior() { + @Override + protected void onUpdate(final AjaxRequestTarget target) { + target.add(container); + } } - }); + ); add(mileStoneCompletedBefore); } private void addProjectMileStoneList() { container.add(new Label(TOTAL_PROJECTS, countTotalProjects())); - container.add(new ListView<>(PROJECT_ACTIVITY_LIST, getActivities(MilestoneActivityTemplate.Type.PROJECT)) { - @Override - protected void populateItem(ListItem item) { - Link link = new Link<>(DETAILS_LINK, item.getModel()) { - @Override - public void onClick() { - setResponsePage(pageSupplier.projectPage(getModel(), filter)); - } - }; - link.add(new Label(PROJECT_ACTIVITY_NAME, item.getModel().map(MilestoneActivityTemplate::getTitle))); - item.add(link); - item.add(new Label(COMPLETED_PROJECTS, countCompleted(item.getModel()))); + container.add( + new ListView<>(PROJECT_ACTIVITY_LIST, getActivities(MilestoneActivityTemplate.Type.PROJECT)) { + @Override + protected void populateItem(ListItem item) { + Link link = new Link<>(DETAILS_LINK, item.getModel()) { + @Override + public void onClick() { + setResponsePage(pageSupplier.projectPage(getModel(), filter)); + } + }; + link.add( + new Label(PROJECT_ACTIVITY_NAME, item.getModel().map(MilestoneActivityTemplate::getTitle)) + ); + item.add(link); + item.add(new Label(COMPLETED_PROJECTS, countCompleted(item.getModel()))); + } } - }); + ); } private void addIndividualMileStoneList() { - container.add(new ListView<>(INDIVIDUAL_ACTIVITY_LIST, getActivities(MilestoneActivityTemplate.Type.STUDENT)) { - @Override - protected void populateItem(ListItem item) { - Link link = new Link<>(INDIVIDUAL_ACTIVITY_NAME, item.getModel()) { - @Override - public void onClick() { - setResponsePage(pageSupplier.individualPage(getModel(), filter)); - } - }; - item.add(link); - link.setBody(item.getModel().map(MilestoneActivityTemplate::getTitle)); - item.add(new Label(COMPLETED_AUTHORS, countCompleted(item.getModel()))); + container.add( + new ListView<>(INDIVIDUAL_ACTIVITY_LIST, getActivities(MilestoneActivityTemplate.Type.STUDENT)) { + @Override + protected void populateItem(ListItem item) { + Link link = new Link<>(INDIVIDUAL_ACTIVITY_NAME, item.getModel()) { + @Override + public void onClick() { + setResponsePage(pageSupplier.individualPage(getModel(), filter)); + } + }; + item.add(link); + link.setBody(item.getModel().map(MilestoneActivityTemplate::getTitle)); + item.add(new Label(COMPLETED_AUTHORS, countCompleted(item.getModel()))); + } } - }); + ); } private IModel countCompleted(final IModel activityModel) { diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanel.java index 0fe0e4a954..c0254656a5 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; @@ -24,14 +26,14 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class MilestoneStatisticsProgressPanel extends Panel { + @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Inject private MilestoneStatisticsService milestoneStatisticsService; + @Inject private ProjectService projectService; @@ -40,14 +42,29 @@ public class MilestoneStatisticsProgressPanel extends Panel { public MilestoneStatisticsProgressPanel(final String id) { super(id); - - add(new Form("selection") { - { - IModel> templates = getTemplates(); - add(new DropDownChoice<>("completed", completed, templates, new MilestoneActivityTemplateChoiceRenderer()).setRequired(true)); - add(new DropDownChoice<>("notCompleted", notCompleted, templates, new MilestoneActivityTemplateChoiceRenderer()).setRequired(true)); + add( + new Form("selection") { + { + IModel> templates = getTemplates(); + add( + new DropDownChoice<>( + "completed", + completed, + templates, + new MilestoneActivityTemplateChoiceRenderer() + ).setRequired(true) + ); + add( + new DropDownChoice<>( + "notCompleted", + notCompleted, + templates, + new MilestoneActivityTemplateChoiceRenderer() + ).setRequired(true) + ); + } } - }); + ); add(new ExportableDataPanel<>("projects", columns(), new ProgressedProjectsProvider())); } @@ -57,12 +74,14 @@ public class MilestoneStatisticsProgressPanel extends Panel { columns.add(new TemporalColumn<>(Model.of("Project started"), "startDate", Project::getStartDate)); columns.add(new LambdaColumn<>(Model.of("Title"), "title", Project::getTitle)); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", Project::getProjectTypeName)); - columns.add(new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - protected IModel> getUsers(IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + columns.add( + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + protected IModel> getUsers(IModel rowModel) { + return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + } } - }); + ); columns.add(new EnumLambdaColumn<>(Model.of("Status"), Project::getProjectStatus)); columns.add(new UserColumn<>(Model.of("Supervisor"), "headSupervisor.fullName", Project::getHeadSupervisor)); return columns; @@ -80,14 +99,23 @@ public class MilestoneStatisticsProgressPanel extends Panel { } private class ProgressedProjectsProvider extends SortableDataProvider { + @Override public Iterator iterator(final long first, final long count) { - return milestoneStatisticsService.getProgressedProjects(completed.getObject(), notCompleted.getObject(), new PageAdapter(first, count, getSort())).iterator(); + return milestoneStatisticsService + .getProgressedProjects( + completed.getObject(), + notCompleted.getObject(), + new PageAdapter(first, count, getSort()) + ) + .iterator(); } @Override public long size() { - if (completed.getObject() == null || notCompleted.getObject() == null) { return 0; } + if (completed.getObject() == null || notCompleted.getObject() == null) { + return 0; + } return milestoneStatisticsService.countProgressedProjects(completed.getObject(), notCompleted.getObject()); } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/ProjectExternalStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/ProjectExternalStatisticsPage.java index e119475632..ebf960031f 100755 --- a/view/src/main/java/se/su/dsv/scipro/statistics/ProjectExternalStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/ProjectExternalStatisticsPage.java @@ -4,7 +4,7 @@ import se.su.dsv.scipro.datatables.project.ProjectExternalOrganisationPanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -@Authorization(authorizedRoles = {Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class ProjectExternalStatisticsPage extends AbstractAdminStatisticsPage { public ProjectExternalStatisticsPage() { @@ -12,5 +12,4 @@ public class ProjectExternalStatisticsPage extends AbstractAdminStatisticsPage { } static final String PANEL = "panel"; - } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanel.java index 3f407870b0..0e93bd5bde 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanel.java @@ -1,44 +1,60 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import se.su.dsv.scipro.components.DateColumn; -import se.su.dsv.scipro.components.EnumLambdaColumn; -import se.su.dsv.scipro.components.ListAdapterModel; -import se.su.dsv.scipro.components.TemporalColumn; -import se.su.dsv.scipro.components.datatables.MultipleUsersColumn; -import se.su.dsv.scipro.components.datatables.UserColumn; -import se.su.dsv.scipro.milestones.dataobjects.Milestone; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; - -import java.util.ArrayList; -import java.util.List; - -public class ProjectMilestoneDetailsPanel extends AbstractMilestoneDetailsPanel { - public ProjectMilestoneDetailsPanel(String id, IModel model, MileStoneService.Filter filter) { - super(id, model, filter); - } - - @Override - protected List> createColumns() { - List> columns = new ArrayList<>(); - columns.add(new TemporalColumn<>(Model.of("Project started"), "project.startDate", m -> m.getProject().getStartDate())); - columns.add(new LambdaColumn<>(Model.of("Title"), "project.title", m -> m.getProject().getTitle())); - columns.add(new LambdaColumn<>(Model.of("Type"), "project.projectType.name", m -> m.getProject().getProjectTypeName())); - columns.add(new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - protected IModel> getUsers(IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Milestone::getProject).map(Project::getProjectParticipants)); - } - }); - columns.add(new EnumLambdaColumn<>(Model.of("Status"), m -> m.getProject().getProjectStatus())); - columns.add(new UserColumn<>(Model.of("Supervisor"), "project.headSupervisor.fullName", m -> m.getProject().getHeadSupervisor())); - columns.add(new DateColumn<>(Model.of("Milestone completed"), Milestone::getLastModified, "lastModified")); - return columns; - } -} +package se.su.dsv.scipro.statistics; + +import java.util.ArrayList; +import java.util.List; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.LambdaColumn; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import se.su.dsv.scipro.components.DateColumn; +import se.su.dsv.scipro.components.EnumLambdaColumn; +import se.su.dsv.scipro.components.ListAdapterModel; +import se.su.dsv.scipro.components.TemporalColumn; +import se.su.dsv.scipro.components.datatables.MultipleUsersColumn; +import se.su.dsv.scipro.components.datatables.UserColumn; +import se.su.dsv.scipro.milestones.dataobjects.Milestone; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; + +public class ProjectMilestoneDetailsPanel extends AbstractMilestoneDetailsPanel { + + public ProjectMilestoneDetailsPanel( + String id, + IModel model, + MileStoneService.Filter filter + ) { + super(id, model, filter); + } + + @Override + protected List> createColumns() { + List> columns = new ArrayList<>(); + columns.add( + new TemporalColumn<>(Model.of("Project started"), "project.startDate", m -> m.getProject().getStartDate()) + ); + columns.add(new LambdaColumn<>(Model.of("Title"), "project.title", m -> m.getProject().getTitle())); + columns.add( + new LambdaColumn<>(Model.of("Type"), "project.projectType.name", m -> m.getProject().getProjectTypeName()) + ); + columns.add( + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + protected IModel> getUsers(IModel rowModel) { + return new ListAdapterModel<>( + rowModel.map(Milestone::getProject).map(Project::getProjectParticipants) + ); + } + } + ); + columns.add(new EnumLambdaColumn<>(Model.of("Status"), m -> m.getProject().getProjectStatus())); + columns.add( + new UserColumn<>(Model.of("Supervisor"), "project.headSupervisor.fullName", m -> + m.getProject().getHeadSupervisor() + ) + ); + columns.add(new DateColumn<>(Model.of("Milestone completed"), Milestone::getLastModified, "lastModified")); + return columns; + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorApplicationPeriodStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorApplicationPeriodStatisticsPanel.java index a4000f6aa5..e393dc55e3 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorApplicationPeriodStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorApplicationPeriodStatisticsPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.List; +import java.util.Objects; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; @@ -13,37 +16,54 @@ import se.su.dsv.scipro.match.TargetService; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.List; -import java.util.Objects; - public class SupervisorApplicationPeriodStatisticsPanel extends GenericPanel { + @Inject private ApplicationPeriodService applicationPeriodService; + @Inject private TargetService targetService; public SupervisorApplicationPeriodStatisticsPanel(String id, IModel supervisorModel) { super(id, supervisorModel); - LoadableDetachableModel> targets = LoadableDetachableModel.of(() -> - upcomingPeriods().stream() - .flatMap(period -> period.getProjectTypes().stream() + upcomingPeriods() + .stream() + .flatMap(period -> + period + .getProjectTypes() + .stream() .map(projectType -> { final Target target = targetService.findOne(period, getModelObject(), projectType); return new PeriodTypeTarget(period, projectType, target); - })) + }) + ) .filter(ptt -> ptt.getTarget().getTarget() > 0) - .toList()); + .toList() + ); - add(new ListView<>("targets", targets){ - @Override - public void populateItem(ListItem item) { - item.add(new Label("period", item.getModel().map(PeriodTypeTarget::getApplicationPeriod).map(ApplicationPeriod::getName))); - item.add(new Label("projectType", item.getModel().map(PeriodTypeTarget::getProjectType).map(ProjectType::getName))); - item.add(new Label("target", item.getModel().map(PeriodTypeTarget::getTarget).map(Target::getTarget))); + add( + new ListView<>("targets", targets) { + @Override + public void populateItem(ListItem item) { + item.add( + new Label( + "period", + item.getModel().map(PeriodTypeTarget::getApplicationPeriod).map(ApplicationPeriod::getName) + ) + ); + item.add( + new Label( + "projectType", + item.getModel().map(PeriodTypeTarget::getProjectType).map(ProjectType::getName) + ) + ); + item.add( + new Label("target", item.getModel().map(PeriodTypeTarget::getTarget).map(Target::getTarget)) + ); + } } - }); + ); } private List upcomingPeriods() { @@ -51,6 +71,7 @@ public class SupervisorApplicationPeriodStatisticsPanel extends GenericPanel> columns = Arrays.asList( - new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName()), - new EnumLambdaColumn<>(Model.of("Idea"), "type", Idea::getType), - new LambdaColumn<>(Model.of("Title"), "title", Idea::getTitle), - new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - protected IModel> getUsers(IModel rowModel) { - return rowModel.map(idea -> idea.getIdeaParticipations() - .stream() - .map(IdeaParticipation::getUser) - .toList()); - } + new LambdaColumn<>(Model.of("Type"), "projectType.name", idea -> idea.getProjectType().getName()), + new EnumLambdaColumn<>(Model.of("Idea"), "type", Idea::getType), + new LambdaColumn<>(Model.of("Title"), "title", Idea::getTitle), + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + protected IModel> getUsers(IModel rowModel) { + return rowModel.map(idea -> + idea.getIdeaParticipations().stream().map(IdeaParticipation::getUser).toList() + ); } + } + ); + FilteredDataProvider provider = new FilteredDataProvider<>( + ideaService, + Model.of(param) ); - FilteredDataProvider provider = new FilteredDataProvider<>(ideaService, Model.of(param)); provider.setSort("title", SortOrder.ASCENDING); add(new ExportableDataPanel<>(IDEAS, columns, provider)); } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanel.java index 7c2b43500f..92856f256a 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; +import java.util.*; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; @@ -21,13 +23,11 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.ProjectTeamMemberRoles; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.*; - public class SupervisorProjectStatisticsPanel extends Panel { @Inject private ProjectService projectService; + private ProjectService.Filter filter; public SupervisorProjectStatisticsPanel(String id) { @@ -52,22 +52,26 @@ public class SupervisorProjectStatisticsPanel extends Panel { } private List> createColumns() { - List> columns = new ArrayList<>(); + List> columns = new ArrayList<>(); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", Project::getProjectTypeName)); columns.add(new LambdaColumn<>(Model.of("Title"), "title", Project::getTitle)); - columns.add(new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - protected IModel> getUsers(IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + columns.add( + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + protected IModel> getUsers(IModel rowModel) { + return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + } } - }); - columns.add(new AbstractColumn<>(Model.of("Role")) { - @Override - public void populateItem(Item> item, String id, IModel model) { - Project p = model.getObject(); - item.add(new Label(id, getRoleString(p))); + ); + columns.add( + new AbstractColumn<>(Model.of("Role")) { + @Override + public void populateItem(Item> item, String id, IModel model) { + Project p = model.getObject(); + item.add(new Label(id, getRoleString(p))); + } } - }); + ); return columns; } diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPage.java index fa8244c1cf..22896d3ae1 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPage.java @@ -1,11 +1,12 @@ package se.su.dsv.scipro.statistics; -import se.su.dsv.scipro.security.auth.Authorization; - import static se.su.dsv.scipro.security.auth.roles.Roles.ADMIN; -@Authorization(authorizedRoles = {ADMIN}) +import se.su.dsv.scipro.security.auth.Authorization; + +@Authorization(authorizedRoles = { ADMIN }) public class SupervisorStatisticsPage extends AbstractAdminStatisticsPage { + static final String PANEL = "panel"; public SupervisorStatisticsPage() { diff --git a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanel.java b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanel.java index e792588e31..25c662aaa9 100644 --- a/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.statistics; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; @@ -8,54 +9,55 @@ import se.su.dsv.scipro.data.DetachableServiceModel; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; - public class SupervisorStatisticsPanel extends Panel { - @Inject - private UserService userService; + @Inject + private UserService userService; - private final SupervisorApplicationPeriodStatisticsPanel periodStatisticsPanel; - private SupervisorProjectStatisticsPanel projectPanel; - private SupervisorIdeaStatisticsPanel ideaPanel; + private final SupervisorApplicationPeriodStatisticsPanel periodStatisticsPanel; + private SupervisorProjectStatisticsPanel projectPanel; + private SupervisorIdeaStatisticsPanel ideaPanel; - public SupervisorStatisticsPanel(String id) { - super(id); - addEmployeeSelection(); + public SupervisorStatisticsPanel(String id) { + super(id); + addEmployeeSelection(); projectPanel = new SupervisorProjectStatisticsPanel(PROJECTS_PANEL); - projectPanel.setOutputMarkupPlaceholderTag(true); - add(projectPanel); + projectPanel.setOutputMarkupPlaceholderTag(true); + add(projectPanel); ideaPanel = new SupervisorIdeaStatisticsPanel(IDEAS_PANEL); - ideaPanel.setOutputMarkupPlaceholderTag(true); - add(ideaPanel); - periodStatisticsPanel = new SupervisorApplicationPeriodStatisticsPanel("periods", new DetachableServiceModel<>(userService)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject() != null); - } - }; - periodStatisticsPanel.setOutputMarkupPlaceholderTag(true); - add(periodStatisticsPanel); - } + ideaPanel.setOutputMarkupPlaceholderTag(true); + add(ideaPanel); + periodStatisticsPanel = new SupervisorApplicationPeriodStatisticsPanel( + "periods", + new DetachableServiceModel<>(userService) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject() != null); + } + }; + periodStatisticsPanel.setOutputMarkupPlaceholderTag(true); + add(periodStatisticsPanel); + } - private void addEmployeeSelection() { - add(new EmployeeAutoComplete(SUPERVISOR_SELECTION, new DetachableServiceModel<>(userService)) { - + private void addEmployeeSelection() { + add( + new EmployeeAutoComplete(SUPERVISOR_SELECTION, new DetachableServiceModel<>(userService)) { + @Override + protected void action(AjaxRequestTarget pTarget, User newSelection) { + projectPanel.updateSupervisor(newSelection); + ideaPanel.updateSupervisor(newSelection); + periodStatisticsPanel.setModelObject(getModelObject()); + pTarget.add(projectPanel); + pTarget.add(ideaPanel); + pTarget.add(periodStatisticsPanel); + } + } + ); + } - @Override - protected void action(AjaxRequestTarget pTarget, User newSelection) { - projectPanel.updateSupervisor(newSelection); - ideaPanel.updateSupervisor(newSelection); - periodStatisticsPanel.setModelObject(getModelObject()); - pTarget.add(projectPanel); - pTarget.add(ideaPanel); - pTarget.add(periodStatisticsPanel); - } - }); - } - - static final String SUPERVISOR_SELECTION = "employeeSelection"; - static final String PROJECTS_PANEL = "projectPanel"; - static final String IDEAS_PANEL = "ideaPanel"; + static final String SUPERVISOR_SELECTION = "employeeSelection"; + static final String PROJECTS_PANEL = "projectPanel"; + static final String IDEAS_PANEL = "ideaPanel"; } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorAllProjectsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorAllProjectsPage.java index 5fdd11f498..7ce72b9779 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorAllProjectsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorAllProjectsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.activityplan.SupervisorActivityPlanTemplatesPage; @@ -13,10 +16,6 @@ import se.su.dsv.scipro.peer.SupervisorPeersPage; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public abstract class AbstractSupervisorAllProjectsPage extends AbstractSupervisorPage { @Inject @@ -39,35 +38,50 @@ public abstract class AbstractSupervisorAllProjectsPage extends AbstractSupervis } private void addSubMenu() { - add(new AbstractMenuPanel("menuPanel", AbstractSupervisorAllProjectsPage.class, this.getClass()) { + add( + new AbstractMenuPanel("menuPanel", AbstractSupervisorAllProjectsPage.class, this.getClass()) { + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + @Override + protected List getItemList() { + final List items = new ArrayList<>(); + items.add(new MenuItem("Start", SupervisorAllProjectsPage.class)); + if (moduleIsEnabled(ProjectModule.FINAL_SEMINAR)) { + items.add(new MenuItem("Final seminars", SupervisorFinalSeminarListingPage.class)); + } + if (moduleIsEnabled(ProjectModule.GRADING)) { + items.add(new MenuItem("Final theses", SupervisorFinalThesisListingPage.class)); + } + if (moduleIsEnabled(ProjectModule.PEER)) { + items.add( + new MenuItem("Peers", SupervisorPeersPage.class, MenuHighlightSupervisorAllPeers.class) + ); + } + if (moduleIsEnabled(ProjectModule.ACTIVITY_PLAN)) { + items.add( + new MenuItem( + "Activity plan templates", + SupervisorActivityPlanTemplatesPage.class, + MenuHighlightSupervisorActivityTemplates.class + ) + ); + } + if (moduleIsEnabled(ProjectModule.MILESTONES)) { + items.add( + new MenuItem( + "Milestone statistics", + SupervisorMilestoneStatisticsPage.class, + MenuHighlightSupervisorMilestoneStatistics.class + ) + ); + } + return items; + } } - - @Override - protected List getItemList() { - final List items = new ArrayList<>(); - items.add(new MenuItem("Start", SupervisorAllProjectsPage.class)); - if (moduleIsEnabled(ProjectModule.FINAL_SEMINAR)) { - items.add(new MenuItem("Final seminars", SupervisorFinalSeminarListingPage.class)); - } - if (moduleIsEnabled(ProjectModule.GRADING)) { - items.add(new MenuItem("Final theses", SupervisorFinalThesisListingPage.class)); - } - if (moduleIsEnabled(ProjectModule.PEER)) { - items.add(new MenuItem("Peers", SupervisorPeersPage.class, MenuHighlightSupervisorAllPeers.class)); - } - if (moduleIsEnabled(ProjectModule.ACTIVITY_PLAN)) { - items.add(new MenuItem("Activity plan templates", SupervisorActivityPlanTemplatesPage.class, MenuHighlightSupervisorActivityTemplates.class)); - } - if (moduleIsEnabled(ProjectModule.MILESTONES)) { - items.add(new MenuItem("Milestone statistics", SupervisorMilestoneStatisticsPage.class, MenuHighlightSupervisorMilestoneStatistics.class)); - } - return items; - } - }); + ); } private boolean moduleIsEnabled(ProjectModule module) { diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorGroupPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorGroupPage.java index c93e9a146a..6247f3295a 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorGroupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorGroupPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import jakarta.servlet.http.Cookie; import org.apache.wicket.RestartResponseException; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; @@ -21,11 +23,10 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import jakarta.servlet.http.Cookie; - @SystemModuleComponent(SystemModule.GROUP) -public abstract class AbstractSupervisorGroupPage extends AbstractSupervisorPage implements MenuHighlightSupervisorMyGroups { +public abstract class AbstractSupervisorGroupPage + extends AbstractSupervisorPage + implements MenuHighlightSupervisorMyGroups { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSupervisorGroupPage.class); public static final String COOKIE_KEY = "supervisorLastVisitedGID"; @@ -33,6 +34,7 @@ public abstract class AbstractSupervisorGroupPage extends AbstractSupervisorPage @Inject protected GroupService groupService; + @Inject protected GroupFacade groupFacade; @@ -40,20 +42,19 @@ public abstract class AbstractSupervisorGroupPage extends AbstractSupervisorPage public AbstractSupervisorGroupPage(PageParameters pp) { super(pp); - Long groupId = null; StringValue groupValue = pp.get(PageParameterKeys.MAP.get(Group.class)); if (!groupValue.isNull()) { try { groupId = groupValue.toLongObject(); - } catch (StringValueConversionException e){ + } catch (StringValueConversionException e) { throw new RestartResponseException(NotFoundPage.class); } /* * Cookie is set when the link to visit this details page is clicked but for it to work - * if a URL is entered directly we set it here too - */ + * if a URL is entered directly we set it here too + */ Cookie c = new Cookie(COOKIE_KEY, groupId.toString()); c.setMaxAge(MAX_AGE); c.setPath("/"); diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorPage.java index 47ae5ea786..5a5e424670 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.basepages.MenuPage; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettingsService; @@ -9,9 +10,7 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.supervisor.panels.SupervisorTabMenuPanel; -import jakarta.inject.Inject; - -@Authorization(authorizedRoles = {Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) public abstract class AbstractSupervisorPage extends MenuPage { @Inject @@ -27,7 +26,8 @@ public abstract class AbstractSupervisorPage extends MenuPage { public AbstractSupervisorPage(PageParameters pp) { super(pp); userProfileService.setSelectedRole(SciProSession.get().getUser(), Roles.SUPERVISOR); - SciProSession.get().setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); + SciProSession.get() + .setSystemModules(generalSystemSettingsService.getGeneralSystemSettingsInstance().getSystemModules()); add(new SupervisorTabMenuPanel("tabMenu", this.getClass())); } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorProjectDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorProjectDetailsPage.java index d435a71a71..6e5c051ff8 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorProjectDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/AbstractSupervisorProjectDetailsPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import jakarta.servlet.http.Cookie; import org.apache.wicket.RestartResponseException; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; @@ -18,9 +20,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import jakarta.servlet.http.Cookie; - public abstract class AbstractSupervisorProjectDetailsPage extends AbstractSupervisorPage { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSupervisorProjectDetailsPage.class); @@ -34,21 +33,20 @@ public abstract class AbstractSupervisorProjectDetailsPage extends AbstractSuper public AbstractSupervisorProjectDetailsPage(PageParameters pp) { super(pp); - Long projectId = null; StringValue projectValue = pp.get(PageParameterKeys.MAP.get(Project.class)); if (!projectValue.isNull()) { try { projectId = projectValue.toLongObject(); - } catch (StringValueConversionException e){ + } catch (StringValueConversionException e) { LOGGER.warn("Project ID is not valid.", e); throw new RestartResponseException(NotFoundPage.class); } /* * Cookie is set when the link to visit this details page is clicked but for it to work - * if a URL is entered directly we set it here too - */ + * if a URL is entered directly we set it here too + */ Cookie c = new Cookie(COOKIE_KEY, projectId.toString()); c.setMaxAge(MAX_AGE); c.setPath("/"); @@ -82,12 +80,14 @@ public abstract class AbstractSupervisorProjectDetailsPage extends AbstractSuper projectModel = new DetachableServiceModel<>(projectService, projectId); setDefaultModel(projectModel); - add(new SupervisorSubTabMenuPanel("supervisorSub", this.getClass(), getPageParameters(project), projectModel) { - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + add( + new SupervisorSubTabMenuPanel("supervisorSub", this.getClass(), getPageParameters(project), projectModel) { + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } } - }); + ); add(new ProjectHeaderPanel("projectHeader", projectModel)); } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorAllProjectsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorAllProjectsPage.java index 72e88883e0..11dbda267c 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorAllProjectsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorAllProjectsPage.java @@ -1,4 +1,3 @@ -package se.su.dsv.scipro.supervisor.pages; - -public class SupervisorAllProjectsPage extends AbstractSupervisorAllProjectsPage { -} +package se.su.dsv.scipro.supervisor.pages; + +public class SupervisorAllProjectsPage extends AbstractSupervisorAllProjectsPage {} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPage.java index 168169319b..556377c818 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -14,8 +15,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - @SystemModuleComponent(SystemModule.GROUP) public class SupervisorEditGroupPage extends AbstractSupervisorPage implements MenuHighlightSupervisorMyGroups { @@ -23,10 +22,9 @@ public class SupervisorEditGroupPage extends AbstractSupervisorPage implements M private GroupService groupService; public SupervisorEditGroupPage(PageParameters pp) { - final IModel model = new DetachableServiceModel<>(groupService); - if (pp.get(PageParameterKeys.MAP.get(Group.class)).isNull()){ + if (pp.get(PageParameterKeys.MAP.get(Group.class)).isNull()) { Group group = new Group(); group.setUser(SciProSession.get().getUser()); model.setObject(group); @@ -37,6 +35,5 @@ public class SupervisorEditGroupPage extends AbstractSupervisorPage implements M } add(new EditGroupPanel("createGroupPanel", model)); - } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePage.java index 4b0a755beb..417c08a6a8 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePage.java @@ -15,15 +15,16 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.util.PageParameterKeys; -@Authorization(authorizedRoles={Roles.SUPERVISOR}) +@Authorization(authorizedRoles = { Roles.SUPERVISOR }) @ProjectModuleComponent(ProjectModule.FILES) -public class SupervisorFilePage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { +public class SupervisorFilePage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { private static final Logger LOGGER = LoggerFactory.getLogger(SupervisorFilePage.class); - public SupervisorFilePage(PageParameters pp) { - super(pp); - + public SupervisorFilePage(PageParameters pp) { + super(pp); Long projectId = pp.get(PageParameterKeys.MAP.get(Project.class)).toLong(); Project project = projectService.findOne(projectId); @@ -31,7 +32,7 @@ public class SupervisorFilePage extends AbstractSupervisorProjectDetailsPage imp failAndRedirect(); } add(new ProjectFilePanel("filePanel", new DetachableServiceModel<>(projectService, project))); - } + } private void failAndRedirect() { LOGGER.warn("User not part of project tried to access the file panel"); diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFirstMeetingPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFirstMeetingPage.java index e811ce058b..5e57849514 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFirstMeetingPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorFirstMeetingPage.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import java.util.Date; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.TextArea; @@ -16,14 +18,14 @@ import se.su.dsv.scipro.notifications.NotificationController; import se.su.dsv.scipro.notifications.dataobject.NotificationSource; import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import jakarta.inject.Inject; -import java.util.Date; - public class SupervisorFirstMeetingPage extends AbstractSupervisorProjectDetailsPage { + @Inject private FirstMeetingService firstMeetingService; + @Inject private NotificationController notificationController; + @Inject private DateService dateService; @@ -33,34 +35,41 @@ public class SupervisorFirstMeetingPage extends AbstractSupervisorProjectDetails public SupervisorFirstMeetingPage(final PageParameters pp) { super(pp); - - firstMeetingService.findByProject(projectModel.getObject()).ifPresent(firstMeeting -> { - date.setObject(firstMeeting.getDate()); - room.setObject(firstMeeting.getRoom()); - description.setObject(firstMeeting.getDescription()); - }); + firstMeetingService + .findByProject(projectModel.getObject()) + .ifPresent(firstMeeting -> { + date.setObject(firstMeeting.getDate()); + room.setObject(firstMeeting.getRoom()); + description.setObject(firstMeeting.getDescription()); + }); add(new FeedbackPanel("feedback")); - add(new Form<>("form", projectModel) { - { - add(new BootstrapDateTimeComponent("date", date).setRequired(true)); - add(new RequiredTextField<>("room", room)); - add(new TextArea<>("description", description)); - } + add( + new Form<>("form", projectModel) { + { + add(new BootstrapDateTimeComponent("date", date).setRequired(true)); + add(new RequiredTextField<>("room", room)); + add(new TextArea<>("description", description)); + } - @Override - protected void onSubmit() { - success("First meeting scheduled"); - final ProjectFirstMeeting firstMeeting = firstMeetingService.schedule(projectModel.getObject(), date.getObject(), room.getObject(), description.getObject()); - NotificationSource source = new NotificationSource(); - String date = dateService.format(firstMeeting.getDate(), DateStyle.DATETIME); - String room = firstMeeting.getRoom(); - source.setMessage(date + "\nRoom: " + room); - source.setAdditionalMessage(firstMeeting.getDescription()); - notificationController.notifyProject(getModelObject(), - ProjectEvent.Event.FIRST_MEETING, source); + @Override + protected void onSubmit() { + success("First meeting scheduled"); + final ProjectFirstMeeting firstMeeting = firstMeetingService.schedule( + projectModel.getObject(), + date.getObject(), + room.getObject(), + description.getObject() + ); + NotificationSource source = new NotificationSource(); + String date = dateService.format(firstMeeting.getDate(), DateStyle.DATETIME); + String room = firstMeeting.getRoom(); + source.setMessage(date + "\nRoom: " + room); + source.setAdditionalMessage(firstMeeting.getDescription()); + notificationController.notifyProject(getModelObject(), ProjectEvent.Event.FIRST_MEETING, source); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPage.java index bc014061f9..70da4fce6d 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyGroups; @@ -11,25 +12,28 @@ import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.group.GroupForum; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - - -public class SupervisorGroupCreateThreadPage extends AbstractSupervisorGroupPage implements MenuHighlightSupervisorMyGroups { +public class SupervisorGroupCreateThreadPage + extends AbstractSupervisorGroupPage + implements MenuHighlightSupervisorMyGroups { @Inject private GroupForumService groupForumService; public SupervisorGroupCreateThreadPage(PageParameters pp) { super(pp); - add(new BookmarkablePageLink("back", SupervisorGroupPage.class, getPageParameters(groupModel.getObject()))); - add(new SubmitForumThreadPanel<>("createThread", new GroupForum(groupForumService, groupModel)) { - @Override - public void onThreadCreated(final GroupThread thread) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Group.class), groupModel.getObject().getId()); - pp.add(PageParameterKeys.MAP.get(ForumThread.class), thread.getId()); - setResponsePage(SupervisorViewGroupThreadPage.class, pp); + add( + new BookmarkablePageLink("back", SupervisorGroupPage.class, getPageParameters(groupModel.getObject())) + ); + add( + new SubmitForumThreadPanel<>("createThread", new GroupForum(groupForumService, groupModel)) { + @Override + public void onThreadCreated(final GroupThread thread) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Group.class), groupModel.getObject().getId()); + pp.add(PageParameterKeys.MAP.get(ForumThread.class), thread.getId()); + setResponsePage(SupervisorViewGroupThreadPage.class, pp); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPage.java index 1271727152..4307836a19 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.IModel; @@ -13,12 +17,6 @@ import se.su.dsv.scipro.forum.panels.threaded.ThreadsOverviewPanel; import se.su.dsv.scipro.group.GroupThreadDiscussable; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - - public class SupervisorGroupPage extends AbstractSupervisorGroupPage implements MenuHighlightSupervisorMyGroups { @Inject @@ -28,12 +26,15 @@ public class SupervisorGroupPage extends AbstractSupervisorGroupPage implements super(pp); add(new FeedbackPanel("feedback")); add(new BookmarkablePageLink("createThread", SupervisorGroupCreateThreadPage.class, pp)); - add(new ThreadsOverviewPanel<>("threads", getThreads(), new GroupThreadDiscussable(), - (id, thread) -> { - PageParameters parameters = new PageParameters(pp) - .set(PageParameterKeys.MAP.get(ForumThread.class), thread.getObject().getId()); - return new BookmarkablePageLink<>(id, SupervisorViewGroupThreadPage.class, parameters); - })); + add( + new ThreadsOverviewPanel<>("threads", getThreads(), new GroupThreadDiscussable(), (id, thread) -> { + PageParameters parameters = new PageParameters(pp).set( + PageParameterKeys.MAP.get(ForumThread.class), + thread.getObject().getId() + ); + return new BookmarkablePageLink<>(id, SupervisorViewGroupThreadPage.class, parameters); + }) + ); } private IModel> getThreads() { diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPage.java index 61c7f499a7..5e08d01a90 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPage.java @@ -1,14 +1,19 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMilestoneStatistics; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.statistics.IndividualMilestoneDetailsPanel; - -public class SupervisorIndividualMilestoneDetailsPage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorMilestoneStatistics { - - public SupervisorIndividualMilestoneDetailsPage(IModel model, MileStoneService.Filter filter) { - add(new IndividualMilestoneDetailsPanel("details", model, filter)); - } -} +package se.su.dsv.scipro.supervisor.pages; + +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMilestoneStatistics; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.statistics.IndividualMilestoneDetailsPanel; + +public class SupervisorIndividualMilestoneDetailsPage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorMilestoneStatistics { + + public SupervisorIndividualMilestoneDetailsPage( + IModel model, + MileStoneService.Filter filter + ) { + add(new IndividualMilestoneDetailsPanel("details", model, filter)); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPage.java index 17110c6047..3200ef4db0 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -18,55 +19,65 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.supervisor.panels.RoughDraftApprovalPanel; - -import jakarta.inject.Inject; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeSettings; @Authorization(authorizedRoles = Roles.SUPERVISOR) -public class SupervisorInteractWithReviewerPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { +public class SupervisorInteractWithReviewerPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { @Inject private ReviewerInteractionService reviewerInteractionService; + @Inject private FileService fileDescriptionService; + @Inject private RoughDraftApprovalService roughDraftApprovalService; public SupervisorInteractWithReviewerPage(final PageParameters pp) { super(pp); - - add(new WebMarkupContainer("reviewerRequested") { - @Override - protected void onConfigure() { - super.onConfigure(); - final Project project = projectModel.getObject(); - setVisible(project.getReviewer() == null && roughDraftApprovalService.findBy(project).isPresent()); + add( + new WebMarkupContainer("reviewerRequested") { + @Override + protected void onConfigure() { + super.onConfigure(); + final Project project = projectModel.getObject(); + setVisible(project.getReviewer() == null && roughDraftApprovalService.findBy(project).isPresent()); + } } - }); + ); IModel moreInformationUrl = projectModel - .map(Project::getProjectType) - .map(ProjectType::getProjectTypeSettings) - .map(ProjectTypeSettings::getReviewProcessInformationUrl); - add(new ExternalLink("review_process_information", moreInformationUrl) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(moreInformationUrl.getObject() != null); + .map(Project::getProjectType) + .map(ProjectType::getProjectTypeSettings) + .map(ProjectTypeSettings::getReviewProcessInformationUrl); + add( + new ExternalLink("review_process_information", moreInformationUrl) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(moreInformationUrl.getObject() != null); + } } - }); + ); ForumThread reviewerThread = new ReviewerInteractionForumThread(reviewerInteractionService); add(new RoughDraftApprovalPanel("roughDraftApproval", projectModel)); add(new SubmitForumReplyPanel<>("communication", projectModel, reviewerThread)); add(new TimelinePanel("timeline", projectModel)); - } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("communication_toggle", "click", "$(this).hide(); $('#communication').show();")); + response.render( + OnEventHeaderItem.forMarkupId( + "communication_toggle", + "click", + "$(this).hide(); $('#communication').show();" + ) + ); response.render(OnEventHeaderItem.forMarkupId("pgr_help_toggle", "click", "$('#pgr_help').toggle();")); } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPage.java index dedd165c1e..f72681f868 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPage.java @@ -1,26 +1,34 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.apache.wicket.Page; -import org.apache.wicket.model.IModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.statistics.MilestoneStatisticsPanel; - -public class SupervisorMilestoneStatisticsPage extends AbstractSupervisorAllProjectsPage { - - public SupervisorMilestoneStatisticsPage(PageParameters pp) { - super(pp); - add(new MilestoneStatisticsPanel("statistics", new MilestoneStatisticsPanel.PageSupplier() { - @Override - public Page individualPage(IModel model, MileStoneService.Filter filter) { - return new SupervisorIndividualMilestoneDetailsPage(model, filter); - } - - @Override - public Page projectPage(IModel model, MileStoneService.Filter filter) { - return new SupervisorProjectMilestoneDetailsPage(model, filter); - } - })); - } -} +package se.su.dsv.scipro.supervisor.pages; + +import org.apache.wicket.Page; +import org.apache.wicket.model.IModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.statistics.MilestoneStatisticsPanel; + +public class SupervisorMilestoneStatisticsPage extends AbstractSupervisorAllProjectsPage { + + public SupervisorMilestoneStatisticsPage(PageParameters pp) { + super(pp); + add( + new MilestoneStatisticsPanel( + "statistics", + new MilestoneStatisticsPanel.PageSupplier() { + @Override + public Page individualPage( + IModel model, + MileStoneService.Filter filter + ) { + return new SupervisorIndividualMilestoneDetailsPage(model, filter); + } + + @Override + public Page projectPage(IModel model, MileStoneService.Filter filter) { + return new SupervisorProjectMilestoneDetailsPage(model, filter); + } + } + ) + ); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMyGroupsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMyGroupsPage.java index cb71b9101a..c1a6563e27 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMyGroupsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorMyGroupsPage.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder; @@ -26,10 +29,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - @SystemModuleComponent(SystemModule.GROUP) public class SupervisorMyGroupsPage extends AbstractSupervisorPage implements MenuHighlightSupervisorMyGroups { @@ -38,7 +37,6 @@ public class SupervisorMyGroupsPage extends AbstractSupervisorPage implements Me public SupervisorMyGroupsPage(PageParameters pp) { super(pp); - add(new FeedbackPanel("feedback")); add(new BookmarkablePageLink<>("createGroupLink", SupervisorEditGroupPage.class)); @@ -56,19 +54,31 @@ public class SupervisorMyGroupsPage extends AbstractSupervisorPage implements Me columns.add(new DateColumn<>(Model.of("Date created"), Group::getDateCreated, "dateCreated", DateStyle.DATE)); - columns.add(new AbstractColumn<>(Model.of("Title"), "title") { - @Override - public void populateItem(Item> cellItem, String componentId, IModel rowModel) { - cellItem.add(new AjaxLinkPanel<>(componentId, rowModel, LambdaModel.of(rowModel, Group::getTitle, Group::setTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - PageParameters pp = new PageParameters(); - pp.add(PageParameterKeys.MAP.get(Group.class), model.getObject().getId()); - setResponsePage(SupervisorGroupPage.class, pp); - } - }); + columns.add( + new AbstractColumn<>(Model.of("Title"), "title") { + @Override + public void populateItem( + Item> cellItem, + String componentId, + IModel rowModel + ) { + cellItem.add( + new AjaxLinkPanel<>( + componentId, + rowModel, + LambdaModel.of(rowModel, Group::getTitle, Group::setTitle) + ) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + PageParameters pp = new PageParameters(); + pp.add(PageParameterKeys.MAP.get(Group.class), model.getObject().getId()); + setResponsePage(SupervisorGroupPage.class, pp); + } + } + ); + } } - }); + ); return columns; } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePage.java index 5c9c645334..9b73219331 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePage.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.supervisor.pages; +import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; + +import jakarta.inject.Inject; +import java.util.Arrays; +import java.util.Set; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.*; import org.apache.wicket.markup.html.list.ListItem; @@ -16,13 +21,7 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.settings.pages.AbstractSettingsPage; import se.su.dsv.scipro.system.*; -import jakarta.inject.Inject; -import java.util.Arrays; -import java.util.Set; - -import static se.su.dsv.scipro.security.auth.roles.Roles.SUPERVISOR; - -@Authorization(authorizedRoles = {SUPERVISOR}) +@Authorization(authorizedRoles = { SUPERVISOR }) public class SupervisorProfilePage extends AbstractSettingsPage { @Inject @@ -37,34 +36,44 @@ public class SupervisorProfilePage extends AbstractSettingsPage { public ProfileForm(String id, final IModel model) { super(id, model); - - add(new BootstrapCheckBoxMultipleChoice<>("languages", LambdaModel.of(getModel(), User::getLanguages, User::setLanguages), Arrays.asList(Language.values()), - new EnumChoiceRenderer<>(this))); + add( + new BootstrapCheckBoxMultipleChoice<>( + "languages", + LambdaModel.of(getModel(), User::getLanguages, User::setLanguages), + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ) + ); add(new Label("unit", getModel().map(User::getUnit).map(Unit::getTitle))); - add(new Label("noUnit", new ResourceModel("noUnit")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getModelObject().getUnit() == null); + add( + new Label("noUnit", new ResourceModel("noUnit")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getModelObject().getUnit() == null); + } } - }); + ); - add(new ListView<>("researchAreas", - new ListAdapterModel<>(getActiveResearchAreas())) { - @Override - protected void populateItem(ListItem item) { - item.add(new Label("areaName", item.getModel().map(ResearchArea::getTitle))); + add( + new ListView<>("researchAreas", new ListAdapterModel<>(getActiveResearchAreas())) { + @Override + protected void populateItem(ListItem item) { + item.add(new Label("areaName", item.getModel().map(ResearchArea::getTitle))); + } } - }); + ); - add(new Label("noAreas", new ResourceModel("noAreas")) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(getActiveResearchAreas().getObject().isEmpty()); + add( + new Label("noAreas", new ResourceModel("noAreas")) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed(getActiveResearchAreas().getObject().isEmpty()); + } } - }); + ); } private IModel> getActiveResearchAreas() { diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPage.java index 2fa7da749d..12949ce3a8 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPage.java @@ -20,7 +20,9 @@ import se.su.dsv.scipro.projectstate.ProjectStatePanel; import se.su.dsv.scipro.supervisor.panels.SupervisorExternalProjectPanel; import se.su.dsv.scipro.thesislink.ExternalLinkPanel; -public class SupervisorProjectDetailsPage extends AbstractSupervisorProjectDetailsPage implements MenuHighlightSupervisorMyProjects { +public class SupervisorProjectDetailsPage + extends AbstractSupervisorProjectDetailsPage + implements MenuHighlightSupervisorMyProjects { public static final String FINAL_SEMINAR_NEW = "finalSeminarNew"; public static final String EXTERNAL_ORGANIZATION = "externalOrganization"; @@ -35,17 +37,23 @@ public class SupervisorProjectDetailsPage extends AbstractSupervisorProjectDetai public SupervisorProjectDetailsPage(PageParameters pp) { super(pp); - add(new ExternalLinkPanel(EXTERNAL_LINK, projectModel)); - add(new ExternalResourcesPanel(EXTERNAL_RESOURCES, LambdaModel.of(projectModel, Project::getProjectType, Project::setProjectType))); + add( + new ExternalResourcesPanel( + EXTERNAL_RESOURCES, + LambdaModel.of(projectModel, Project::getProjectType, Project::setProjectType) + ) + ); - add(new ProjectStatePanel(STATE_OF_MIND_PANEL, projectModel) { - @Override - public boolean isAuthorView() { - return false; + add( + new ProjectStatePanel(STATE_OF_MIND_PANEL, projectModel) { + @Override + public boolean isAuthorView() { + return false; + } } - }); + ); add(new LatestEventsPanel(LATEST_UPLOAD, projectModel)); add(new PeerSummaryPanel(PEER_SUMMARY, projectModel)); @@ -59,10 +67,13 @@ public class SupervisorProjectDetailsPage extends AbstractSupervisorProjectDetai add(new OverviewSeminarPanel(FINAL_SEMINAR_NEW, projectModel)); add(new MilestoneSummaryPanel(MILESTONE, projectModel)); - add(new GroupsOverviewPanel("groups", projectModel, (id, pp1) -> new BookmarkablePageLink<>(id, SupervisorGroupPage.class, pp1))); + add( + new GroupsOverviewPanel("groups", projectModel, (id, pp1) -> + new BookmarkablePageLink<>(id, SupervisorGroupPage.class, pp1) + ) + ); add(new ChecklistOverviewPanel("checklistOverview", projectModel)); - } @Override diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPage.java index f97be18975..c9277bee67 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPage.java @@ -1,15 +1,20 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMilestoneStatistics; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.statistics.ProjectMilestoneDetailsPanel; - -public class SupervisorProjectMilestoneDetailsPage extends AbstractSupervisorAllProjectsPage implements MenuHighlightSupervisorMilestoneStatistics { - - public SupervisorProjectMilestoneDetailsPage(IModel model, MileStoneService.Filter filter) { - super(); - add(new ProjectMilestoneDetailsPanel("details", model, filter)); - } -} +package se.su.dsv.scipro.supervisor.pages; + +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMilestoneStatistics; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.statistics.ProjectMilestoneDetailsPanel; + +public class SupervisorProjectMilestoneDetailsPage + extends AbstractSupervisorAllProjectsPage + implements MenuHighlightSupervisorMilestoneStatistics { + + public SupervisorProjectMilestoneDetailsPage( + IModel model, + MileStoneService.Filter filter + ) { + super(); + add(new ProjectMilestoneDetailsPanel("details", model, filter)); + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPage.java index 03a5311aed..44796a7ce3 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPage.java @@ -10,8 +10,6 @@ public class SupervisorStartPage extends AbstractSupervisorPage { public SupervisorStartPage(PageParameters pp) { super(pp); - add(new SupervisorMyProjectsPanel(PROJECTS_OVERVIEW_PANEL)); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorViewGroupThreadPage.java b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorViewGroupThreadPage.java index 840930e001..5b77ea926f 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorViewGroupThreadPage.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/pages/SupervisorViewGroupThreadPage.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.pages; +import jakarta.inject.Inject; import org.apache.wicket.Component; import org.apache.wicket.RestartResponseException; import org.apache.wicket.markup.html.link.BookmarkablePageLink; @@ -9,22 +10,21 @@ import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorMyGroups; import se.su.dsv.scipro.forum.GroupForumService; -import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.dataobjects.ForumThread; +import se.su.dsv.scipro.forum.dataobjects.GroupThread; import se.su.dsv.scipro.forum.panels.threaded.ViewForumThreadPanel; import se.su.dsv.scipro.group.GroupForumThread; import se.su.dsv.scipro.util.PageParameterKeys; -import jakarta.inject.Inject; - -public class SupervisorViewGroupThreadPage extends AbstractSupervisorGroupPage implements MenuHighlightSupervisorMyGroups { +public class SupervisorViewGroupThreadPage + extends AbstractSupervisorGroupPage + implements MenuHighlightSupervisorMyGroups { @Inject private GroupForumService groupForumService; public SupervisorViewGroupThreadPage(final PageParameters parameters) { super(parameters); - final long threadId = parameters.get(PageParameterKeys.MAP.get(ForumThread.class)).toLong(0L); final IModel groupThreadModel = new LoadableDetachableModel<>() { @Override @@ -40,13 +40,16 @@ public class SupervisorViewGroupThreadPage extends AbstractSupervisorGroupPage i add(new FeedbackPanel("feedback")); - add(new ViewForumThreadPanel<>("thread", groupThreadModel, new GroupForumThread(groupForumService)) { - @Override - protected Component newBackLink(final String id) { - PageParameters pageParameters = new PageParameters(parameters) - .remove(PageParameterKeys.MAP.get(ForumThread.class)); - return new BookmarkablePageLink(id, SupervisorGroupPage.class, pageParameters); + add( + new ViewForumThreadPanel<>("thread", groupThreadModel, new GroupForumThread(groupForumService)) { + @Override + protected Component newBackLink(final String id) { + PageParameters pageParameters = new PageParameters(parameters).remove( + PageParameterKeys.MAP.get(ForumThread.class) + ); + return new BookmarkablePageLink(id, SupervisorGroupPage.class, pageParameters); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanel.java index e1e4a91e68..00ba26aa74 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanel.java @@ -17,55 +17,102 @@ import se.su.dsv.scipro.reviewing.Decision; import se.su.dsv.scipro.reviewing.ReviewerApproval; public class FinalSeminarApprovalProcessPanel extends GenericPanel { + public FinalSeminarApprovalProcessPanel(final String id, final IModel process) { super(id, process); - - add(new ViewAttachmentPanel("currentThesis", process.map(ReviewerApproval::getCurrentThesis).map(FileReference::getFileDescription), DateStyle.DATE)); + add( + new ViewAttachmentPanel( + "currentThesis", + process.map(ReviewerApproval::getCurrentThesis).map(FileReference::getFileDescription), + DateStyle.DATE + ) + ); add(new EnumLabel<>("currentStatus", process.map(ReviewerApproval::getCurrentStatus))); - add(new MultiLineLabel("currentDecision.comment", process.map(ReviewerApproval::getCurrentDecision).map(Decision::getComment)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); + add( + new MultiLineLabel( + "currentDecision.comment", + process.map(ReviewerApproval::getCurrentDecision).map(Decision::getComment) + ) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } } - }); - add(new MultiLineLabel("currentReason", process.map(ReviewerApproval::getCurrentReason)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject().isDecided()); + ); + add( + new MultiLineLabel("currentReason", process.map(ReviewerApproval::getCurrentReason)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject().isDecided()); + } } - }); - add(new ViewAttachmentPanel("currentAttachment", new OrNullModel<>(process.map(ReviewerApproval::getCurrentAttachment)).map(FileReference::getFileDescription))); - add(new ListView<>("history", process.map(ReviewerApproval::getHistory)) { - @Override - protected void populateItem(final ListItem item) { - final IModel decision = item.getModel(); - item.add(new MultiLineLabel("comment", decision.map(Decision::getComment)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); - } - }); - item.add(new MultiLineLabel("reason", decision.map(Decision::getReason)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getDefaultModelObject() != null); - } - }); - item.add(new ViewAttachmentPanel("thesis", decision.map(Decision::getThesis).map(FileReference::getFileDescription), DateStyle.DATE)); - item.add(new EnumLabel<>("status", decision.map(Decision::getStatus)) { - @Override - public void renderHead(IHeaderResponse response) { - super.renderHead(response); - response.render(OnEventHeaderItem.forComponent(this, "click", "$(this).siblings('div').slideToggle(); return false")); - } - }); - item.add(new DateLabel("decisionDate", decision.map(Decision::getDecisionDate), DateStyle.DATE)); - item.add(new ViewAttachmentPanel("attachment", new OrNullModel<>(item.getModel().map(Decision::getAttachment)).map(FileReference::getFileDescription))); + ); + add( + new ViewAttachmentPanel( + "currentAttachment", + new OrNullModel<>(process.map(ReviewerApproval::getCurrentAttachment)).map( + FileReference::getFileDescription + ) + ) + ); + add( + new ListView<>("history", process.map(ReviewerApproval::getHistory)) { + @Override + protected void populateItem(final ListItem item) { + final IModel decision = item.getModel(); + item.add( + new MultiLineLabel("comment", decision.map(Decision::getComment)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } + } + ); + item.add( + new MultiLineLabel("reason", decision.map(Decision::getReason)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getDefaultModelObject() != null); + } + } + ); + item.add( + new ViewAttachmentPanel( + "thesis", + decision.map(Decision::getThesis).map(FileReference::getFileDescription), + DateStyle.DATE + ) + ); + item.add( + new EnumLabel<>("status", decision.map(Decision::getStatus)) { + @Override + public void renderHead(IHeaderResponse response) { + super.renderHead(response); + response.render( + OnEventHeaderItem.forComponent( + this, + "click", + "$(this).siblings('div').slideToggle(); return false" + ) + ); + } + } + ); + item.add(new DateLabel("decisionDate", decision.map(Decision::getDecisionDate), DateStyle.DATE)); + item.add( + new ViewAttachmentPanel( + "attachment", + new OrNullModel<>(item.getModel().map(Decision::getAttachment)).map( + FileReference::getFileDescription + ) + ) + ); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/ProjectNoteColumn.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/ProjectNoteColumn.java index 77424cf02a..abb9418c73 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/ProjectNoteColumn.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/ProjectNoteColumn.java @@ -1,6 +1,8 @@ package se.su.dsv.scipro.supervisor.panels; import jakarta.inject.Inject; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; @@ -25,18 +27,19 @@ import se.su.dsv.scipro.project.ProjectNoteService; import se.su.dsv.scipro.settings.dataobjects.SupervisorProjectNoteDisplay; import se.su.dsv.scipro.system.User; -import java.time.LocalTime; -import java.time.temporal.ChronoUnit; - public class ProjectNoteColumn extends AbstractExportableColumn { + @Inject private ProjectNoteService projectNoteService; private final IModel user; private final IModel supervisorProjectNoteDisplayModel; - public ProjectNoteColumn(IModel displayModel, IModel user, - IModel supervisorProjectNoteDisplayModel) { + public ProjectNoteColumn( + IModel displayModel, + IModel user, + IModel supervisorProjectNoteDisplayModel + ) { super(displayModel); Injector.get().inject(this); this.supervisorProjectNoteDisplayModel = supervisorProjectNoteDisplayModel; @@ -45,21 +48,18 @@ public class ProjectNoteColumn extends AbstractExportableColumn @Override public IModel getDataModel(IModel rowModel) { - return LoadableDetachableModel.of(() -> projectNoteService.getUserNote( - rowModel.getObject(), - user.getObject())); + return LoadableDetachableModel.of(() -> projectNoteService.getUserNote(rowModel.getObject(), user.getObject())); } @Override - public void populateItem(Item> cellItem, String componentId, - IModel rowModel) { + public void populateItem(Item> cellItem, String componentId, IModel rowModel) { cellItem.add(new ViewAndEditNoteCellPanel(componentId, rowModel)); } private class ViewAndEditNoteCellPanel extends GenericPanel { + public ViewAndEditNoteCellPanel(String id, IModel model) { super(id, model); - ModalWindowPlus modal = new LargeModalWindow("edit_note_modal"); modal.setTitle(new StringResourceModel("note.modal.title", this, model)); modal.setContent(componentId -> new ViewAndEditNoteForm(componentId, model)); @@ -68,20 +68,28 @@ public class ProjectNoteColumn extends AbstractExportableColumn setOutputMarkupId(true); modal.onClose(target -> target.add(this)); - add(new MaxLengthLabel("shortened_note", getDataModel(model), Model.of(100)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(supervisorProjectNoteDisplayModel.getObject() == SupervisorProjectNoteDisplay.COMPACT); + add( + new MaxLengthLabel("shortened_note", getDataModel(model), Model.of(100)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + supervisorProjectNoteDisplayModel.getObject() == SupervisorProjectNoteDisplay.COMPACT + ); + } } - }); - add(new MultiLineLabel("full_note", getDataModel(model)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisibilityAllowed(supervisorProjectNoteDisplayModel.getObject() == SupervisorProjectNoteDisplay.FULL); + ); + add( + new MultiLineLabel("full_note", getDataModel(model)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisibilityAllowed( + supervisorProjectNoteDisplayModel.getObject() == SupervisorProjectNoteDisplay.FULL + ); + } } - }); + ); AjaxLink noteLink = new AjaxLink<>("view_note") { @Override @@ -94,19 +102,15 @@ public class ProjectNoteColumn extends AbstractExportableColumn } private class ViewAndEditNoteForm extends GenericPanel { + public ViewAndEditNoteForm(String id, IModel project) { super(id, project); - IModel note = getDataModel(project); Form form = new Form<>("form", project) { @Override protected void onSubmit() { - projectNoteService.setUserNote( - project.getObject(), - user.getObject(), - note.getObject() - ); + projectNoteService.setUserNote(project.getObject(), user.getObject(), note.getObject()); success("Note saved at " + LocalTime.now().truncatedTo(ChronoUnit.SECONDS)); } }; @@ -115,12 +119,14 @@ public class ProjectNoteColumn extends AbstractExportableColumn form.add(new FencedFeedbackPanel("feedback", form)); form.add(new TextArea<>("note", note)); - form.add(new AjaxSubmitLink("save") { - @Override - protected void onAfterSubmit(AjaxRequestTarget target) { - target.add(form); + form.add( + new AjaxSubmitLink("save") { + @Override + protected void onAfterSubmit(AjaxRequestTarget target) { + target.add(form); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/RoughDraftApprovalPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/RoughDraftApprovalPanel.java index 617f935d66..c33a83e97e 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/RoughDraftApprovalPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/RoughDraftApprovalPanel.java @@ -1,25 +1,23 @@ -package se.su.dsv.scipro.supervisor.panels; - -import org.apache.wicket.model.IModel; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.reviewing.ReviewerApprovalService; -import se.su.dsv.scipro.reviewing.RoughDraftApproval; -import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; - -import jakarta.inject.Inject; - -public class RoughDraftApprovalPanel extends SupervisorApprovalPanel { - - @Inject - private RoughDraftApprovalService roughDraftApprovalService; - - public RoughDraftApprovalPanel(String id, final IModel model) { - super(id, model); - } - - @Override - protected ReviewerApprovalService getService() { - return roughDraftApprovalService; - } - -} +package se.su.dsv.scipro.supervisor.panels; + +import jakarta.inject.Inject; +import org.apache.wicket.model.IModel; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.reviewing.ReviewerApprovalService; +import se.su.dsv.scipro.reviewing.RoughDraftApproval; +import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; + +public class RoughDraftApprovalPanel extends SupervisorApprovalPanel { + + @Inject + private RoughDraftApprovalService roughDraftApprovalService; + + public RoughDraftApprovalPanel(String id, final IModel model) { + super(id, model); + } + + @Override + protected ReviewerApprovalService getService() { + return roughDraftApprovalService; + } +} diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorApprovalPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorApprovalPanel.java index 32920d25d7..49ef4b564c 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorApprovalPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorApprovalPanel.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.supervisor.panels; import jakarta.inject.Inject; +import java.util.Arrays; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnEventHeaderItem; @@ -20,8 +21,6 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.ResearchAreaService; -import java.util.Arrays; - public abstract class SupervisorApprovalPanel extends GenericPanel { @Inject @@ -29,21 +28,28 @@ public abstract class SupervisorApprovalPanel extend public SupervisorApprovalPanel(String id, IModel model) { super(id, model); - add(new RequestFinalSeminarApprovalForm("requestApproval", model)); - add(new FinalSeminarApprovalProcessPanel("process", getProcess(model)) { - @Override - protected void onConfigure() { - super.onConfigure(); - setVisible(getModelObject() != null); + add( + new FinalSeminarApprovalProcessPanel("process", getProcess(model)) { + @Override + protected void onConfigure() { + super.onConfigure(); + setVisible(getModelObject() != null); + } } - }); + ); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); - response.render(OnEventHeaderItem.forMarkupId("info_toggle", "click", "$(this).parent().parent().find('[data-info]').toggle()")); + response.render( + OnEventHeaderItem.forMarkupId( + "info_toggle", + "click", + "$(this).parent().parent().find('[data-info]').toggle()" + ) + ); } protected IModel getProcess(final IModel project) { @@ -58,12 +64,12 @@ public abstract class SupervisorApprovalPanel extend protected abstract ReviewerApprovalService getService(); protected class RequestFinalSeminarApprovalForm extends StatelessForm { + private final FileUploadField thesisUpload; private IModel comment = new Model<>(); public RequestFinalSeminarApprovalForm(final String id, final IModel project) { super(id, project); - add(new FencedFeedbackPanel("feedback", this)); add(new TextArea<>("comment", comment)); @@ -71,19 +77,21 @@ public abstract class SupervisorApprovalPanel extend thesisUpload.setRequired(true); add(thesisUpload); - DropDownChoice researchArea = new DropDownChoice<>("area", - LambdaModel.of(project, Project::getResearchArea, Project::setResearchArea), - researchAreaService::findNotDeleted, - new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId)); + DropDownChoice researchArea = new DropDownChoice<>( + "area", + LambdaModel.of(project, Project::getResearchArea, Project::setResearchArea), + researchAreaService::findNotDeleted, + new LambdaChoiceRenderer<>(ResearchArea::getTitle, ResearchArea::getId) + ); researchArea.setRequired(true); add(researchArea); - final DropDownChoice language = - new DropDownChoice<>( - "language", - LambdaModel.of(getModel(), Project::getLanguage, Project::setLanguage), - Arrays.asList(Language.values()), - new EnumChoiceRenderer<>(this)); + final DropDownChoice language = new DropDownChoice<>( + "language", + LambdaModel.of(getModel(), Project::getLanguage, Project::setLanguage), + Arrays.asList(Language.values()), + new EnumChoiceRenderer<>(this) + ); language.setRequired(true); add(language); } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanel.java index 74a6fd113d..6cdb2582c5 100644 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanel.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.supervisor.panels; +import jakarta.inject.Inject; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.feedback.ContainerFeedbackMessageFilter; @@ -17,8 +18,6 @@ import se.su.dsv.scipro.project.ExternalOrganization; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; -import jakarta.inject.Inject; - public class SupervisorExternalProjectPanel extends GenericPanel { @Inject @@ -28,13 +27,19 @@ public class SupervisorExternalProjectPanel extends GenericPanel { public SupervisorExternalProjectPanel(final String id, final IModel model) { super(id, model); - createEnclosure(); createForm(); } private void createEnclosure() { - TextField textField = new TextField<>(EXTERNAL_FIELD, LambdaModel.of(getModel().map(Project::getExternalOrganization), ExternalOrganization::getName, ExternalOrganization::setName)); + TextField textField = new TextField<>( + EXTERNAL_FIELD, + LambdaModel.of( + getModel().map(Project::getExternalOrganization), + ExternalOrganization::getName, + ExternalOrganization::setName + ) + ); InfoPanel helpIcon = new InfoPanel(HELP_TEXT, new ResourceModel("helpText")); @@ -60,18 +65,20 @@ public class SupervisorExternalProjectPanel extends GenericPanel { }; form.setOutputMarkupId(true); - form.add(new AjaxCheckBox(EXTERNAL_CHECKBOX, Model.of(getProject().hasExternalOrganization())) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - getProject().setExternalOrganization(getModelObject() ? new ExternalOrganization() : null); - projectService.save(getProject()); - target.add(form); + form.add( + new AjaxCheckBox(EXTERNAL_CHECKBOX, Model.of(getProject().hasExternalOrganization())) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + getProject().setExternalOrganization(getModelObject() ? new ExternalOrganization() : null); + projectService.save(getProject()); + target.add(form); - if (!getModelObject()) { - info(getString("external.organization.removed")); + if (!getModelObject()) { + info(getString("external.organization.removed")); + } } } - }); + ); form.add(enclosure); form.add(new FeedbackPanel(FEEDBACK, new ContainerFeedbackMessageFilter(form))); diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorMyProjectsPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorMyProjectsPanel.java index e3cab053eb..2b3c9dce94 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorMyProjectsPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorMyProjectsPanel.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.supervisor.panels; +import static java.util.Arrays.asList; + +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; @@ -39,12 +44,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeService; import se.su.dsv.scipro.system.User; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - -import static java.util.Arrays.asList; - public class SupervisorMyProjectsPanel extends Panel { public static final String FILTER_FORM = "filterForm"; @@ -56,10 +55,13 @@ public class SupervisorMyProjectsPanel extends Panel { @Inject private ProjectTypeService projectTypeService; + @Inject private ProjectService projectService; + @Inject private UserProfileService profileService; + @Inject private ProjectForumService projectForumService; @@ -75,7 +77,10 @@ public class SupervisorMyProjectsPanel extends Panel { } private void dataViewSetup() { - SortableDataProvider provider = new FilteredDataProvider<>(projectService, Model.of(this.filter)); + SortableDataProvider provider = new FilteredDataProvider<>( + projectService, + Model.of(this.filter) + ); provider.setSort("dateCreated", SortOrder.DESCENDING); dataPanel = new ExportableDataPanel<>(DATA_PANEL, createColumns(), provider); add(dataPanel); @@ -88,14 +93,24 @@ public class SupervisorMyProjectsPanel extends Panel { columns.add(new TemporalColumn<>(Model.of("Started"), "startDate", Project::getStartDate)); columns.add(new LambdaColumn<>(Model.of("Type"), "projectType.name", Project::getProjectTypeName)); columns.add(new ProjectTitleColumn(Model.of("Title"), "title")); - columns.add(new MultipleUsersColumn<>(Model.of("Authors")) { - @Override - public ListAdapterModel getUsers(final IModel rowModel) { - return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + columns.add( + new MultipleUsersColumn<>(Model.of("Authors")) { + @Override + public ListAdapterModel getUsers(final IModel rowModel) { + return new ListAdapterModel<>(rowModel.map(Project::getProjectParticipants)); + } } - }); - columns.add(new ProjectNoteColumn(Model.of("Note"), LoadableDetachableModel.of(this::currentUser), supervisorProjectNoteDisplayModel)); - columns.add(new UserColumn<>(Model.of("Head supervisor"), "headSupervisor.fullName", Project::getHeadSupervisor)); + ); + columns.add( + new ProjectNoteColumn( + Model.of("Note"), + LoadableDetachableModel.of(this::currentUser), + supervisorProjectNoteDisplayModel + ) + ); + columns.add( + new UserColumn<>(Model.of("Head supervisor"), "headSupervisor.fullName", Project::getHeadSupervisor) + ); return columns; } @@ -132,47 +147,87 @@ public class SupervisorMyProjectsPanel extends Panel { public FilterForm(String id, IModel filterParams) { super(id, filterParams); - - add(new AjaxCheckBox(SUPERVISOR, LambdaModel.of(filterParams, ProjectService.Filter::isFilterSupervisor, ProjectService.Filter::setFilterSupervisor)) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); - updateProfileWithCurrentFilter(); + add( + new AjaxCheckBox( + SUPERVISOR, + LambdaModel.of( + filterParams, + ProjectService.Filter::isFilterSupervisor, + ProjectService.Filter::setFilterSupervisor + ) + ) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + updateProfileWithCurrentFilter(); + } } - }); - add(new AjaxCheckBoxMultipleChoice<>(ROLE_FILTER, LambdaModel.of(filterParams, ProjectService.Filter::getRoles, ProjectService.Filter::setRoles), List.of(ProjectTeamMemberRoles.CO_SUPERVISOR), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); - updateProfileWithCurrentFilter(); + ); + add( + new AjaxCheckBoxMultipleChoice<>( + ROLE_FILTER, + LambdaModel.of(filterParams, ProjectService.Filter::getRoles, ProjectService.Filter::setRoles), + List.of(ProjectTeamMemberRoles.CO_SUPERVISOR), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + updateProfileWithCurrentFilter(); + } } - }); - add(new AjaxCheckBoxMultipleChoice<>(STATUS_FILTER, LambdaModel.of(filterParams, ProjectService.Filter::getStatuses, ProjectService.Filter::setStatuses), asList(ProjectStatus.values()), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); - updateProfileWithCurrentFilter(); + ); + add( + new AjaxCheckBoxMultipleChoice<>( + STATUS_FILTER, + LambdaModel.of( + filterParams, + ProjectService.Filter::getStatuses, + ProjectService.Filter::setStatuses + ), + asList(ProjectStatus.values()), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + updateProfileWithCurrentFilter(); + } } - }); - add(new AjaxCheckBoxMultipleChoice<>(TYPE_FILTER, LambdaModel.of(filterParams, ProjectService.Filter::getProjectTypes, ProjectService.Filter::setProjectTypes), projectTypeService.findBySupervisorProjects(SciProSession.get().getUser()), new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); - updateProfileWithCurrentFilter(); + ); + add( + new AjaxCheckBoxMultipleChoice<>( + TYPE_FILTER, + LambdaModel.of( + filterParams, + ProjectService.Filter::getProjectTypes, + ProjectService.Filter::setProjectTypes + ), + projectTypeService.findBySupervisorProjects(SciProSession.get().getUser()), + new LambdaChoiceRenderer<>(ProjectType::getName, ProjectType::getId) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + updateProfileWithCurrentFilter(); + } } - }); + ); BootstrapRadioChoice noteDisplay = new BootstrapRadioChoice<>( - "note_display", - supervisorProjectNoteDisplayModel, - List.of(SupervisorProjectNoteDisplay.values()), - new EnumChoiceRenderer<>(this)); - noteDisplay.add(new AjaxFormChoiceComponentUpdatingBehavior() { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); - updateProfileWithCurrentFilter(); + "note_display", + supervisorProjectNoteDisplayModel, + List.of(SupervisorProjectNoteDisplay.values()), + new EnumChoiceRenderer<>(this) + ); + noteDisplay.add( + new AjaxFormChoiceComponentUpdatingBehavior() { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + updateProfileWithCurrentFilter(); + } } - }); + ); add(noteDisplay); } @@ -188,27 +243,32 @@ public class SupervisorMyProjectsPanel extends Panel { } private class ProjectForumStateColumn extends AbstractColumn { + public ProjectForumStateColumn(IModel label) { super(label); } @Override public void populateItem(Item> item, String id, IModel projectModel) { - item.add(new AbstractReadStatePanel(id) { - @Override - protected boolean isRead() { - return !projectForumService.hasUnreadThreads( + item.add( + new AbstractReadStatePanel(id) { + @Override + protected boolean isRead() { + return !projectForumService.hasUnreadThreads( projectModel.getObject(), - SciProSession.get().getUser()); - } + SciProSession.get().getUser() + ); + } - @Override - protected void onFlagClick(AjaxRequestTarget target) { - setResponsePage( + @Override + protected void onFlagClick(AjaxRequestTarget target) { + setResponsePage( SupervisorThreadedForumPage.class, - SupervisorThreadedForumPage.getPageParameters(projectModel.getObject())); + SupervisorThreadedForumPage.getPageParameters(projectModel.getObject()) + ); + } } - }); + ); } } } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanel.java index 2aa29d72eb..a59683e880 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -17,10 +20,6 @@ import se.su.dsv.scipro.report.GradingReportService; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.supervisor.pages.*; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class SupervisorSubTabMenuPanel extends AbstractMenuPanel { public static final String SEND_TO_EXAMINER = "Finishing up"; @@ -36,13 +35,19 @@ public class SupervisorSubTabMenuPanel extends AbstractMenuPanel { @Inject private MilestoneActivityTemplateService milestoneActivityTemplateService; + @Inject private GradingReportService gradingReportService; private final PageParameters projectParams; private IModel projectModel; - public SupervisorSubTabMenuPanel(String id, Class containerClass, PageParameters projectParams, IModel projectModel) { + public SupervisorSubTabMenuPanel( + String id, + Class containerClass, + PageParameters projectParams, + IModel projectModel + ) { super(id, AbstractSupervisorProjectDetailsPage.class, containerClass); this.projectParams = projectParams; this.projectModel = projectModel; @@ -51,20 +56,48 @@ public class SupervisorSubTabMenuPanel extends AbstractMenuPanel { @Override protected List getItemList() { List items = new ArrayList<>(); - items.add(new MenuItem(OVERVIEW, SupervisorProjectDetailsPage.class, MenuHighlightSupervisorOverview.class, projectParams)); + items.add( + new MenuItem( + OVERVIEW, + SupervisorProjectDetailsPage.class, + MenuHighlightSupervisorOverview.class, + projectParams + ) + ); if (mileStonesAreAvailable()) { items.add(new MenuItem(MILESTONES, SupervisorMileStonePage.class, projectParams)); } - items.add(new MenuItem(ACTIVITY_PLAN, SupervisorActivityPlanPage.class, MenuHighlightSupervisorActivityPlan.class, projectParams)); + items.add( + new MenuItem( + ACTIVITY_PLAN, + SupervisorActivityPlanPage.class, + MenuHighlightSupervisorActivityPlan.class, + projectParams + ) + ); items.add(new MenuItem(FIRST_MEETING, SupervisorFirstMeetingPage.class, projectParams)); items.add(new MenuItem(FILES, SupervisorFilePage.class, projectParams)); items.add(new MenuItem(FORUM, SupervisorForumBasePage.class, MenuHighlightForum.class, projectParams)); if (isSupervisor() && isReviewed()) { items.add(new MenuItem(INTERACT_WITH_REVIEWER, SupervisorInteractWithReviewerPage.class, projectParams)); } - items.add(new MenuItem(FINAL_SEMINAR, SupervisorFinalSeminarPage.class, MenuHighlightFinalSeminar.class, projectParams)); + items.add( + new MenuItem( + FINAL_SEMINAR, + SupervisorFinalSeminarPage.class, + MenuHighlightFinalSeminar.class, + projectParams + ) + ); if (gradingReportTemplateIsAvailable() && hasDaisyConnection()) { - items.add(new MenuItem(SEND_TO_EXAMINER, SupervisorGradingReportPage.class, MenuHighlightSupervisorGradingReport.class, projectParams)); + items.add( + new MenuItem( + SEND_TO_EXAMINER, + SupervisorGradingReportPage.class, + MenuHighlightSupervisorGradingReport.class, + projectParams + ) + ); } return items; } @@ -87,12 +120,13 @@ public class SupervisorSubTabMenuPanel extends AbstractMenuPanel { } private boolean gradingReportTemplateIsAvailable() { - return gradingReportService.getTemplate(projectModel.getObject()) != null; + return (gradingReportService.getTemplate(projectModel.getObject()) != null); } private boolean mileStonesAreAvailable() { Project project = projectModel.getObject(); - return milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate()) != 0; + return ( + milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate()) != 0 + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanel.java b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanel.java index 4c0077e763..96d936ab89 100755 --- a/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanel.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.panels; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.components.menuhighlighting.MenuHighlightSupervisorAllProjects; @@ -14,39 +17,35 @@ import se.su.dsv.scipro.supervisor.pages.SupervisorStartPage; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectTypeService; -import jakarta.inject.Inject; -import java.util.ArrayList; -import java.util.List; - public class SupervisorTabMenuPanel extends AbstractMenuPanel { @Inject private ProjectTypeService projectTypeService; public SupervisorTabMenuPanel(String id, Class containerClass) { - super(id, AbstractSupervisorPage.class, containerClass); - } + super(id, AbstractSupervisorPage.class, containerClass); + } - @Override - protected List getItemList() { - - List items = new ArrayList<>(); - items.add(new MenuItem("My projects", SupervisorStartPage.class, MenuHighlightSupervisorMyProjects.class)); - items.add(new MenuItem("My groups", SupervisorMyGroupsPage.class, MenuHighlightSupervisorMyGroups.class)); + @Override + protected List getItemList() { + List items = new ArrayList<>(); + items.add(new MenuItem("My projects", SupervisorStartPage.class, MenuHighlightSupervisorMyProjects.class)); + items.add(new MenuItem("My groups", SupervisorMyGroupsPage.class, MenuHighlightSupervisorMyGroups.class)); if (matchIsEnabled()) { items.add(new MenuItem("Ideas", SupervisorIdeaStartPage.class, MenuHighlightSupervisorProjectIdea.class)); } - items.add(new MenuItem("All projects", SupervisorAllProjectsPage.class, MenuHighlightSupervisorAllProjects.class)); - return items; - } + items.add( + new MenuItem("All projects", SupervisorAllProjectsPage.class, MenuHighlightSupervisorAllProjects.class) + ); + return items; + } private boolean matchIsEnabled() { return projectTypeService.projectTypeWithModuleExists(ProjectModule.MATCH); } @Override - protected MenuType getMenuType() { - return MenuType.TAB_MULTIPLE_ROWS; - } - + protected MenuType getMenuType() { + return MenuType.TAB_MULTIPLE_ROWS; + } } diff --git a/view/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkPanel.java b/view/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkPanel.java index ad9add6f42..48b8eecec4 100644 --- a/view/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/thesislink/ExternalLinkPanel.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.thesislink; +import jakarta.inject.Inject; +import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.markup.ComponentTag; @@ -21,9 +23,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import jakarta.inject.Inject; -import java.util.List; - public class ExternalLinkPanel extends GenericPanel { public static final String CONTAINER = "container"; @@ -45,7 +44,6 @@ public class ExternalLinkPanel extends GenericPanel { public ExternalLinkPanel(String id, IModel projectModel) { super(id, projectModel); - container = new WebMarkupContainer(CONTAINER); container.setOutputMarkupId(true); add(container); @@ -58,8 +56,19 @@ public class ExternalLinkPanel extends GenericPanel { links = new ListView<>(LINKS, getLoadedList()) { @Override protected void populateItem(final ListItem item) { - item.add(new UserLinkPanel(USER, LambdaModel.of(item.getModel(), ExternalLink::getUser, ExternalLink::setUser))); - item.add(new org.apache.wicket.markup.html.link.ExternalLink(LINK, LambdaModel.of(item.getModel(), ExternalLink::getUrl, ExternalLink::setUrl), LambdaModel.of(item.getModel(), ExternalLink::getDescription, ExternalLink::setDescription))); + item.add( + new UserLinkPanel( + USER, + LambdaModel.of(item.getModel(), ExternalLink::getUser, ExternalLink::setUser) + ) + ); + item.add( + new org.apache.wicket.markup.html.link.ExternalLink( + LINK, + LambdaModel.of(item.getModel(), ExternalLink::getUrl, ExternalLink::setUrl), + LambdaModel.of(item.getModel(), ExternalLink::getDescription, ExternalLink::setDescription) + ) + ); item.add(new DeleteLink(DELETE, item.getModel())); } }; @@ -73,10 +82,16 @@ public class ExternalLinkPanel extends GenericPanel { } private ExternalLink newLink() { - return ExternalLink.builder().project(getModelObject()).url("").user(SciProSession.get().getUser()).description("").build(); + return ExternalLink.builder() + .project(getModelObject()) + .url("") + .user(SciProSession.get().getUser()) + .description("") + .build(); } private class DeleteLink extends AjaxConfirmationLink { + public DeleteLink(String id, IModel model) { super(id, model, "Are you sure you want to delete the link?"); } @@ -109,13 +124,18 @@ public class ExternalLinkPanel extends GenericPanel { public LinkForm(String id, final IModel externalLinkModel) { super(id, externalLinkModel); - - TextField url = new RequiredTextField<>(URL, LambdaModel.of(externalLinkModel, ExternalLink::getUrl, ExternalLink::setUrl)); + TextField url = new RequiredTextField<>( + URL, + LambdaModel.of(externalLinkModel, ExternalLink::getUrl, ExternalLink::setUrl) + ); url.add(StringValidator.lengthBetween(0, ExternalLink.MAX_CHARS)); - url.add(new UrlValidator(new String[]{"http", "https"})); + url.add(new UrlValidator(new String[] { "http", "https" })); add(url); - TextField description = new RequiredTextField<>(DESCRIPTION, LambdaModel.of(externalLinkModel, ExternalLink::getDescription, ExternalLink::setDescription)); + TextField description = new RequiredTextField<>( + DESCRIPTION, + LambdaModel.of(externalLinkModel, ExternalLink::getDescription, ExternalLink::setDescription) + ); description.add(StringValidator.lengthBetween(0, ExternalLink.MAX_CHARS)); add(description); } @@ -131,9 +151,9 @@ public class ExternalLinkPanel extends GenericPanel { @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); - if(!hasError()) { + if (!hasError()) { tag.append("class", "hidden", " "); } } } -} \ No newline at end of file +} diff --git a/view/src/main/java/se/su/dsv/scipro/user/AbstractAdminUsersPage.java b/view/src/main/java/se/su/dsv/scipro/user/AbstractAdminUsersPage.java index b4ef2899df..c3347829ea 100644 --- a/view/src/main/java/se/su/dsv/scipro/user/AbstractAdminUsersPage.java +++ b/view/src/main/java/se/su/dsv/scipro/user/AbstractAdminUsersPage.java @@ -1,33 +1,35 @@ package se.su.dsv.scipro.user; +import static java.util.Arrays.asList; + +import java.util.List; import se.su.dsv.scipro.admin.pages.AbstractAdminPage; import se.su.dsv.scipro.components.AbstractMenuPanel; import se.su.dsv.scipro.security.auth.Authorization; import se.su.dsv.scipro.security.auth.roles.Roles; -import java.util.List; - -import static java.util.Arrays.asList; - -@Authorization(authorizedRoles = {Roles.ADMIN, Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN, Roles.SYSADMIN }) public class AbstractAdminUsersPage extends AbstractAdminPage { public static final String TABS = "tabs"; public AbstractAdminUsersPage() { - add(new AbstractMenuPanel(TABS, AbstractAdminUsersPage.class, this.getClass()) { - @Override - protected List getItemList() { - return asList( + add( + new AbstractMenuPanel(TABS, AbstractAdminUsersPage.class, this.getClass()) { + @Override + protected List getItemList() { + return asList( new MenuItem("Roles", AdminRolePage.class), new MenuItem("Switch user", AdminSwitchUserPage.class), - new MenuItem("Import", AdminImportUserPage.class)); - } + new MenuItem("Import", AdminImportUserPage.class) + ); + } - @Override - protected MenuType getMenuType() { - return MenuType.HORIZONTAL; + @Override + protected MenuType getMenuType() { + return MenuType.HORIZONTAL; + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/user/AdminImportUserPage.java b/view/src/main/java/se/su/dsv/scipro/user/AdminImportUserPage.java index 20f3c271aa..12d00f0081 100644 --- a/view/src/main/java/se/su/dsv/scipro/user/AdminImportUserPage.java +++ b/view/src/main/java/se/su/dsv/scipro/user/AdminImportUserPage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.user; +import jakarta.inject.Inject; +import java.util.Collections; +import java.util.List; +import java.util.Set; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; @@ -14,15 +18,11 @@ import se.su.dsv.scipro.system.UserImportService; import se.su.dsv.scipro.system.UserImportService.ImportableUser; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.util.Collections; -import java.util.List; -import java.util.Set; - public class AdminImportUserPage extends AbstractAdminUsersPage { @Inject private Set userImportServices; + @Inject private UserService userService; @@ -32,57 +32,70 @@ public class AdminImportUserPage extends AbstractAdminUsersPage { public AdminImportUserPage() { add(new FeedbackPanel("feedback")); - add(new Form("form") { - { - add(new TextField<>("searchTerm", searchTermModel)); - } + add( + new Form("form") { + { + add(new TextField<>("searchTerm", searchTermModel)); + } - @Override - protected void onSubmit() { - List byPersonnummer = userImportServices.stream() + @Override + protected void onSubmit() { + List byPersonnummer = userImportServices + .stream() .map(uis -> uis.search(searchTermModel.getObject())) .flatMap(List::stream) .toList(); - importablePeopleModel.setObject(byPersonnummer); + importablePeopleModel.setObject(byPersonnummer); + } } - }); + ); - add(new ListView<>("importCandidates", importablePeopleModel) { - @Override - protected void populateItem(final ListItem item) { - final IModel importableUser = item.getModel(); - item.add(new Label("firstName", importableUser.map(ImportableUser::getFirstName))); - item.add(new Label("lastName", importableUser.map(ImportableUser::getLastName))); - item.add(new Label("email", importableUser.map(ImportableUser::getEmail))); + add( + new ListView<>("importCandidates", importablePeopleModel) { + @Override + protected void populateItem(final ListItem item) { + final IModel importableUser = item.getModel(); + item.add(new Label("firstName", importableUser.map(ImportableUser::getFirstName))); + item.add(new Label("lastName", importableUser.map(ImportableUser::getLastName))); + item.add(new Label("email", importableUser.map(ImportableUser::getEmail))); - item.add(new Link<>("import", item.getModel()) { - @Override - protected void onConfigure() { - super.onConfigure(); - final ImportableUser importableUser1 = getModelObject(); - final boolean alreadyImported = userService.findByExternalIdentifier(importableUser1.getId()) != null; - if (alreadyImported) { - setEnabled(false); - setBody(new ResourceModel("person.already.imported", "Already imported")); - } else if (importableUser1.getEmail() == null) { - setEnabled(false); - setBody(new ResourceModel("person.lacks.email", "Must specify an e-mail address in Daisy")); - } else { - setEnabled(true); - setBody(new ResourceModel("import.person", "Import")); + item.add( + new Link<>("import", item.getModel()) { + @Override + protected void onConfigure() { + super.onConfigure(); + final ImportableUser importableUser1 = getModelObject(); + final boolean alreadyImported = + userService.findByExternalIdentifier(importableUser1.getId()) != null; + if (alreadyImported) { + setEnabled(false); + setBody(new ResourceModel("person.already.imported", "Already imported")); + } else if (importableUser1.getEmail() == null) { + setEnabled(false); + setBody( + new ResourceModel( + "person.lacks.email", + "Must specify an e-mail address in Daisy" + ) + ); + } else { + setEnabled(true); + setBody(new ResourceModel("import.person", "Import")); + } + } + + @Override + public void onClick() { + ImportableUser toImport = getModelObject(); + for (UserImportService userImportService : userImportServices) { + userImportService.importUser(toImport); + } + getPage().success(getString("person.imported", getModel())); + } } - } - - @Override - public void onClick() { - ImportableUser toImport = getModelObject(); - for (UserImportService userImportService : userImportServices) { - userImportService.importUser(toImport); - } - getPage().success(getString("person.imported", getModel())); - } - }); + ); + } } - }); + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/user/AdminRolePage.java b/view/src/main/java/se/su/dsv/scipro/user/AdminRolePage.java index 8fb5140e04..ecef958adf 100755 --- a/view/src/main/java/se/su/dsv/scipro/user/AdminRolePage.java +++ b/view/src/main/java/se/su/dsv/scipro/user/AdminRolePage.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.user; +import jakarta.inject.Inject; +import java.text.MessageFormat; +import java.time.Duration; +import java.util.*; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -33,12 +37,7 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.UserService; -import jakarta.inject.Inject; -import java.text.MessageFormat; -import java.time.Duration; -import java.util.*; - -@Authorization(authorizedRoles={Roles.ADMIN}) +@Authorization(authorizedRoles = { Roles.ADMIN }) public class AdminRolePage extends AbstractAdminUsersPage { public static final long DURATION = 500L; @@ -84,12 +83,19 @@ public class AdminRolePage extends AbstractAdminUsersPage { } private void addRoleFilter() { - add(new AjaxCheckBoxMultipleChoice<>(ROLE_FILTER, LambdaModel.>of(filter::getRoles, filter::setRoles), Arrays.asList(Roles.values()), new EnumChoiceRenderer<>(this)) { - @Override - public void onUpdate(AjaxRequestTarget target) { - target.add(dataPanel); + add( + new AjaxCheckBoxMultipleChoice<>( + ROLE_FILTER, + LambdaModel.>of(filter::getRoles, filter::setRoles), + Arrays.asList(Roles.values()), + new EnumChoiceRenderer<>(this) + ) { + @Override + public void onUpdate(AjaxRequestTarget target) { + target.add(dataPanel); + } } - }); + ); } private void setupEditUserDialog() { @@ -117,17 +123,9 @@ public class AdminRolePage extends AbstractAdminUsersPage { private List getRoles(final User user) { if (user.hasRole(Roles.SYSADMIN)) { return Arrays.asList(Roles.values()); - } - else if (user.hasRole(Roles.ADMIN)) { - return Arrays.asList( - Roles.AUTHOR, - Roles.SUPERVISOR, - Roles.REVIEWER, - Roles.EXAMINER, - Roles.BETA - ); - } - else { + } else if (user.hasRole(Roles.ADMIN)) { + return Arrays.asList(Roles.AUTHOR, Roles.SUPERVISOR, Roles.REVIEWER, Roles.EXAMINER, Roles.BETA); + } else { return Collections.emptyList(); } } @@ -135,17 +133,32 @@ public class AdminRolePage extends AbstractAdminUsersPage { private AbstractColumn createUserColumn() { return new AbstractColumn<>(Model.of("Name"), "fullName") { @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { User user = rowModel.getObject(); - IModel label = Model.of(MessageFormat.format("{0} {1} <{2}>", user.getFirstName(), user.getLastName(), user.getEmailAddress())); - cellItem.add(new AjaxLinkPanel<>(componentId, rowModel, label) { - @Override - public void onClick(AjaxRequestTarget target, IModel clickedModel) { - editUserModalWindowPlus.setContent(new DisplayUserProfilePanel(editUserModalWindowPlus.getContentId(), clickedModel)); - editUserModalWindowPlus.setTitle(clickedModel.getObject().getFullName()); - editUserModalWindowPlus.show(target); + IModel label = Model.of( + MessageFormat.format( + "{0} {1} <{2}>", + user.getFirstName(), + user.getLastName(), + user.getEmailAddress() + ) + ); + cellItem.add( + new AjaxLinkPanel<>(componentId, rowModel, label) { + @Override + public void onClick(AjaxRequestTarget target, IModel clickedModel) { + editUserModalWindowPlus.setContent( + new DisplayUserProfilePanel(editUserModalWindowPlus.getContentId(), clickedModel) + ); + editUserModalWindowPlus.setTitle(clickedModel.getObject().getFullName()); + editUserModalWindowPlus.show(target); + } } - }); + ); } }; } @@ -153,34 +166,56 @@ public class AdminRolePage extends AbstractAdminUsersPage { private AbstractColumn createRoleColumn(final Roles role) { return new AbstractColumn<>(Model.of(role.name())) { @Override - public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { + public void populateItem( + Item> cellItem, + String componentId, + final IModel rowModel + ) { Fragment fragment = new Fragment(componentId, "roleCheckbox", AdminRolePage.this); //noinspection WicketForgeJavaIdInspection - fragment.add(new AjaxCheckBox("checkbox", Model.of(rowModel.getObject().hasRole(role))) { - @Override - protected void onUpdate(AjaxRequestTarget target) { - User user = rowModel.getObject(); - if (getModelObject()) { - LOGGER.info("{} gave {} the role {}", SciProSession.get().getUser(), user, role); - user.addRole(role); - } else { - LOGGER.info("{} removed the role {} from {}", SciProSession.get().getUser(), role, user); - user.removeRole(role); + fragment.add( + new AjaxCheckBox("checkbox", Model.of(rowModel.getObject().hasRole(role))) { + @Override + protected void onUpdate(AjaxRequestTarget target) { + User user = rowModel.getObject(); + if (getModelObject()) { + LOGGER.info("{} gave {} the role {}", SciProSession.get().getUser(), user, role); + user.addRole(role); + } else { + LOGGER.info( + "{} removed the role {} from {}", + SciProSession.get().getUser(), + role, + user + ); + user.removeRole(role); + } + userService.save(user); } - userService.save(user); - } - @Override - protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) { - super.updateAjaxAttributes(attributes); - String message = getModelObject() ? "Are you sure you want to remove " + role.name() + " from " + rowModel.getObject().getFullName() + "?" - : "Are you sure you want to give the role " + role.name() + " to " + rowModel.getObject().getFullName() + "?"; - String escapedMessage = message.replaceAll("'", "\\\\'"); - AjaxCallListener ajaxCallListener = new AjaxCallListener(); - ajaxCallListener.onPrecondition("if (!confirm('" + escapedMessage + "')) {window.location.reload(); return false;}"); - attributes.getAjaxCallListeners().add(ajaxCallListener); + @Override + protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) { + super.updateAjaxAttributes(attributes); + String message = getModelObject() + ? "Are you sure you want to remove " + + role.name() + + " from " + + rowModel.getObject().getFullName() + + "?" + : "Are you sure you want to give the role " + + role.name() + + " to " + + rowModel.getObject().getFullName() + + "?"; + String escapedMessage = message.replaceAll("'", "\\\\'"); + AjaxCallListener ajaxCallListener = new AjaxCallListener(); + ajaxCallListener.onPrecondition( + "if (!confirm('" + escapedMessage + "')) {window.location.reload(); return false;}" + ); + attributes.getAjaxCallListeners().add(ajaxCallListener); + } } - }); + ); cellItem.add(fragment); } }; diff --git a/view/src/main/java/se/su/dsv/scipro/user/AdminSwitchUserPage.java b/view/src/main/java/se/su/dsv/scipro/user/AdminSwitchUserPage.java index 915e31668a..d3ee4d7a36 100644 --- a/view/src/main/java/se/su/dsv/scipro/user/AdminSwitchUserPage.java +++ b/view/src/main/java/se/su/dsv/scipro/user/AdminSwitchUserPage.java @@ -10,7 +10,7 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; -@Authorization(authorizedRoles = {Roles.SYSADMIN}) +@Authorization(authorizedRoles = { Roles.SYSADMIN }) public class AdminSwitchUserPage extends AbstractAdminUsersPage { public static final String FORM = "form"; @@ -19,21 +19,24 @@ public class AdminSwitchUserPage extends AbstractAdminUsersPage { private IModel userModel = new Model<>(); public AdminSwitchUserPage() { - add(new Form(FORM) { - { - add(new UserAutoComplete(USER, userModel) { - @Override - protected void action(final AjaxRequestTarget target, final User user) { - if (user != null) { - SciProSession.get().setUser(user); - setResponsePage(getApplication().getHomePage()); - } else { - setResponsePage(getPage()); + add( + new Form(FORM) { + { + add( + new UserAutoComplete(USER, userModel) { + @Override + protected void action(final AjaxRequestTarget target, final User user) { + if (user != null) { + SciProSession.get().setUser(user); + setResponsePage(getApplication().getHomePage()); + } else { + setResponsePage(getPage()); + } + } } - } - }); + ); + } } - }); + ); } - } diff --git a/view/src/main/java/se/su/dsv/scipro/user/AdminUsersPage.java b/view/src/main/java/se/su/dsv/scipro/user/AdminUsersPage.java index a229f11589..20bab6c615 100644 --- a/view/src/main/java/se/su/dsv/scipro/user/AdminUsersPage.java +++ b/view/src/main/java/se/su/dsv/scipro/user/AdminUsersPage.java @@ -4,11 +4,11 @@ import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; public class AdminUsersPage extends AbstractAdminUsersPage { + public AdminUsersPage() { if (SciProSession.get().authorizedForRole(Roles.SYSADMIN)) { setResponsePage(AdminSwitchUserPage.class); - } - else { + } else { setResponsePage(AdminRolePage.class); } } diff --git a/view/src/main/java/se/su/dsv/scipro/util/AdditionalExceptionLogger.java b/view/src/main/java/se/su/dsv/scipro/util/AdditionalExceptionLogger.java index 89d4072335..fb60ce250c 100644 --- a/view/src/main/java/se/su/dsv/scipro/util/AdditionalExceptionLogger.java +++ b/view/src/main/java/se/su/dsv/scipro/util/AdditionalExceptionLogger.java @@ -47,27 +47,39 @@ public class AdditionalExceptionLogger implements IRequestCycleListener { private void logRequestParameters(Request request) { IRequestParameters requestParameters = request.getRequestParameters(); for (String parameterName : requestParameters.getParameterNames()) { - if (!parameterName.contains("password")){ - LOGGER.info("Request parameter: {}={}", parameterName, requestParameters.getParameterValues(parameterName)); + if (!parameterName.contains("password")) { + LOGGER.info( + "Request parameter: {}={}", + parameterName, + requestParameters.getParameterValues(parameterName) + ); } } } private void logRequestUrl(Request request) { - LOGGER.info("Request url: {} {}", ((ServletWebRequest) request).getContainerRequest().getMethod(), request.getUrl()); + LOGGER.info( + "Request url: {} {}", + ((ServletWebRequest) request).getContainerRequest().getMethod(), + request.getUrl() + ); } private void logCurrentUser() { User user = SciProSession.get().getUser(); if (user != null) { LOGGER.info("Current user: {} ({})", user, user.getId()); - } - else { + } else { LOGGER.info("Current user: not logged in"); } } private boolean isWicketHandledException(Exception ex) { - return ex instanceof StalePageException || ex instanceof PageExpiredException || ex instanceof AuthorizationException || ex instanceof ResponseIOException; + return ( + ex instanceof StalePageException || + ex instanceof PageExpiredException || + ex instanceof AuthorizationException || + ex instanceof ResponseIOException + ); } } diff --git a/view/src/main/java/se/su/dsv/scipro/util/Ajax.java b/view/src/main/java/se/su/dsv/scipro/util/Ajax.java index 5db135a128..797e8f1583 100644 --- a/view/src/main/java/se/su/dsv/scipro/util/Ajax.java +++ b/view/src/main/java/se/su/dsv/scipro/util/Ajax.java @@ -4,6 +4,7 @@ import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; public class Ajax { + private Ajax() {} /** @@ -24,10 +25,12 @@ public class Ajax { */ public static void hide(Component component, AjaxRequestTarget target) { if (component.isVisible()) { - target.prependJavaScript(""" - var continueCall = Wicket.Ajax.suspendCall(); - $('#%s').slideUp(function() { continueCall() }) - """.formatted(component.getMarkupId())); + target.prependJavaScript( + """ + var continueCall = Wicket.Ajax.suspendCall(); + $('#%s').slideUp(function() { continueCall() }) + """.formatted(component.getMarkupId()) + ); } component.setVisible(false); target.add(component); diff --git a/view/src/main/java/se/su/dsv/scipro/util/CopyTextPanel.java b/view/src/main/java/se/su/dsv/scipro/util/CopyTextPanel.java index 761266e631..3768398713 100644 --- a/view/src/main/java/se/su/dsv/scipro/util/CopyTextPanel.java +++ b/view/src/main/java/se/su/dsv/scipro/util/CopyTextPanel.java @@ -5,6 +5,7 @@ import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; public class CopyTextPanel extends GenericPanel { + public CopyTextPanel(String id, IModel model) { super(id, model); add(new TextArea<>("copyMe", model)); diff --git a/view/src/main/java/se/su/dsv/scipro/util/JavascriptEventConfirmation.java b/view/src/main/java/se/su/dsv/scipro/util/JavascriptEventConfirmation.java index 86be385fa9..756c08ab52 100755 --- a/view/src/main/java/se/su/dsv/scipro/util/JavascriptEventConfirmation.java +++ b/view/src/main/java/se/su/dsv/scipro/util/JavascriptEventConfirmation.java @@ -39,15 +39,17 @@ public class JavascriptEventConfirmation extends Behavior { final String confirmationMsg = getConfirmationMsg(component); if (confirmationMsg == null) return; - String confirmScript = "var conf = confirm('" + confirmationMsg.replaceAll("'", "\\\\'") + "'); " + - "if (!conf) event.preventDefault();"; + String confirmScript = + "var conf = confirm('" + + confirmationMsg.replaceAll("'", "\\\\'") + + "'); " + + "if (!conf) event.preventDefault();"; response.render(OnEventHeaderItem.forComponent(component, event, confirmScript)); } private String getConfirmationMsg(Component component) { IModel model = msgModel; - if (model instanceof IComponentAssignedModel icam) - { + if (model instanceof IComponentAssignedModel icam) { model = icam.wrapOnAssignment(component); } return model.getObject(); diff --git a/view/src/main/java/se/su/dsv/scipro/util/PageParameterKeys.java b/view/src/main/java/se/su/dsv/scipro/util/PageParameterKeys.java index 766ca4b5cc..25a907b883 100644 --- a/view/src/main/java/se/su/dsv/scipro/util/PageParameterKeys.java +++ b/view/src/main/java/se/su/dsv/scipro/util/PageParameterKeys.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.util; import com.google.common.collect.ImmutableMap; +import java.util.Map; import se.su.dsv.scipro.activityplan.Activity; import se.su.dsv.scipro.activityplan.ActivityPlan; import se.su.dsv.scipro.activityplan.ActivityPlanTemplate; @@ -18,8 +19,6 @@ import se.su.dsv.scipro.peer.PeerReview; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.Map; - public final class PageParameterKeys { /** @@ -31,21 +30,21 @@ public final class PageParameterKeys { } public static final Map MAP = ImmutableMap.builder() - .put(ActivityPlanTemplate.class, "stid") - .put(Activity.class, "acid") - .put(ActivityPlan.class, "actp") - .put(ApplicationPeriod.class, "apid") - .put(Checklist.class, "clid") - .put(ChecklistTemplate.class, "cltid") - .put(FinalSeminar.class, "fsid") - .put(FinalSeminarOpposition.class, "oid") - .put(ForumPost.class, "fpid") - .put(Idea.class, "ideaid") - .put(PeerRequest.class, "requestid") - .put(PeerReview.class, "reviewid") - .put(Project.class, "pid") - .put(User.class, "uid") - .put(Group.class, "gid") - .put(ForumThread.class, "tid") - .build(); -} \ No newline at end of file + .put(ActivityPlanTemplate.class, "stid") + .put(Activity.class, "acid") + .put(ActivityPlan.class, "actp") + .put(ApplicationPeriod.class, "apid") + .put(Checklist.class, "clid") + .put(ChecklistTemplate.class, "cltid") + .put(FinalSeminar.class, "fsid") + .put(FinalSeminarOpposition.class, "oid") + .put(ForumPost.class, "fpid") + .put(Idea.class, "ideaid") + .put(PeerRequest.class, "requestid") + .put(PeerReview.class, "reviewid") + .put(Project.class, "pid") + .put(User.class, "uid") + .put(Group.class, "gid") + .put(ForumThread.class, "tid") + .build(); +} diff --git a/view/src/test/java/se/su/dsv/scipro/HomePageTest.java b/view/src/test/java/se/su/dsv/scipro/HomePageTest.java index 3290e55fc9..61da46fdf7 100644 --- a/view/src/test/java/se/su/dsv/scipro/HomePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/HomePageTest.java @@ -3,6 +3,7 @@ package se.su.dsv.scipro; import org.apache.wicket.Page; public class HomePageTest extends PageTest { + @Override protected Class getPage() { return getHomePage(); diff --git a/view/src/test/java/se/su/dsv/scipro/SciProSessionTest.java b/view/src/test/java/se/su/dsv/scipro/SciProSessionTest.java index 386ab5b992..ef5e074443 100755 --- a/view/src/test/java/se/su/dsv/scipro/SciProSessionTest.java +++ b/view/src/test/java/se/su/dsv/scipro/SciProSessionTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import org.apache.wicket.request.Request; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.session.SciProSession; @@ -7,10 +10,6 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.SystemModule; import se.su.dsv.scipro.system.User; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - public class SciProSessionTest extends SciProSession { Collection currentRoles = new HashSet<>(); @@ -58,4 +57,4 @@ public class SciProSessionTest extends SciProSession { public Set getSystemModules() { return currentSystemModules; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/SciProTest.java b/view/src/test/java/se/su/dsv/scipro/SciProTest.java index 2b469c39ec..ceec7ebadb 100755 --- a/view/src/test/java/se/su/dsv/scipro/SciProTest.java +++ b/view/src/test/java/se/su/dsv/scipro/SciProTest.java @@ -1,6 +1,14 @@ package se.su.dsv.scipro; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import java.lang.reflect.Field; +import java.time.Clock; +import java.util.*; import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.Session; @@ -132,22 +140,15 @@ import se.su.dsv.scipro.thesislink.ExternalLinkService; import se.su.dsv.scipro.workerthreads.Scheduler; import se.su.dsv.scipro.workerthreads.WorkerDataService; -import java.lang.reflect.Field; -import java.time.Clock; -import java.util.*; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public abstract class SciProTest { @Mock protected EventBus eventBus; + @Mock protected ActivityPlanService activityPlanService; + @Mock protected SurveyService surveyService; @@ -156,203 +157,301 @@ public abstract class SciProTest { */ @Mock protected ProjectFinalSeminarStatisticsService projectFinalSeminarStatisticsService; + @Mock protected NoteService noteService; + @Mock protected GroupService groupService; + @Mock protected ReviewerDeadlineFollowupService reviewerDeadlineFollowupService; + @Mock protected ProgramService programService; + @Mock protected ReviewerDeadlineSettingsService reviewerDeadlineSettingsService; + @Mock protected AuthenticationService authenticationService; + @Mock protected ActivityService activityService; + @Mock protected ApplicationPeriodService applicationPeriodService; + @Mock protected ChecklistService checklistService; + @Mock protected ChecklistTemplateService checklistTemplateService; + @Mock protected CommentService commentService; + @Mock protected CommentThreadService commentThreadService; + @Mock protected DateService dateService; + @Mock protected DaysService daysService; + @Mock protected FileService fileDescriptionService; + @Mock protected FinalSeminarService finalSeminarService; + @Mock protected FinalThesisService finalThesisService; + @Mock protected BasicForumService basicForumService; + @Mock protected ProjectForumService projectForumService; + @Mock protected GroupForumService groupForumService; + @Mock protected GeneralSystemSettingsService generalSystemSettingsService; + @Mock protected GenericService genericService; + @Mock protected KeywordService keywordService; + @Mock protected IdeaService ideaService; + @Mock protected MatchService matchService; + @Mock protected NotificationService notificationService; + @Mock protected PeerRequestService peerRequestService; + @Mock protected PeerReviewService peerReviewService; + @Mock protected ProjectTypeService projectTypeService; + @Mock protected ProjectPartnerService projectPartnerService; + @Mock protected ProjectService projectService; + @Mock protected ResearchAreaService researchAreaService; + @Mock protected ActivityPlanTemplateService activityPlanTemplateService; + @Mock protected SupervisorService supervisorService; + @Mock protected UnitService unitService; + @Mock protected UserNameService userNameService; + @Mock protected UserService userService; + @Mock protected MyReviewService myReviewService; + @Mock protected UserProfileService userProfileService; + @Mock protected NonWorkDayPeriodService nonWorkDayPeriodService; + @Mock protected MileStoneService mileStoneService; + @Mock protected MilestoneStatisticsService milestoneStatisticsService; + @Mock protected MilestoneActivityTemplateService milestoneActivityTemplateService; + @Mock protected MilestonePhaseTemplateService mileStonePhaseTemplateService; + @Mock protected FinalSeminarSettingsService finalSeminarSettingsService; + @Mock protected FinalSeminarRespondentService finalSeminarRespondentService; + @Mock protected FinalSeminarOppositionService finalSeminarOppositionService; + @Mock protected FinalSeminarActiveParticipationService finalSeminarActiveParticipationService; + @Mock protected WorkerDataService workerDataService; + @Mock protected GradingReportService gradingReportService; + @Mock protected OppositionReportService oppositionReportService; + @Mock protected MailEventService mailEventService; + /** * Other */ @Mock protected NotificationController notificationController; + @Mock protected FinalSeminarUploadController finalSeminarUploadController; + @Mock protected FinalSeminarOppositionRepo finalSeminarOppositionRepo; + @Mock protected PlagiarismControl plagiarismControl; + @Mock protected TargetService targetService; + @Mock protected IdeaFacade ideaFacade; + @Mock protected PeerPortal peerPortal; + @Mock protected ActivityPlanFacade activityPlanFacade; + @Mock protected GroupFacade groupFacade; + @Mock protected ChecklistQuestionRepo checklistQuestionRepo; + @Mock protected ChecklistCategoryRepo checklistCategoryRepo; + @Mock protected ExternalLinkService externalLinkService; + @Mock protected ApplicationPeriodProjectTypeService applicationPeriodProjectTypeService; + @Mock protected PasswordRepo passwordRepo; + @Mock protected PasswordService passwordService; + @Mock protected PerformReviewService performReviewService; + @Mock protected ChecklistAnswerService checklistAnswerService; + @Mock protected CurrentUser currentUser; + @Mock private Scheduler scheduler; + @Mock protected ReviewerInteractionService reviewerInteractionService; + @Mock protected ReviewerApprovalService reviewerApprovalService; + @Mock protected FinalSeminarApprovalService finalSeminarApprovalService; + @Mock protected ReviewerDecisionService reviewerDecisionService; + @Mock protected RoughDraftApprovalService roughDraftApprovalService; + @Mock protected ExternalResourceService externalResourceService; + @Mock protected FooterLinkService footerLinkService; + @Mock protected FooterAddressRepo footerAddressRepo; + @Mock protected ApplicationPeriodFacade applicationPeriodFacade; + @Mock protected FirstMeetingRepository firstMeetingRepository; + @Mock protected ProjectPeopleStatisticsService projectPeopleStatisticsService; + @Mock protected ProjectFileService projectFileService; + @Mock protected UrkundService urkundService; + @Mock protected DaisyAPI daisyAPI; + @Mock protected PreliminaryMatchService preliminaryMatchService; + @Mock protected OAuthService oAuthService; + @Mock protected GradeCalculatorService gradeCalculatorService; + @Mock protected UserImportService userImportService; + @Mock protected Reporter reporter; + @Mock protected ReflectionService reflectionService; + @Mock protected PublishingConsentService publishingConsentService; + @Mock protected UserSearchService userSearchService; + @Mock protected GradingService gradingService; + @Mock protected PublicationMetadataService publicationMetadataService; + @Mock protected ExaminerTimelineService examinerTimelineService; + @Mock protected NationalSubjectCategoryService nationalSubjectCategoryService; + @Mock protected ProjectNoteService projectNoteService; @@ -367,14 +466,14 @@ public abstract class SciProTest { currentProfile.setCurrentProfileString("TEST"); SciProApplication application = new SciProApplication(currentProfile) { - @Override public Session newSession(Request request, Response response) { return new SciProSessionTest(request); } }; - application.getComponentInstantiationListeners().add( - new SpringComponentInjector(application, applicationContext)); + application + .getComponentInstantiationListeners() + .add(new SpringComponentInjector(application, applicationContext)); tester = new WicketTester(application, System.getProperty("user.dir") + "/src/main/webapp"); setLoggedIn(true); @@ -384,15 +483,19 @@ public abstract class SciProTest { lenient().when(daisyAPI.getPhoto(anyInt(), anyInt(), anyBoolean())).thenReturn(new PhotoResult.Missing()); lenient().when(oAuthService.authorizeUrl(anyString(), anySet())).thenReturn(""); - lenient().when(gradingReportService.getSupervisorGradingReport(any(), any())).thenReturn(mock(SupervisorGradingReport.class)); - lenient().when(publicationMetadataService.getByProject(any())) - .thenAnswer(answer -> { - PublicationMetadata publicationMetadata = new PublicationMetadata(); - publicationMetadata.setProject(answer.getArgument(0)); - return publicationMetadata; - }); - lenient().when(publishingConsentService.getPublishingConsent(any(), any())) - .thenReturn(new PublishingConsentService.PublishingConsent(null, List.of())); + lenient() + .when(gradingReportService.getSupervisorGradingReport(any(), any())) + .thenReturn(mock(SupervisorGradingReport.class)); + lenient() + .when(publicationMetadataService.getByProject(any())) + .thenAnswer(answer -> { + PublicationMetadata publicationMetadata = new PublicationMetadata(); + publicationMetadata.setProject(answer.getArgument(0)); + return publicationMetadata; + }); + lenient() + .when(publishingConsentService.getPublishingConsent(any(), any())) + .thenReturn(new PublishingConsentService.PublishingConsent(null, List.of())); } @BeforeEach @@ -404,7 +507,9 @@ public abstract class SciProTest { @BeforeEach public void createGeneralSystemSettings() { - lenient().when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(new GeneralSystemSettings()); + lenient() + .when(generalSystemSettingsService.getGeneralSystemSettingsInstance()) + .thenReturn(new GeneralSystemSettings()); } @BeforeEach @@ -412,7 +517,6 @@ public abstract class SciProTest { lenient().when(userProfileService.findByUser(any(User.class))).thenReturn(new UserProfile()); } - public Class getHomePage() { Collection roles = ((SciProSessionTest) tester.getSession()).currentRoles; if (roles.contains(Roles.ADMIN)) return AdminStartPage.class; @@ -470,6 +574,7 @@ public abstract class SciProTest { } private class MockModule extends ApplicationContextMock { + private final Class clazz; public MockModule(Class clazz) { diff --git a/view/src/test/java/se/su/dsv/scipro/SciProUtilitiesTest.java b/view/src/test/java/se/su/dsv/scipro/SciProUtilitiesTest.java index 945e9b4369..bfc6b91dd2 100644 --- a/view/src/test/java/se/su/dsv/scipro/SciProUtilitiesTest.java +++ b/view/src/test/java/se/su/dsv/scipro/SciProUtilitiesTest.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.reusable.SciProUtilities; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Calendar; import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.reusable.SciProUtilities; /** * Created by: fred-fri diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanPanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanPanelTest.java index 455f4d6ed2..441859f4c4 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanPanelTest.java @@ -1,24 +1,23 @@ package se.su.dsv.scipro.activityplan; +import java.time.LocalDate; +import java.util.Arrays; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.checklist.Checklist; import se.su.dsv.scipro.checklists.ProjectViewChecklistPage; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Arrays; - public class ActivityPlanPanelTest extends SciProTest { private Project project; @@ -26,7 +25,12 @@ public class ActivityPlanPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - project = Project.builder().title("My project").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).headSupervisor(new User()).build(); + project = Project.builder() + .title("My project") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(new User()) + .build(); project.setId(20934L); } @@ -97,7 +101,7 @@ public class ActivityPlanPanelTest extends SciProTest { startPanel(); PageParameters pageParameters = new PageParameters(); pageParameters.set(PageParameterKeys.MAP.get(Checklist.class), checklist.getId()); - tester.assertBookmarkablePageLink(checklistLink(), ProjectViewChecklistPage.class, pageParameters ); + tester.assertBookmarkablePageLink(checklistLink(), ProjectViewChecklistPage.class, pageParameters); } private String checklistLink() { @@ -113,10 +117,16 @@ public class ActivityPlanPanelTest extends SciProTest { } private void mockExistingEvents(Activity... events) { - Mockito.when(activityPlanFacade.findEventsByProject(ArgumentMatchers.eq(project), ArgumentMatchers.any(Pageable.class))) - .thenReturn(Arrays.asList(events)); - Mockito.when(activityPlanFacade.countEventsByProject(ArgumentMatchers.eq(project), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn((long) events.length); + Mockito.when( + activityPlanFacade.findEventsByProject(ArgumentMatchers.eq(project), ArgumentMatchers.any(Pageable.class)) + ).thenReturn(Arrays.asList(events)); + Mockito.when( + activityPlanFacade.countEventsByProject( + ArgumentMatchers.eq(project), + ArgumentMatchers.any(), + ArgumentMatchers.any() + ) + ).thenReturn((long) events.length); } private Activity createActivity() { diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanelTest.java index e1fcf04e47..e0f2843553 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/ActivityPlanTemplateDataPanelTest.java @@ -13,15 +13,17 @@ public class ActivityPlanTemplateDataPanelTest extends SciProTest { } private void startPanel() { - tester.startComponentInPage(new ActivityPlanTemplateDataPanel("id") { - @Override - public void onNewClick() {} + tester.startComponentInPage( + new ActivityPlanTemplateDataPanel("id") { + @Override + public void onNewClick() {} - @Override - public void onTitleClick(IModel clicked, AjaxRequestTarget target) {} + @Override + public void onTitleClick(IModel clicked, AjaxRequestTarget target) {} - @Override - public void onEditClick(IModel clicked) {} - }); + @Override + public void onEditClick(IModel clicked) {} + } + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanelTest.java index c979026b10..66d8bf074b 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/AddActivitiesFromTemplatePanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.activityplan; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -8,14 +15,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AddActivitiesFromTemplatePanelTest extends SciProTest { private List templates; @@ -35,21 +34,26 @@ public class AddActivitiesFromTemplatePanelTest extends SciProTest { templates = Arrays.asList(template1, template2); project = new Project(); - when(activityPlanTemplateService.findAll(isA(ActivityPlanTemplateService.Filter.class))) - .thenReturn(templates); + when(activityPlanTemplateService.findAll(isA(ActivityPlanTemplateService.Filter.class))).thenReturn(templates); tester.startComponentInPage(new AddActivitiesFromTemplatePanel("id", Model.of(project))); } @Test public void lists_all_templates() { - tester.assertModelValue(path("id", "content", "stupidContainerSinceWicketCantRefreshListViews", "templates"), templates); + tester.assertModelValue( + path("id", "content", "stupidContainerSinceWicketCantRefreshListViews", "templates"), + templates + ); } @Test public void add_activities_from_template() { - tester.clickLink(path("id", "content", "stupidContainerSinceWicketCantRefreshListViews", "templates", 0, "title"), true); + tester.clickLink( + path("id", "content", "stupidContainerSinceWicketCantRefreshListViews", "templates", 0, "title"), + true + ); FormTester formTester = tester.newFormTester(path("id", "content", "form")); formTester.submit(); verify(activityPlanFacade).addActivitiesFromTemplate(eq(project), eq(templates.get(0)), any(Date.class)); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPageTest.java index 36fc22103b..8a6163af95 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminActivityPlanTemplatesPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminActivityPlanTemplatesPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminActivityPlanTemplatesPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanelTest.java index 1d420b7548..a61258a92d 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import static se.su.dsv.scipro.activityplan.AdminEditActivityPanel.*; + +import java.util.Collections; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -10,11 +13,7 @@ import org.mockito.Mockito; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.checklist.ChecklistTemplate; -import java.util.Collections; - -import static se.su.dsv.scipro.activityplan.AdminEditActivityPanel.*; - -public class AdminEditActivityPanelTest extends SciProTest{ +public class AdminEditActivityPanelTest extends SciProTest { private AdminEditActivityPanel panel; @@ -54,10 +53,11 @@ public class AdminEditActivityPanelTest extends SciProTest{ } private void startPanel() { - panel = tester.startComponentInPage(new AdminEditActivityPanel("panel", new Model<>(new ActivityTemplate())) { - @Override - protected void onSubmit(final AjaxRequestTarget target, final IModel activity) { + panel = tester.startComponentInPage( + new AdminEditActivityPanel("panel", new Model<>(new ActivityTemplate())) { + @Override + protected void onSubmit(final AjaxRequestTarget target, final IModel activity) {} } - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePageTest.java index 2b8f5cd3a7..c50ffe37d0 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/AdminEditActivityTemplatePageTest.java @@ -13,10 +13,14 @@ public class AdminEditActivityTemplatePageTest extends SciProTest { private void mockExistingTemplate() { ActivityPlanTemplate activityPlanTemplate = new ActivityPlanTemplate(); activityPlanTemplate.setId(1L); - activityPlanTemplate.setCreator(new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create()); + activityPlanTemplate.setCreator( + new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create() + ); activityPlanTemplate.setSysAdminTemplate(true); activityPlanTemplate.setDescription("naizz"); - Mockito.when(activityPlanTemplateService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(activityPlanTemplate); + Mockito.when(activityPlanTemplateService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn( + activityPlanTemplate + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityPanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityPanelTest.java index f9e2ff4e8b..73fe8330c1 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.activityplan; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; + +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -20,20 +26,12 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; - public class EditActivityPanelTest extends SciProTest { private Project project; @BeforeEach public void setUp() throws Exception { - setModules(ProjectModule.ACTIVITY_PLAN); final User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); @@ -43,11 +41,11 @@ public class EditActivityPanelTest extends SciProTest { final User supervisor = new UserBuilder().setFirstName("Super").setLastName("Supersson").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); final ActivityPlan activityPlan = new ActivityPlan(); @@ -64,7 +62,9 @@ public class EditActivityPanelTest extends SciProTest { checklistTemplate.setQuestions(new ArrayList<>(Arrays.asList("who is your daddy", "and what does he do"))); checklistTemplate.setTemplateNumber(0); - Mockito.when(checklistTemplateService.findByProject(isA(Project.class))).thenReturn(new ArrayList<>(Collections.singletonList(checklistTemplate))); + Mockito.when(checklistTemplateService.findByProject(isA(Project.class))).thenReturn( + new ArrayList<>(Collections.singletonList(checklistTemplate)) + ); startPanel(); } @@ -93,13 +93,14 @@ public class EditActivityPanelTest extends SciProTest { formTester.submit(); tester.assertNoErrorMessage(); verify(activityPlanFacade).saveActivity(isA(Activity.class)); - verify(notificationController).notifyProject(isA(Project.class), isA(ProjectEvent.Event.class), isA(NotificationSource.class)); + verify(notificationController).notifyProject( + isA(Project.class), + isA(ProjectEvent.Event.class), + isA(NotificationSource.class) + ); } - - private void startPanel() { tester.startComponentInPage(new EditActivityPanel("panel", Model.of(project), Model.of(new Activity()))); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanelTest.java index ed747653ac..ab225ba3ca 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/EditActivityTemplatePanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import static se.su.dsv.scipro.activityplan.EditActivityTemplatePanel.*; + +import java.util.Arrays; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.Form; @@ -15,10 +18,6 @@ import org.mockito.Mockito; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.test.UserBuilder; -import java.util.Arrays; - -import static se.su.dsv.scipro.activityplan.EditActivityTemplatePanel.*; - public class EditActivityTemplatePanelTest extends SciProTest { private EditActivityTemplatePanel panel; @@ -33,7 +32,9 @@ public class EditActivityTemplatePanelTest extends SciProTest { public void setUp() throws Exception { activityPlanTemplate = new ActivityPlanTemplate(); activityPlanTemplate.setId(1L); - activityPlanTemplate.setCreator(new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create()); + activityPlanTemplate.setCreator( + new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create() + ); activityPlanTemplate.setSysAdminTemplate(true); activityPlanTemplate.setDescription("naizz"); @@ -115,7 +116,9 @@ public class EditActivityTemplatePanelTest extends SciProTest { @Test public void saves() { - Mockito.when(activityPlanTemplateService.save(ArgumentMatchers.isA(ActivityPlanTemplate.class))).thenReturn(activityPlanTemplate); + Mockito.when(activityPlanTemplateService.save(ArgumentMatchers.isA(ActivityPlanTemplate.class))).thenReturn( + activityPlanTemplate + ); startPanel(); FormTester formTester = tester.newFormTester(path(panel.getId(), FORM)); formTester.setValue(TITLE_FIELD, "a nice title"); diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanelTest.java index cee5c07718..e05990bf93 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/PreviewActivityPlanTemplatePanelTest.java @@ -1,18 +1,17 @@ package se.su.dsv.scipro.activityplan; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; + public class PreviewActivityPlanTemplatePanelTest extends SciProTest { private List activityPlanTemplate; @@ -43,6 +42,8 @@ public class PreviewActivityPlanTemplatePanelTest extends SciProTest { } private PreviewActivityPlanTemplatePanel startPanel() { - return tester.startComponentInPage(new PreviewActivityPlanTemplatePanel("id", Model.ofList(activityPlanTemplate))); + return tester.startComponentInPage( + new PreviewActivityPlanTemplatePanel("id", Model.ofList(activityPlanTemplate)) + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPageTest.java index add93322e4..5a60767909 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectActivityPlanPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.activityplan; +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,8 +15,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - public class ProjectActivityPlanPageTest extends PageTest { @BeforeEach @@ -24,11 +23,11 @@ public class ProjectActivityPlanPageTest extends PageTest { setLoggedInAs(user); User supervisor = new UserBuilder().setFirstName("Super").setLastName("Supersson").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); Mockito.when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPageTest.java index de66b9e97b..c139225309 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/ProjectEditActivityPageTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.activityplan; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; +import java.util.TreeSet; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.Test; @@ -16,21 +23,12 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; -import java.util.HashSet; -import java.util.TreeSet; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class ProjectEditActivityPageTest extends SciProTest { private User supervisor; @Test public void notParticipant() { - User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); user.setRoles(new HashSet<>(Collections.singletonList(Roles.AUTHOR))); setLoggedInAs(user); @@ -41,22 +39,20 @@ public class ProjectEditActivityPageTest extends SciProTest { supervisor = new UserBuilder().setFirstName("Super").setLastName("Supersson").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); when(projectService.isPartOfProject(project, user)).thenReturn(false); startWithParametersAndExpect(AccessDeniedPage.class); - } @Test public void participant() { - User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); user.setRoles(new HashSet<>(Collections.singletonList(Roles.AUTHOR))); setLoggedInAs(user); @@ -69,12 +65,12 @@ public class ProjectEditActivityPageTest extends SciProTest { TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(user)); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .projectParticipants(projectParticipants) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); when(projectService.isPartOfProject(project, user)).thenReturn(true); @@ -87,7 +83,6 @@ public class ProjectEditActivityPageTest extends SciProTest { when(activityService.findOne(isA(Long.class))).thenReturn(activity); startWithParametersAndExpect(ProjectEditActivityPage.class); - } private void startWithParametersAndExpect(Class pageClass) { @@ -96,7 +91,7 @@ public class ProjectEditActivityPageTest extends SciProTest { } public Roles[] getRoles() { - return new Roles[]{Roles.AUTHOR}; + return new Roles[] { Roles.AUTHOR }; } protected PageParameters getPageParameters() { @@ -105,4 +100,4 @@ public class ProjectEditActivityPageTest extends SciProTest { pageParameters.add(PageParameterKeys.MAP.get(Activity.class), 1); return pageParameters; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanelTest.java index 8102cdccd1..5c20a1539c 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/SaveAsTemplatePanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.activityplan; +import static org.mockito.Mockito.*; + import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -7,8 +9,6 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.User; -import static org.mockito.Mockito.*; - public class SaveAsTemplatePanelTest extends SciProTest { private ActivityPlan activityPlan; @@ -45,4 +45,4 @@ public class SaveAsTemplatePanelTest extends SciProTest { verifyNoMoreInteractions(activityPlanFacade); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPageTest.java index 24fb79b429..ec52cbee69 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.supervisor.pages.SupervisorPageTest; public class SupervisorActivityPlanPageTest extends SupervisorPageTest { + @Override protected Class getPage() { return SupervisorActivityPlanPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPageTest.java index 7663455afc..84e1f90405 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorActivityPlanTemplatesPageTest.java @@ -5,10 +5,12 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class SupervisorActivityPlanTemplatesPageTest extends SciProTest { + @Test public void renders() throws Exception { PageParameters pageParameters = new PageParameters(); - SupervisorActivityPlanTemplatesPage supervisorActivityPlanTemplatesPage = new SupervisorActivityPlanTemplatesPage(pageParameters); + SupervisorActivityPlanTemplatesPage supervisorActivityPlanTemplatesPage = + new SupervisorActivityPlanTemplatesPage(pageParameters); tester.startPage(supervisorActivityPlanTemplatesPage); } diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPageTest.java index 33b3e4ab09..09f382d1ae 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.activityplan; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.Test; @@ -16,18 +22,10 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; -import java.util.HashSet; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorEditActivityPageTest extends SciProTest { @Test public void notParticipant() { - User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); user.setRoles(new HashSet<>(Collections.singletonList(Roles.SUPERVISOR))); setLoggedInAs(user); @@ -37,10 +35,10 @@ public class SupervisorEditActivityPageTest extends SciProTest { setModules(ProjectModule.ACTIVITY_PLAN); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); when(projectService.hasSupervisingRole(project, user)).thenReturn(false); @@ -49,12 +47,10 @@ public class SupervisorEditActivityPageTest extends SciProTest { activityPlan.setProject(project); startWithParametersAndExpect(AccessDeniedPage.class); - } @Test public void participant() { - User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); user.setRoles(new HashSet<>(Collections.singletonList(Roles.SUPERVISOR))); setLoggedInAs(user); @@ -64,11 +60,11 @@ public class SupervisorEditActivityPageTest extends SciProTest { setModules(ProjectModule.ACTIVITY_PLAN); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); when(projectService.hasSupervisingRole(project, user)).thenReturn(true); @@ -81,7 +77,6 @@ public class SupervisorEditActivityPageTest extends SciProTest { when(activityService.findOne(isA(Long.class))).thenReturn(activity); startWithParametersAndExpect(SupervisorEditActivityPage.class); - } private void startWithParametersAndExpect(Class pageClass) { @@ -90,7 +85,7 @@ public class SupervisorEditActivityPageTest extends SciProTest { } public Roles[] getRoles() { - return new Roles[]{Roles.SUPERVISOR}; + return new Roles[] { Roles.SUPERVISOR }; } protected PageParameters getPageParameters() { @@ -99,5 +94,4 @@ public class SupervisorEditActivityPageTest extends SciProTest { pageParameters.add(PageParameterKeys.MAP.get(Activity.class), 1); return pageParameters; } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePageTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePageTest.java index 477d3feef6..22955c23c1 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/SupervisorEditActivityTemplatePageTest.java @@ -13,10 +13,14 @@ public class SupervisorEditActivityTemplatePageTest extends SciProTest { private void mockExistingTemplate() { ActivityPlanTemplate activityPlanTemplate = new ActivityPlanTemplate(); activityPlanTemplate.setId(1L); - activityPlanTemplate.setCreator(new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create()); + activityPlanTemplate.setCreator( + new UserBuilder().setId(1L).setEmail("e@mail.com").setFirstName("Nisse").setLastName("Karlsson").create() + ); activityPlanTemplate.setSysAdminTemplate(false); activityPlanTemplate.setDescription("naizz"); - Mockito.when(activityPlanTemplateService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(activityPlanTemplate); + Mockito.when(activityPlanTemplateService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn( + activityPlanTemplate + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanelTest.java b/view/src/test/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanelTest.java index 6af79a01c0..d04957f30d 100644 --- a/view/src/test/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/activityplan/UpcomingActivitiesPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.activityplan; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Date; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; @@ -12,39 +15,35 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Date; - public class UpcomingActivitiesPanelTest extends SciProTest { private UpcomingActivitiesPanel panel; - private static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); + private static final ProjectType SOME_PROJECT_TYPE = new ProjectType( + DegreeType.BACHELOR, + "Some project type", + "Some description" + ); private Project project; - @BeforeEach public void setUp() throws Exception { - User user = new UserBuilder() - .setFirstName("Some first name") - .setLastName("Some last name") - .create(); + User user = new UserBuilder().setFirstName("Some first name").setLastName("Some last name").create(); user.setId(1L); project = Project.builder() - .title("Some title") - .projectType(SOME_PROJECT_TYPE) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("Some title") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); project.setId(1L); } @@ -76,66 +75,87 @@ public class UpcomingActivitiesPanelTest extends SciProTest { @Test public void testDate() { startPanel(true, true); - panel.listView.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(UpcomingActivitiesPanel.DATE)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.listView.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component.get(path(UpcomingActivitiesPanel.DATE)).isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test public void testEmployeeLink() { startPanel(false, true); - panel.listView.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(UpcomingActivitiesPanel.EMPLOYEE_LINK)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.listView.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component + .get(path(UpcomingActivitiesPanel.EMPLOYEE_LINK)) + .isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test public void testEmployeeLabel() { startPanel(false, true); - panel.listView.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(UpcomingActivitiesPanel.EMPLOYEE_LINK, UpcomingActivitiesPanel.EMPLOYEE_LABEL)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.listView.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component + .get(path(UpcomingActivitiesPanel.EMPLOYEE_LINK, UpcomingActivitiesPanel.EMPLOYEE_LABEL)) + .isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test public void testAuthorLink() { startPanel(true, true); - panel.listView.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(UpcomingActivitiesPanel.AUTHOR_LINK)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.listView.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component.get(path(UpcomingActivitiesPanel.AUTHOR_LINK)).isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test public void testAuthorLabel() { startPanel(true, true); - panel.listView.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(UpcomingActivitiesPanel.AUTHOR_LINK, UpcomingActivitiesPanel.AUTHOR_LABEL)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.listView.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component + .get(path(UpcomingActivitiesPanel.AUTHOR_LINK, UpcomingActivitiesPanel.AUTHOR_LABEL)) + .isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } private void startPanel(final boolean isAuthor, boolean addEvents) { @@ -148,13 +168,22 @@ public class UpcomingActivitiesPanelTest extends SciProTest { events.add(pse); } - Mockito.when(activityPlanFacade.findEventsByProject(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(Date.class), ArgumentMatchers.isNull(), ArgumentMatchers.isA(Pageable.class))).thenReturn(events); + Mockito.when( + activityPlanFacade.findEventsByProject( + ArgumentMatchers.isA(Project.class), + ArgumentMatchers.isA(Date.class), + ArgumentMatchers.isNull(), + ArgumentMatchers.isA(Pageable.class) + ) + ).thenReturn(events); - panel = tester.startComponentInPage(new UpcomingActivitiesPanel("panel", Model.of(project)) { - @Override - public boolean isAuthorView() { - return isAuthor; + panel = tester.startComponentInPage( + new UpcomingActivitiesPanel("panel", Model.of(project)) { + @Override + public boolean isAuthorView() { + return isAuthor; + } } - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPageTest.java index 5796f18e12..b906d0c324 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminCreateProjectPageTest.java @@ -1,5 +1,19 @@ package se.su.dsv.scipro.admin.pages; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.time.Month; +import java.util.*; import org.apache.wicket.Page; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -14,21 +28,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.time.Month; -import java.util.*; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminCreateProjectPageTest extends PageTest { private String title; @@ -178,8 +177,7 @@ public class AdminCreateProjectPageTest extends PageTest { @Test public void shows_confirmation_page_if_any_author_already_has_an_active_project() { Project otherActiveProject = new Project(); - when(projectService.findByUserAndStatus(author, ProjectStatus.ACTIVE)) - .thenReturn(List.of(otherActiveProject)); + when(projectService.findByUserAndStatus(author, ProjectStatus.ACTIVE)).thenReturn(List.of(otherActiveProject)); startPage(); diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPageTest.java index 1bb3ed94fa..fca1614838 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminEditProjectPageTest.java @@ -1,272 +1,276 @@ -package se.su.dsv.scipro.admin.pages; - -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.tester.FormTester; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.mail.MailEvent; -import se.su.dsv.scipro.notifications.dataobject.NotificationSource; -import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.time.LocalDate; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.admin.pages.AdminEditProjectPage.*; - -public class AdminEditProjectPageTest extends SciProTest { - - public static final long AUTHOR_ID = 1L; - public static final long SUPERVISOR_ID = 2L; - public static final long SOME_EMPLOYEE_ID = 666L; - private static final Long ANOTHER_AUTHOR_ID = 8L; - public static final long EXISTING_CO_SUPERVISOR_ID = 11L; - public static final long EXISTING_REVIEWER_ID = 12L; - public static final long EXISTING_PARTICIPANT_ID = 13L; - - private User supervisor; - private User someEmployee; - private User author; - private Project project; - private User existingCoSupervisor; - private User existingReviewer; - private User existingParticipant; - private ProjectType bachelor; - - @BeforeEach - public void setUp() throws Exception { - bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - bachelor.setId(1L); - when(projectTypeService.findAllActive()).thenReturn(Collections.singletonList(bachelor)); - author = createUser("author", "user", "author@example.com", AUTHOR_ID); - author.addRole(Roles.AUTHOR); - someEmployee = createUser("some", "employee", "some@employee.com", SOME_EMPLOYEE_ID); - someEmployee.addRole(Roles.SUPERVISOR); - someEmployee.addRole(Roles.REVIEWER); - supervisor = createUser("supervisor", "user", "author@example.com", SUPERVISOR_ID); - supervisor.addRole(Roles.SUPERVISOR); - supervisor.addRole(Roles.REVIEWER); - - existingCoSupervisor = createUser("pelle", "svensson", "pelle@example.com", EXISTING_CO_SUPERVISOR_ID); - existingCoSupervisor.addRole(Roles.SUPERVISOR); - - existingReviewer = createUser("stina", "svensson", "stina@example.com", EXISTING_REVIEWER_ID); - existingReviewer.addRole(Roles.REVIEWER); - existingReviewer.addRole(Roles.SUPERVISOR); - - existingParticipant = createUser("kalle", "svensson", "kalle@example.com", EXISTING_PARTICIPANT_ID); - existingParticipant.addRole(Roles.AUTHOR); - - project = new Project(); - project.addProjectParticipant(author); - project.setId(20987234L); - project.setStartDate(LocalDate.now()); - startPage(project); - } - - private void mockAnotherAuthor() { - User anotherAuthor = createUser("another", "author", "another@example.com", ANOTHER_AUTHOR_ID); - anotherAuthor.addRole(Roles.AUTHOR); - } - - @Test - public void uses_separate_page_to_create_projects() { - startPage(new Project()); - tester.assertRenderedPage(AdminCreateProjectPage.class); - } - - @Test - public void title_required() { - submitForm("", SUPERVISOR_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("titleField.Required")); - } - - @Test - public void project_type_required() { - tester.isRequired(path(FORM, PROJECT_TYPE_SELECT)); - } - - @Test - public void head_supervisor_required() { - submitForm("title", null, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("headSupervisorSelect.Required")); - } - - @Test - public void author_required() { - final Project project1 = mockExistingProject(); - project1.setProjectParticipants(List.of()); - startPage(project1); - submitForm("title", SUPERVISOR_ID, null, existingReviewer.getId(), existingCoSupervisor.getId()); - tester.isRequired(path(FORM, AUTHORS)); - } - - @Test - public void not_same_user_head_reviewer() { - project.addReviewer(someEmployee); - startPage(project); - submitForm("title", SOME_EMPLOYEE_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("headReviewerSame")); - } - - @Test - public void not_same_user_head_co() { - project.addCoSupervisor(someEmployee); - startPage(project); - submitForm("title", SOME_EMPLOYEE_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("headCoSame")); - } - - @Test - public void not_same_user_head_author() { - submitForm("title", AUTHOR_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("headAuthorSame")); - } - - @Test - public void not_same_user_reviewer_co_supervisor() { - project.addCoSupervisor(someEmployee); - project.addReviewer(someEmployee); - startPage(project); - submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("reviewerCoSame")); - } - - @Test - public void not_same_user_reviewer_author() { - author.addRole(Roles.REVIEWER); - project.addReviewer(author); - startPage(project); - submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("reviewerAuthorSame")); - } - - @Test - public void not_same_user_co_author() { - project.addCoSupervisor(author); - startPage(project); - submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); - tester.assertErrorMessages(tester.getLastRenderedPage().getString("authorCoSame")); - } - - @Test - public void saves() { - String title = "cool title"; - submitForm(title, SUPERVISOR_ID, AUTHOR_ID, null, null); - ArgumentCaptor captor = ArgumentCaptor.forClass(Project.class); - verify(projectService).save(captor.capture()); - - tester.assertNoErrorMessage(); - assertEquals(title, captor.getValue().getTitle()); - } - - @Test - public void sends_notification_on_head_supervisor_change() { - startPage(mockExistingProject()); - submitForm("title", SOME_EMPLOYEE_ID, null, null, null); - verifyNotification(ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED); - verify(mailEventService).save(any(MailEvent.class)); - } - - @Test - public void sends_notification_when_authors_changed() { - mockAnotherAuthor(); - startPage(mockExistingProject()); - submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, null, null); - verifyNotification(ProjectEvent.Event.AUTHORS_CHANGED); - } - - @Test - public void sends_notification_when_reviewers_change() { - mockAnotherAuthor(); - startPage(mockExistingProject()); - submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, SOME_EMPLOYEE_ID, null); - verifyNotification(ProjectEvent.Event.REVIEWERS_CHANGED); - } - - @Test - public void sends_notification_when_co_supervisors_change() { - mockAnotherAuthor(); - startPage(mockExistingProject()); - submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, null, SOME_EMPLOYEE_ID); - verifyNotification(ProjectEvent.Event.CO_SUPERVISOR_CHANGED); - } - - private void verifyNotification(ProjectEvent.Event event) { - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Project.class); - verify(projectService).save(argumentCaptor.capture()); - verify(notificationController).notifyProject(eq(argumentCaptor.getValue()), eq(event), any(NotificationSource.class)); - } - - private Project mockExistingProject() { - Project project = Project.builder().title("a nice title").projectType(bachelor).startDate(LocalDate.now()).build(); - - project.addCoSupervisor(existingCoSupervisor); - - project.addReviewer(existingReviewer); - project.setHeadSupervisor(supervisor); - - project.addProjectParticipant(existingParticipant); - project.setId(777L); - - - - return project; - } - - private void submitForm(String title, Long supervisorId, Long authorId, Long reviewerId, Long coSupervisorId) { - FormTester formTester = tester.newFormTester(path(FORM)); - if (authorId != null) { - addAuthor(formTester, authorId); - } - if(reviewerId != null) { - addFollower(formTester, reviewerId, REVIEWERS); - } - if(coSupervisorId != null) { - addFollower(formTester, coSupervisorId, CO_SUPERVISORS); - } - if (supervisorId != null) { - formTester.setValue(HEAD_SUPERVISOR_SELECT, String.valueOf(supervisorId)); - } - formTester.setValue(TITLE_FIELD, title); - formTester.setValue("startDate", "2022-08-28"); - formTester.submit(); - } - - private void addFollower(FormTester formTester, Long reviewerId, String list) { - formTester.setValue(path(list), String.valueOf(reviewerId)); - } - - private void addAuthor(FormTester formTester, long authorId) { - formTester.setValue(path(AUTHORS), String.valueOf(authorId)); - } - - private User createUser(String firstName, String lastName, String emailAddress, long id) { - User user = User.builder().firstName(firstName).lastName(lastName).emailAddress(emailAddress).build(); - user.setId(id); - lenient().when(userSearchService.findOne(id)).thenReturn(user); - lenient().when(userService.findOne(id)).thenReturn(user); - return user; - } - - private void startPage(Project project) { - if (project.getId() != null) - when(projectService.findOne(project.getId())).thenReturn(project); - PageParameters pp = new PageParameters(); - pp.set(PageParameterKeys.MAP.get(Project.class), project.getId()); - tester.startPage(AdminEditProjectPage.class, pp); - } -} +package se.su.dsv.scipro.admin.pages; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.admin.pages.AdminEditProjectPage.*; + +import java.time.LocalDate; +import java.util.*; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.tester.FormTester; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.mail.MailEvent; +import se.su.dsv.scipro.notifications.dataobject.NotificationSource; +import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class AdminEditProjectPageTest extends SciProTest { + + public static final long AUTHOR_ID = 1L; + public static final long SUPERVISOR_ID = 2L; + public static final long SOME_EMPLOYEE_ID = 666L; + private static final Long ANOTHER_AUTHOR_ID = 8L; + public static final long EXISTING_CO_SUPERVISOR_ID = 11L; + public static final long EXISTING_REVIEWER_ID = 12L; + public static final long EXISTING_PARTICIPANT_ID = 13L; + + private User supervisor; + private User someEmployee; + private User author; + private Project project; + private User existingCoSupervisor; + private User existingReviewer; + private User existingParticipant; + private ProjectType bachelor; + + @BeforeEach + public void setUp() throws Exception { + bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); + bachelor.setId(1L); + when(projectTypeService.findAllActive()).thenReturn(Collections.singletonList(bachelor)); + author = createUser("author", "user", "author@example.com", AUTHOR_ID); + author.addRole(Roles.AUTHOR); + someEmployee = createUser("some", "employee", "some@employee.com", SOME_EMPLOYEE_ID); + someEmployee.addRole(Roles.SUPERVISOR); + someEmployee.addRole(Roles.REVIEWER); + supervisor = createUser("supervisor", "user", "author@example.com", SUPERVISOR_ID); + supervisor.addRole(Roles.SUPERVISOR); + supervisor.addRole(Roles.REVIEWER); + + existingCoSupervisor = createUser("pelle", "svensson", "pelle@example.com", EXISTING_CO_SUPERVISOR_ID); + existingCoSupervisor.addRole(Roles.SUPERVISOR); + + existingReviewer = createUser("stina", "svensson", "stina@example.com", EXISTING_REVIEWER_ID); + existingReviewer.addRole(Roles.REVIEWER); + existingReviewer.addRole(Roles.SUPERVISOR); + + existingParticipant = createUser("kalle", "svensson", "kalle@example.com", EXISTING_PARTICIPANT_ID); + existingParticipant.addRole(Roles.AUTHOR); + + project = new Project(); + project.addProjectParticipant(author); + project.setId(20987234L); + project.setStartDate(LocalDate.now()); + startPage(project); + } + + private void mockAnotherAuthor() { + User anotherAuthor = createUser("another", "author", "another@example.com", ANOTHER_AUTHOR_ID); + anotherAuthor.addRole(Roles.AUTHOR); + } + + @Test + public void uses_separate_page_to_create_projects() { + startPage(new Project()); + tester.assertRenderedPage(AdminCreateProjectPage.class); + } + + @Test + public void title_required() { + submitForm("", SUPERVISOR_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("titleField.Required")); + } + + @Test + public void project_type_required() { + tester.isRequired(path(FORM, PROJECT_TYPE_SELECT)); + } + + @Test + public void head_supervisor_required() { + submitForm("title", null, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("headSupervisorSelect.Required")); + } + + @Test + public void author_required() { + final Project project1 = mockExistingProject(); + project1.setProjectParticipants(List.of()); + startPage(project1); + submitForm("title", SUPERVISOR_ID, null, existingReviewer.getId(), existingCoSupervisor.getId()); + tester.isRequired(path(FORM, AUTHORS)); + } + + @Test + public void not_same_user_head_reviewer() { + project.addReviewer(someEmployee); + startPage(project); + submitForm("title", SOME_EMPLOYEE_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("headReviewerSame")); + } + + @Test + public void not_same_user_head_co() { + project.addCoSupervisor(someEmployee); + startPage(project); + submitForm("title", SOME_EMPLOYEE_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("headCoSame")); + } + + @Test + public void not_same_user_head_author() { + submitForm("title", AUTHOR_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("headAuthorSame")); + } + + @Test + public void not_same_user_reviewer_co_supervisor() { + project.addCoSupervisor(someEmployee); + project.addReviewer(someEmployee); + startPage(project); + submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("reviewerCoSame")); + } + + @Test + public void not_same_user_reviewer_author() { + author.addRole(Roles.REVIEWER); + project.addReviewer(author); + startPage(project); + submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("reviewerAuthorSame")); + } + + @Test + public void not_same_user_co_author() { + project.addCoSupervisor(author); + startPage(project); + submitForm("title", SUPERVISOR_ID, AUTHOR_ID, null, null); + tester.assertErrorMessages(tester.getLastRenderedPage().getString("authorCoSame")); + } + + @Test + public void saves() { + String title = "cool title"; + submitForm(title, SUPERVISOR_ID, AUTHOR_ID, null, null); + ArgumentCaptor captor = ArgumentCaptor.forClass(Project.class); + verify(projectService).save(captor.capture()); + + tester.assertNoErrorMessage(); + assertEquals(title, captor.getValue().getTitle()); + } + + @Test + public void sends_notification_on_head_supervisor_change() { + startPage(mockExistingProject()); + submitForm("title", SOME_EMPLOYEE_ID, null, null, null); + verifyNotification(ProjectEvent.Event.HEAD_SUPERVISOR_CHANGED); + verify(mailEventService).save(any(MailEvent.class)); + } + + @Test + public void sends_notification_when_authors_changed() { + mockAnotherAuthor(); + startPage(mockExistingProject()); + submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, null, null); + verifyNotification(ProjectEvent.Event.AUTHORS_CHANGED); + } + + @Test + public void sends_notification_when_reviewers_change() { + mockAnotherAuthor(); + startPage(mockExistingProject()); + submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, SOME_EMPLOYEE_ID, null); + verifyNotification(ProjectEvent.Event.REVIEWERS_CHANGED); + } + + @Test + public void sends_notification_when_co_supervisors_change() { + mockAnotherAuthor(); + startPage(mockExistingProject()); + submitForm("title", SUPERVISOR_ID, ANOTHER_AUTHOR_ID, null, SOME_EMPLOYEE_ID); + verifyNotification(ProjectEvent.Event.CO_SUPERVISOR_CHANGED); + } + + private void verifyNotification(ProjectEvent.Event event) { + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Project.class); + verify(projectService).save(argumentCaptor.capture()); + verify(notificationController).notifyProject( + eq(argumentCaptor.getValue()), + eq(event), + any(NotificationSource.class) + ); + } + + private Project mockExistingProject() { + Project project = Project.builder() + .title("a nice title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .build(); + + project.addCoSupervisor(existingCoSupervisor); + + project.addReviewer(existingReviewer); + project.setHeadSupervisor(supervisor); + + project.addProjectParticipant(existingParticipant); + project.setId(777L); + + return project; + } + + private void submitForm(String title, Long supervisorId, Long authorId, Long reviewerId, Long coSupervisorId) { + FormTester formTester = tester.newFormTester(path(FORM)); + if (authorId != null) { + addAuthor(formTester, authorId); + } + if (reviewerId != null) { + addFollower(formTester, reviewerId, REVIEWERS); + } + if (coSupervisorId != null) { + addFollower(formTester, coSupervisorId, CO_SUPERVISORS); + } + if (supervisorId != null) { + formTester.setValue(HEAD_SUPERVISOR_SELECT, String.valueOf(supervisorId)); + } + formTester.setValue(TITLE_FIELD, title); + formTester.setValue("startDate", "2022-08-28"); + formTester.submit(); + } + + private void addFollower(FormTester formTester, Long reviewerId, String list) { + formTester.setValue(path(list), String.valueOf(reviewerId)); + } + + private void addAuthor(FormTester formTester, long authorId) { + formTester.setValue(path(AUTHORS), String.valueOf(authorId)); + } + + private User createUser(String firstName, String lastName, String emailAddress, long id) { + User user = User.builder().firstName(firstName).lastName(lastName).emailAddress(emailAddress).build(); + user.setId(id); + lenient().when(userSearchService.findOne(id)).thenReturn(user); + lenient().when(userService.findOne(id)).thenReturn(user); + return user; + } + + private void startPage(Project project) { + if (project.getId() != null) when(projectService.findOne(project.getId())).thenReturn(project); + PageParameters pp = new PageParameters(); + pp.set(PageParameterKeys.MAP.get(Project.class), project.getId()); + tester.startPage(AdminEditProjectPage.class, pp); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminMailLogPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminMailLogPageTest.java index 063d3787f7..9619434cf4 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminMailLogPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminMailLogPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.admin.pages; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static se.su.dsv.scipro.admin.pages.AdminMailLogPage.MAIL_EVENTS; +import static se.su.dsv.scipro.admin.pages.AdminMailLogPage.MAIL_MODAL; + +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable; import org.junit.jupiter.api.BeforeEach; @@ -9,13 +15,6 @@ import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.dataproviders.FilteredDataProvider; import se.su.dsv.scipro.mail.MailEvent; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static se.su.dsv.scipro.admin.pages.AdminMailLogPage.MAIL_EVENTS; -import static se.su.dsv.scipro.admin.pages.AdminMailLogPage.MAIL_MODAL; - public class AdminMailLogPageTest extends PageTest { @BeforeEach diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminStartPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminStartPageTest.java index d94ea25ab5..5730176f22 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminStartPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/AdminStartPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminStartPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminStartPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/ProjectManagementPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/ProjectManagementPageTest.java index fd3966d445..7bdff13fd9 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/ProjectManagementPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/ProjectManagementPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class ProjectManagementPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(ProjectManagementPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePageTest.java index c935da2f59..33b9f2a931 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/SystemMaintenancePageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class SystemMaintenancePageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(SystemMaintenancePage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPageTest.java index 9b9810416e..17c64608e4 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminFooterSettingsPageTest.java @@ -15,4 +15,4 @@ public class AdminFooterSettingsPageTest extends PageTest { protected Class getPage() { return AdminFooterSettingsPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPageTest.java index 600d85ae2a..7cf7275643 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectModuleSettingsPageTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.admin.pages.settings; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.admin.pages.settings.AdminProjectModuleSettingsPage.*; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.util.tester.FormTester; @@ -11,17 +21,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.admin.pages.settings.AdminProjectModuleSettingsPage.*; - public class AdminProjectModuleSettingsPageTest extends SciProTest { private ProjectType projectType; @@ -51,7 +50,10 @@ public class AdminProjectModuleSettingsPageTest extends SciProTest { @Test public void lists_modules_as_rows() { - tester.assertModelValue(path(FORM, AdminProjectModuleSettingsPage.MODULE_LIST), Arrays.asList(ProjectModule.values())); + tester.assertModelValue( + path(FORM, AdminProjectModuleSettingsPage.MODULE_LIST), + Arrays.asList(ProjectModule.values()) + ); } @Test @@ -63,7 +65,10 @@ public class AdminProjectModuleSettingsPageTest extends SciProTest { @Test public void project_types_acts_as_table_header() { - tester.assertLabel(path(FORM, HEADER_LIST, 0, AdminProjectModuleSettingsPage.HEADER_NAME), projectType.getName()); + tester.assertLabel( + path(FORM, HEADER_LIST, 0, AdminProjectModuleSettingsPage.HEADER_NAME), + projectType.getName() + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPageTest.java index cd3b496af0..32085ce9b3 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminProjectTypeSettingsPageTest.java @@ -1,20 +1,23 @@ package se.su.dsv.scipro.admin.pages.settings; +import static org.mockito.Mockito.when; + +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.ProjectType; -import java.util.Collections; - -import static org.mockito.Mockito.when; - public class AdminProjectTypeSettingsPageTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - when(projectTypeService.findAllActive()).thenReturn(Collections.singletonList(new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor"))); - when(projectTypeService.findAllDeleted()).thenReturn(Collections.singletonList(new ProjectType(ProjectType.MASTER, "Master", "Master"))); + when(projectTypeService.findAllActive()).thenReturn( + Collections.singletonList(new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor")) + ); + when(projectTypeService.findAllDeleted()).thenReturn( + Collections.singletonList(new ProjectType(ProjectType.MASTER, "Master", "Master")) + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPageTest.java index 3177b71e49..7ed8e312e5 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/pages/settings/AdminReviewerDeadlineSettingsPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.admin.pages.settings; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -7,15 +11,10 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.reviewing.ReviewerDeadlineSettings; import se.su.dsv.scipro.security.auth.roles.Roles; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminReviewerDeadlineSettingsPageTest extends SciProTest { AdminReviewerDeadlineSettingsPage page; - @BeforeEach public void setUp() throws Exception { setLoggedIn(true); @@ -50,4 +49,4 @@ public class AdminReviewerDeadlineSettingsPageTest extends SciProTest { verify(reviewerDeadlineSettingsService).save(isA(ReviewerDeadlineSettings.class)); tester.assertInfoMessages("Settings saved"); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanelTest.java b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanelTest.java index 7919d0d987..ac63df3755 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterAddressPanelTest.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.admin.panels; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.FooterAddress; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminEditFooterAddressPanelTest extends SciProTest { private AdminEditFooterAddressPanel panel; @@ -34,7 +33,6 @@ public class AdminEditFooterAddressPanelTest extends SciProTest { tester.assertInfoMessages(panel.getString("saved")); } - private FooterAddress newFooterAddress() { FooterAddress footerAddress = new FooterAddress(); footerAddress.setTitle("DSV"); diff --git a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanelTest.java b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanelTest.java index 83b20259f9..4936eccb71 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminEditFooterColumnPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.admin.panels; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -8,13 +14,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.FooterColumn; import se.su.dsv.scipro.system.FooterLink; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminEditFooterColumnPanelTest extends SciProTest { private AdminEditFooterColumnPanel panel; @@ -111,4 +110,4 @@ public class AdminEditFooterColumnPanelTest extends SciProTest { footerLink.setId(45L); return footerLink; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanelTest.java b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanelTest.java index c7eb32c9e9..6ef6e213e6 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminProjectTypePanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.admin.panels; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; + import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -9,9 +12,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; - public class AdminProjectTypePanelTest extends SciProTest { private AdminProjectTypePanel panel; @@ -31,7 +31,7 @@ public class AdminProjectTypePanelTest extends SciProTest { int index = 3; FormTester formTester = tester.newFormTester(path(panel, "projectTypeForm")); - formTester.setValue("name", "bachelor"); + formTester.setValue("name", "bachelor"); formTester.select("degreeType", index); formTester.submit("createButton"); @@ -66,6 +66,9 @@ public class AdminProjectTypePanelTest extends SciProTest { ArgumentCaptor captor = ArgumentCaptor.forClass(ProjectType.class); verify(projectTypeService).save(captor.capture()); - assertEquals("https://example.com", captor.getValue().getProjectTypeSettings().getReviewProcessInformationUrl()); + assertEquals( + "https://example.com", + captor.getValue().getProjectTypeSettings().getReviewProcessInformationUrl() + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanelTest.java b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanelTest.java index 6c84cc81e6..9d0c9cb002 100644 --- a/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/admin/panels/AdminViewMailPanelTest.java @@ -8,10 +8,13 @@ import se.su.dsv.scipro.mail.MailEvent; import se.su.dsv.scipro.test.ObjectMother; public class AdminViewMailPanelTest extends SciProTest { + AdminViewMailPanel panel; private void startPanel() { - panel = tester.startComponentInPage(new AdminViewMailPanel("any", new Model<>(new MailEvent("subject", "body", ObjectMother.SOME_USER, "", "")))); + panel = tester.startComponentInPage( + new AdminViewMailPanel("any", new Model<>(new MailEvent("subject", "body", ObjectMother.SOME_USER, "", ""))) + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanelTest.java index 31e231936e..44eaef7552 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminApplicationPeriodsPanelTest.java @@ -1,17 +1,16 @@ package se.su.dsv.scipro.applicationperiod; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.match.ApplicationPeriod; - -import java.time.LocalDate; -import java.util.*; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.time.LocalDate; +import java.util.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.match.ApplicationPeriod; +import se.su.dsv.scipro.system.Pageable; + public class AdminApplicationPeriodsPanelTest extends SciProTest { @BeforeEach @@ -21,7 +20,7 @@ public class AdminApplicationPeriodsPanelTest extends SciProTest { applicationPeriod.setEndDate(LocalDate.MIN.plusDays(1)); applicationPeriod.setCourseStartDate(LocalDate.MIN.plusDays(2)); List applicationPeriods = new ArrayList<>(Collections.singletonList(applicationPeriod)); - when(applicationPeriodService.count()).thenReturn( (long) applicationPeriods.size()); + when(applicationPeriodService.count()).thenReturn((long) applicationPeriods.size()); when(applicationPeriodService.findAll(any(Pageable.class))).thenReturn(applicationPeriods); } diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPageTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPageTest.java index ec8a31df8c..b70d13b7e3 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodExemptionsPageTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.applicationperiod; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.applicationperiod.AdminEditApplicationPeriodExemptionsPage.*; + +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -12,17 +22,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Date; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.applicationperiod.AdminEditApplicationPeriodExemptionsPage.*; - public class AdminEditApplicationPeriodExemptionsPageTest extends SciProTest { ApplicationPeriod applicationPeriod; @@ -33,7 +32,11 @@ public class AdminEditApplicationPeriodExemptionsPageTest extends SciProTest { applicationPeriod.setId(1L); ApplicationPeriodExemption exemption = new ApplicationPeriodExemption(); - User user = new UserBuilder().setFirstName("Bill").setLastName("Gates").setEmail("billgates@example.com").create(); + User user = new UserBuilder() + .setFirstName("Bill") + .setLastName("Gates") + .setEmail("billgates@example.com") + .create(); exemption.setUser(user); exemption.setType(ApplicationPeriodExemption.Type.NUMBER_OF_AUTHORS); exemption.setComment("Bla bla bla"); @@ -51,9 +54,7 @@ public class AdminEditApplicationPeriodExemptionsPageTest extends SciProTest { startPage(); FormTester formTester = tester.newFormTester(ADD_FORM); formTester.submit(); - tester.assertErrorMessages( - "Field 'Exemption for' is required", - "Field 'Type to exempt' is required"); + tester.assertErrorMessages("Field 'Exemption for' is required", "Field 'Type to exempt' is required"); } @Test @@ -92,4 +93,4 @@ public class AdminEditApplicationPeriodExemptionsPageTest extends SciProTest { parameters.set(PageParameterKeys.MAP.get(ApplicationPeriod.class), 1L); return parameters; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPageTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPageTest.java index 9c6fffbf30..7b68730909 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditApplicationPeriodPageTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.applicationperiod; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.applicationperiod.AdminEditApplicationPeriodPage.*; + +import java.io.Serializable; +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.markup.html.form.RequiredTextField; @@ -19,15 +26,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; -import java.io.Serializable; -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.applicationperiod.AdminEditApplicationPeriodPage.*; - - public class AdminEditApplicationPeriodPageTest extends SciProTest { public static final boolean NOT_OVERLAPPING = false; @@ -60,7 +58,9 @@ public class AdminEditApplicationPeriodPageTest extends SciProTest { @Test public void submit_saves_application_period() { - when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn(NOT_OVERLAPPING); + when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn( + NOT_OVERLAPPING + ); String title = "title"; submitForm(title, 3, 4, 5); @@ -79,7 +79,9 @@ public class AdminEditApplicationPeriodPageTest extends SciProTest { @Test public void feedback_when_submitting_application_period() { - when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn(NOT_OVERLAPPING); + when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn( + NOT_OVERLAPPING + ); Page page = tester.getLastRenderedPage(); submitForm("title", 1, 2, 3); List messages = tester.getMessages(FeedbackMessage.SUCCESS); @@ -88,7 +90,9 @@ public class AdminEditApplicationPeriodPageTest extends SciProTest { @Test public void submission_fails_if_period_exists() { - when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn(OVERLAPPING); + when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn( + OVERLAPPING + ); startPage(); submitForm("title", 1, 2, 3); tester.assertErrorMessages(tester.getLastRenderedPage().getString("overlapping")); @@ -96,7 +100,9 @@ public class AdminEditApplicationPeriodPageTest extends SciProTest { @Test public void saves_correct_project_types() { - when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn(NOT_OVERLAPPING); + when(applicationPeriodService.doesPeriodOverlap(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn( + NOT_OVERLAPPING + ); FormTester formTester = tester.newFormTester(FORM); fillInForm("Title", 0, 1, 2, formTester); formTester.setValue(path(PROJECT_TYPES, 0, CHECKBOX), true); diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPageTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPageTest.java index c5d3add07b..4b4de6a725 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/AdminEditTargetsPageTest.java @@ -1,26 +1,25 @@ package se.su.dsv.scipro.applicationperiod; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.match.Target; import se.su.dsv.scipro.springdata.services.SupervisorService; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class AdminEditTargetsPageTest extends SciProTest { public static final String TARGET_PATH = "table:supervisors:0:applicationPeriods:0:projectTypes:0:target:input"; @@ -32,13 +31,19 @@ public class AdminEditTargetsPageTest extends SciProTest { public void setUp() throws Exception { someEmployee = new UserBuilder().create(); someEmployee.setId(1L); - when(supervisorService.findAll(any(SupervisorService.FilterParams.class), any(Pageable.class))).thenReturn(supervisorPage()); + when(supervisorService.findAll(any(SupervisorService.FilterParams.class), any(Pageable.class))).thenReturn( + supervisorPage() + ); ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); applicationPeriod = createApplicationPeriod(projectType); - when(applicationPeriodService.getPreviousPeriods(applicationPeriod, 2)).thenReturn(Collections.singletonList(createApplicationPeriod(projectType))); + when(applicationPeriodService.getPreviousPeriods(applicationPeriod, 2)).thenReturn( + Collections.singletonList(createApplicationPeriod(projectType)) + ); target = new Target(someEmployee, applicationPeriod, projectType); target.setTarget(3); - when(targetService.findOne(any(ApplicationPeriod.class), any(User.class), any(ProjectType.class))).thenReturn(target); + when(targetService.findOne(any(ApplicationPeriod.class), any(User.class), any(ProjectType.class))).thenReturn( + target + ); tester.startPage(new AdminEditTargetsPage(Model.of(applicationPeriod))); } @@ -49,7 +54,10 @@ public class AdminEditTargetsPageTest extends SciProTest { @Test public void header_contains_info_about_application_period() { - tester.assertLabel(AdminEditTargetsPage.HEADER, tester.getLastRenderedPage().getString("header", Model.of(applicationPeriod))); + tester.assertLabel( + AdminEditTargetsPage.HEADER, + tester.getLastRenderedPage().getString("header", Model.of(applicationPeriod)) + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanelTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanelTest.java index 2fd81ff62e..f21fc885ae 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodActivityPlanTemplateColumnPanelTest.java @@ -16,6 +16,7 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; public class ApplicationPeriodActivityPlanTemplateColumnPanelTest extends SciProTest { + public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); private ApplicationPeriodActivityPlanTemplateColumnPanel panel; @@ -42,27 +43,37 @@ public class ApplicationPeriodActivityPlanTemplateColumnPanelTest extends SciPro @Test public void project_class_label() { startPanel(); - panel.list.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(ApplicationPeriodActivityPlanTemplateColumnPanel.PC)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.list.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component + .get(path(ApplicationPeriodActivityPlanTemplateColumnPanel.PC)) + .isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test public void template_label() { startPanel(); - panel.list.visitChildren(ListItem.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - boolean isVisible = component.get(path(ApplicationPeriodActivityPlanTemplateColumnPanel.TEMPLATE)).isVisibleInHierarchy(); - Assertions.assertTrue(isVisible); - visit.stop(); + panel.list.visitChildren( + ListItem.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + boolean isVisible = component + .get(path(ApplicationPeriodActivityPlanTemplateColumnPanel.TEMPLATE)) + .isVisibleInHierarchy(); + Assertions.assertTrue(isVisible); + visit.stop(); + } } - }); + ); } @Test @@ -72,12 +83,15 @@ public class ApplicationPeriodActivityPlanTemplateColumnPanelTest extends SciPro } private void startPanel() { - panel = tester.startComponentInPage(new ApplicationPeriodActivityPlanTemplateColumnPanel("id", org.apache.wicket.model.Model.of(applicationPeriod)) { - @Override - public void onClick(AjaxRequestTarget target) { - + panel = tester.startComponentInPage( + new ApplicationPeriodActivityPlanTemplateColumnPanel( + "id", + org.apache.wicket.model.Model.of(applicationPeriod) + ) { + @Override + public void onClick(AjaxRequestTarget target) {} } - }); + ); } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanelTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanelTest.java index 202989f82d..81abec4491 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodInfoPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.applicationperiod; +import static se.su.dsv.scipro.applicationperiod.ApplicationPeriodInfoPanel.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.Model; @@ -12,13 +17,6 @@ import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; - -import static se.su.dsv.scipro.applicationperiod.ApplicationPeriodInfoPanel.*; - - @ExtendWith(MockitoExtension.class) public class ApplicationPeriodInfoPanelTest extends SciProTest { @@ -27,7 +25,6 @@ public class ApplicationPeriodInfoPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - bachelor = new ApplicationPeriod("Bachelor"); bachelor.setStartDate(LocalDate.MIN); bachelor.setEndDate(LocalDate.MIN.plusDays(1)); diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanelTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanelTest.java index d8e9e8cb89..f63ffd6efa 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/ApplicationPeriodSupervisorPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.applicationperiod; +import static java.util.Arrays.asList; +import static se.su.dsv.scipro.applicationperiod.ApplicationPeriodSupervisorPanel.*; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -15,15 +21,9 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import static java.util.Arrays.asList; -import static se.su.dsv.scipro.applicationperiod.ApplicationPeriodSupervisorPanel.*; - @ExtendWith(MockitoExtension.class) public class ApplicationPeriodSupervisorPanelTest extends SciProTest { + public static final long MATCHED_IDEAS = 4L; public static final int IDEA_TARGET_NUMBER = 5; private ApplicationPeriodSupervisorPanel panel; @@ -87,10 +87,28 @@ public class ApplicationPeriodSupervisorPanelTest extends SciProTest { ProjectType master = createProjectType(DegreeType.MASTER, "Master", 2L); if (hasEnoughIdeas) { - Mockito.when(targetService.ideasLeftToCreateToMeetTarget(ArgumentMatchers.isA(ApplicationPeriod.class), ArgumentMatchers.isA(User.class), ArgumentMatchers.isA(ProjectType.class))).thenReturn(0); + Mockito.when( + targetService.ideasLeftToCreateToMeetTarget( + ArgumentMatchers.isA(ApplicationPeriod.class), + ArgumentMatchers.isA(User.class), + ArgumentMatchers.isA(ProjectType.class) + ) + ).thenReturn(0); } else { - Mockito.when(targetService.ideasLeftToCreateToMeetTarget(ArgumentMatchers.isA(ApplicationPeriod.class), ArgumentMatchers.isA(User.class), ArgumentMatchers.eq(bachelor))).thenReturn(1); - Mockito.when(targetService.ideasLeftToCreateToMeetTarget(ArgumentMatchers.isA(ApplicationPeriod.class), ArgumentMatchers.isA(User.class), ArgumentMatchers.eq(master))).thenReturn(2); + Mockito.when( + targetService.ideasLeftToCreateToMeetTarget( + ArgumentMatchers.isA(ApplicationPeriod.class), + ArgumentMatchers.isA(User.class), + ArgumentMatchers.eq(bachelor) + ) + ).thenReturn(1); + Mockito.when( + targetService.ideasLeftToCreateToMeetTarget( + ArgumentMatchers.isA(ApplicationPeriod.class), + ArgumentMatchers.isA(User.class), + ArgumentMatchers.eq(master) + ) + ).thenReturn(2); } ApplicationPeriod ap = new ApplicationPeriod(); @@ -101,8 +119,20 @@ public class ApplicationPeriodSupervisorPanelTest extends SciProTest { Target t = new Target(new UserBuilder().create(), ap, bachelor); t.setTarget(IDEA_TARGET_NUMBER); - Mockito.when(targetService.findOne(ArgumentMatchers.isA(ApplicationPeriod.class), ArgumentMatchers.isA(User.class), ArgumentMatchers.isA(ProjectType.class))).thenReturn(t); - Mockito.when(ideaService.countMatched(ArgumentMatchers.isA(ApplicationPeriod.class), ArgumentMatchers.isA(User.class), ArgumentMatchers.isA(ProjectType.class))).thenReturn(MATCHED_IDEAS); + Mockito.when( + targetService.findOne( + ArgumentMatchers.isA(ApplicationPeriod.class), + ArgumentMatchers.isA(User.class), + ArgumentMatchers.isA(ProjectType.class) + ) + ).thenReturn(t); + Mockito.when( + ideaService.countMatched( + ArgumentMatchers.isA(ApplicationPeriod.class), + ArgumentMatchers.isA(User.class), + ArgumentMatchers.isA(ProjectType.class) + ) + ).thenReturn(MATCHED_IDEAS); panel = tester.startComponentInPage(new ApplicationPeriodSupervisorPanel("panel", Model.of(ap))); } diff --git a/view/src/test/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanelTest.java index f3dfe8e813..7f46024839 100644 --- a/view/src/test/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/applicationperiod/EditApplicationPeriodActivityPlanTemplatePanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.applicationperiod; +import static se.su.dsv.scipro.applicationperiod.EditApplicationPeriodActivityPlanTemplatePanel.*; + +import java.util.ArrayList; +import java.util.Collections; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.Model; @@ -14,12 +18,8 @@ import se.su.dsv.scipro.match.ApplicationPeriodProjectType; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.util.ArrayList; -import java.util.Collections; - -import static se.su.dsv.scipro.applicationperiod.EditApplicationPeriodActivityPlanTemplatePanel.*; - public class EditApplicationPeriodActivityPlanTemplatePanelTest extends SciProTest { + public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); private EditApplicationPeriodActivityPlanTemplatePanel panel; @@ -34,7 +34,9 @@ public class EditApplicationPeriodActivityPlanTemplatePanelTest extends SciProTe applicationPeriod.getApplicationPeriodProjectTypes().add(appt); - Mockito.when(activityPlanTemplateService.findAll()).thenReturn(Collections.singletonList(new ActivityPlanTemplate())); + Mockito.when(activityPlanTemplateService.findAll()).thenReturn( + Collections.singletonList(new ActivityPlanTemplate()) + ); } @Test @@ -52,7 +54,10 @@ public class EditApplicationPeriodActivityPlanTemplatePanelTest extends SciProTe @Test public void list() { startPanel(); - tester.assertModelValue(path(FORM, LIST), new ArrayList<>(applicationPeriod.getApplicationPeriodProjectTypes())); + tester.assertModelValue( + path(FORM, LIST), + new ArrayList<>(applicationPeriod.getApplicationPeriodProjectTypes()) + ); } @Test @@ -68,7 +73,9 @@ public class EditApplicationPeriodActivityPlanTemplatePanelTest extends SciProTe } private void startPanel() { - panel = tester.startComponentInPage(new EditApplicationPeriodActivityPlanTemplatePanel("id", Model.of(applicationPeriod))); + panel = tester.startComponentInPage( + new EditApplicationPeriodActivityPlanTemplatePanel("id", Model.of(applicationPeriod)) + ); } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/basepages/MenuPageTest.java b/view/src/test/java/se/su/dsv/scipro/basepages/MenuPageTest.java index 04887ed044..75beadc0fc 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepages/MenuPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepages/MenuPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class MenuPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(new MenuPage() {}); diff --git a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPageTest.java b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPageTest.java index 6bde747737..31cf9d5b19 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/AccessDeniedPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AccessDeniedPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AccessDeniedPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPageTest.java b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPageTest.java index 3abf9e9bd8..c19482e814 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/InternalErrorPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class InternalErrorPageTest extends PageTest { + @Override protected Class getPage() { return InternalErrorPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPageTest.java b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPageTest.java index daa46e5a44..625baaf479 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/NotFoundPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class NotFoundPageTest extends PageTest { + @Override protected Class getPage() { return NotFoundPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPageTest.java b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPageTest.java index 5f41cfdd48..8373ff3ae5 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepages/errorpages/PageExpiredPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class PageExpiredPageTest extends PageTest { + @Override protected Class getPage() { return PageExpiredPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/basepanels/FooterPanelTest.java b/view/src/test/java/se/su/dsv/scipro/basepanels/FooterPanelTest.java index 6b8fbc23a4..62aea3c6f0 100644 --- a/view/src/test/java/se/su/dsv/scipro/basepanels/FooterPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/basepanels/FooterPanelTest.java @@ -1,46 +1,46 @@ -package se.su.dsv.scipro.basepanels; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.FooterAddress; -import se.su.dsv.scipro.system.FooterColumn; -import se.su.dsv.scipro.system.FooterLink; - -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -public class FooterPanelTest extends SciProTest { - - @BeforeEach - public void setUp() throws Exception { - when(footerLinkService.getLinks(any(FooterColumn.class))).thenReturn( - Collections.singletonList(new FooterLink())); - } - - @Test - public void renders() throws Exception { - startPanel(); - } - - @Test - public void shows_current_footer_address_if_available() { - FooterAddress address = mockExistingAddress(); - startPanel(); - tester.assertLabel(path("id", "address", "addresses", "title"), address.getTitle()); - } - - private FooterAddress mockExistingAddress() { - FooterAddress address = new FooterAddress(); - address.setTitle("title!"); - address.setAddress("address 123"); - when(footerAddressRepo.findAll()).thenReturn(Collections.singletonList(address)); - return address; - } - - private FooterPanel startPanel() { - return tester.startComponentInPage(new FooterPanel("id")); - } -} +package se.su.dsv.scipro.basepanels; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.FooterAddress; +import se.su.dsv.scipro.system.FooterColumn; +import se.su.dsv.scipro.system.FooterLink; + +public class FooterPanelTest extends SciProTest { + + @BeforeEach + public void setUp() throws Exception { + when(footerLinkService.getLinks(any(FooterColumn.class))).thenReturn( + Collections.singletonList(new FooterLink()) + ); + } + + @Test + public void renders() throws Exception { + startPanel(); + } + + @Test + public void shows_current_footer_address_if_available() { + FooterAddress address = mockExistingAddress(); + startPanel(); + tester.assertLabel(path("id", "address", "addresses", "title"), address.getTitle()); + } + + private FooterAddress mockExistingAddress() { + FooterAddress address = new FooterAddress(); + address.setTitle("title!"); + address.setAddress("address 123"); + when(footerAddressRepo.findAll()).thenReturn(Collections.singletonList(address)); + return address; + } + + private FooterPanel startPanel() { + return tester.startComponentInPage(new FooterPanel("id")); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/AdminChecklistPageTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/AdminChecklistPageTest.java index 7ff943687a..270373e44e 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/AdminChecklistPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/AdminChecklistPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminChecklistPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminChecklistPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePageTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePageTest.java index 04bd6bd762..8013403bff 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/AdminEditChecklistTemplatePageTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.checklists; +import static org.mockito.Mockito.verify; +import static se.su.dsv.scipro.checklists.AdminEditChecklistTemplatePage.*; + import org.apache.wicket.markup.html.form.CheckBoxMultipleChoice; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.form.TextField; @@ -17,10 +20,8 @@ import se.su.dsv.scipro.checklist.ChecklistTemplate; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import static org.mockito.Mockito.verify; -import static se.su.dsv.scipro.checklists.AdminEditChecklistTemplatePage.*; - public class AdminEditChecklistTemplatePageTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); @@ -75,7 +76,10 @@ public class AdminEditChecklistTemplatePageTest extends SciProTest { FormTester formTester = tester.newFormTester(path(FORM)); formTester.setValue(TITLE, "a"); formTester.submit(); - tester.assertErrorMessages("Could not save checklist template", "The value of 'Title:' is shorter than the minimum of 3 characters."); + tester.assertErrorMessages( + "Could not save checklist template", + "The value of 'Title:' is shorter than the minimum of 3 characters." + ); } @Test @@ -109,4 +113,4 @@ public class AdminEditChecklistTemplatePageTest extends SciProTest { startPage(); tester.assertComponent(path(FORM, AdminEditChecklistTemplatePage.DESCRIPTION), TextArea.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanelTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanelTest.java index 9583c624d6..00bbc53b5a 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistAnswerCommentPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.checklists; +import static se.su.dsv.scipro.checklists.ChecklistAnswerCommentPanel.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.wicket.MarkupContainer; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; @@ -9,13 +15,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.checklist.ChecklistAnswer; import se.su.dsv.scipro.checklist.ChecklistQuestion; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static se.su.dsv.scipro.checklists.ChecklistAnswerCommentPanel.*; - public class ChecklistAnswerCommentPanelTest extends SciProTest { ChecklistAnswerCommentPanel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanelTest.java index 045824e3b2..55a0eda575 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistOverviewPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.checklists; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,12 +14,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class ChecklistOverviewPanelTest extends SciProTest { private ChecklistOverviewPanel panel; @@ -36,5 +35,4 @@ public class ChecklistOverviewPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new ChecklistOverviewPanel("panel", Model.of(project))); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanelTest.java index 0056d0498d..3bd475c418 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistQuestionPanelTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.checklists; +import java.time.LocalDate; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.Assertions; @@ -21,11 +22,13 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; - public class ChecklistQuestionPanelTest extends SciProTest { - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType( + DegreeType.BACHELOR, + "Some project type", + "Some description" + ); private ChecklistQuestionPanel panel; private Project project; private Checklist checklist; @@ -40,7 +43,11 @@ public class ChecklistQuestionPanelTest extends SciProTest { question = new ChecklistQuestion("What?", 1); answer = new ChecklistAnswer(user); question.addAnswer(answer); - project = Project.builder().title("Some title").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).build(); + project = Project.builder() + .title("Some title") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .build(); project.addProjectParticipant(user); checklist = Checklist.builder().name("Some name").project(project).build(); checklist.addQuestion(question); @@ -59,7 +66,11 @@ public class ChecklistQuestionPanelTest extends SciProTest { answerChecklistQuestion(); - Mockito.verify(notificationController).notifyProject(ArgumentMatchers.eq(project), ArgumentMatchers.eq(ProjectEvent.Event.CHECKLIST_ANSWERED), ArgumentMatchers.any(NotificationSource.class)); + Mockito.verify(notificationController).notifyProject( + ArgumentMatchers.eq(project), + ArgumentMatchers.eq(ProjectEvent.Event.CHECKLIST_ANSWERED), + ArgumentMatchers.any(NotificationSource.class) + ); } @Test @@ -68,7 +79,11 @@ public class ChecklistQuestionPanelTest extends SciProTest { answerChecklistQuestion(); - Mockito.verify(notificationController, Mockito.never()).notifyProject(ArgumentMatchers.eq(project), ArgumentMatchers.eq(ProjectEvent.Event.CHECKLIST_ANSWERED), ArgumentMatchers.any(NotificationSource.class)); + Mockito.verify(notificationController, Mockito.never()).notifyProject( + ArgumentMatchers.eq(project), + ArgumentMatchers.eq(ProjectEvent.Event.CHECKLIST_ANSWERED), + ArgumentMatchers.any(NotificationSource.class) + ); } private void answerChecklistQuestion() { @@ -76,17 +91,44 @@ public class ChecklistQuestionPanelTest extends SciProTest { panel = (ChecklistQuestionPanel) startPanel(); - tester.clickLink(path(panel.getId(), "wmc", ChecklistQuestionPanel.QUESTIONS, 0, ChecklistQuestionPanel.ANSWERS, 0, "answer", "answerLink")); - FormTester formTester = tester.newFormTester(path(panel.getId(), "wmc", ChecklistQuestionPanel.QUESTIONS, 0, ChecklistQuestionPanel.ANSWERS, 0, "answer", "dialog", "body", "form"));// (panel.getId(), ChecklistQuestionPanel.ANSWER_DIALOG, AnswerDialogPanel.ANSWER_DIALOG, AnswerDialogPanel.CONTENT, AnswerDialogPanel.ANSWER_FORM)); + tester.clickLink( + path( + panel.getId(), + "wmc", + ChecklistQuestionPanel.QUESTIONS, + 0, + ChecklistQuestionPanel.ANSWERS, + 0, + "answer", + "answerLink" + ) + ); + FormTester formTester = tester.newFormTester( + path( + panel.getId(), + "wmc", + ChecklistQuestionPanel.QUESTIONS, + 0, + ChecklistQuestionPanel.ANSWERS, + 0, + "answer", + "dialog", + "body", + "form" + ) + ); // (panel.getId(), ChecklistQuestionPanel.ANSWER_DIALOG, AnswerDialogPanel.ANSWER_DIALOG, AnswerDialogPanel.CONTENT, AnswerDialogPanel.ANSWER_FORM)); formTester.setValue("comment", "Comment"); -// tester.clickLink(path(panel.getId(), "wmc", ChecklistQuestionPanel.QUESTIONS, 0, ChecklistQuestionPanel.ANSWERS, 0, "answer", "dialog", "body", "form", "submit")); + // tester.clickLink(path(panel.getId(), "wmc", ChecklistQuestionPanel.QUESTIONS, 0, ChecklistQuestionPanel.ANSWERS, 0, "answer", "dialog", "body", "form", "submit")); formTester.submit(); } private Panel startPanel() { Mockito.when(checklistService.findOne(checklist.getId())).thenReturn(checklist); - DetachableServiceModel checklistModel = new DetachableServiceModel<>(checklistService, checklist.getId()); + DetachableServiceModel checklistModel = new DetachableServiceModel<>( + checklistService, + checklist.getId() + ); return tester.startComponentInPage(new ChecklistQuestionPanel("panel", checklistModel)); } } diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanelTest.java index 512d13a250..d5aeb1dc00 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/ChecklistTemplateDataPanelTest.java @@ -4,8 +4,9 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class ChecklistTemplateDataPanelTest extends SciProTest { + @Test public void renders() throws Exception { tester.startComponentInPage(new ChecklistTemplateDataPanel("id")); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPageTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPageTest.java index c7e8690edc..57e4f575e6 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/ProjectViewChecklistPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.checklists; +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -17,8 +18,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - public class ProjectViewChecklistPageTest extends PageTest { private Checklist checklist; @@ -31,11 +30,11 @@ public class ProjectViewChecklistPageTest extends PageTest { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); Project project = Project.builder() - .title("some title") - .projectType(projectType) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); Mockito.when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPageTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPageTest.java index 847647d989..db8e726e0d 100755 --- a/view/src/test/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/SupervisorViewChecklistPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.checklists; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,9 +16,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.ArrayList; -import java.util.List; - public class SupervisorViewChecklistPageTest extends PageTest { private static final String SOME_NAME = "someName"; @@ -37,13 +36,17 @@ public class SupervisorViewChecklistPageTest extends PageTest { @BeforeEach public void setUp() { - - - checklist = Checklist.builder().name(SOME_NAME).project(ObjectMother._Project.create(1L)).description("description!").build(); + checklist = Checklist.builder() + .name(SOME_NAME) + .project(ObjectMother._Project.create(1L)) + .description("description!") + .build(); checklist.setId(2L); Mockito.when(checklistService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(checklist); Mockito.when(projectService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(checklist.getProject()); - Mockito.when(projectService.hasSupervisingRole(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class))).thenReturn(true); + Mockito.when( + projectService.hasSupervisingRole(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class)) + ).thenReturn(true); ChecklistQuestion question = new ChecklistQuestion("", 1); List questions = new ArrayList<>(); diff --git a/view/src/test/java/se/su/dsv/scipro/checklists/TrafficLightPanelTest.java b/view/src/test/java/se/su/dsv/scipro/checklists/TrafficLightPanelTest.java index b6c0e57856..73e63ada01 100644 --- a/view/src/test/java/se/su/dsv/scipro/checklists/TrafficLightPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/checklists/TrafficLightPanelTest.java @@ -6,6 +6,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.checklist.ChecklistAnswerEnum; public class TrafficLightPanelTest extends SciProTest { + private TrafficLightPanel panel; @Test diff --git a/view/src/test/java/se/su/dsv/scipro/components/AddUsersPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/AddUsersPanelTest.java index 33af95068c..6d42fb85b2 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/AddUsersPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/AddUsersPanelTest.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.components; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashSet; import org.apache.wicket.model.util.SetModel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.User; -import java.util.HashSet; - -import static org.junit.jupiter.api.Assertions.assertTrue; - public class AddUsersPanelTest extends SciProTest { AddUsersPanel panel; @@ -32,7 +31,8 @@ public class AddUsersPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new AddUsersPanel("id", new SetModel<>(users), AddUsersPanel.LookFor.AUTHORS)); + panel = tester.startComponentInPage( + new AddUsersPanel("id", new SetModel<>(users), AddUsersPanel.LookFor.AUTHORS) + ); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/components/AjaxEnumLinkPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/AjaxEnumLinkPanelTest.java index 387c0788f0..6bcd604621 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/AjaxEnumLinkPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/AjaxEnumLinkPanelTest.java @@ -13,7 +13,9 @@ public class AjaxEnumLinkPanelTest extends SciProTest { @Test public void displays_proper_enum_label() { EnumPanel.TestEnum expectedEnum = EnumPanel.TestEnum.FOO; - Component panel = tester.startComponentInPage(new EnumPanel("id", Model.of("Some string"), Model.of(expectedEnum))); + Component panel = tester.startComponentInPage( + new EnumPanel("id", Model.of("Some string"), Model.of(expectedEnum)) + ); String labelPath = path(panel, AjaxLinkPanel.LINK, AjaxLinkPanel.LABEL); tester.assertComponent(labelPath, EnumLabel.class); @@ -21,7 +23,10 @@ public class AjaxEnumLinkPanelTest extends SciProTest { } public static class EnumPanel extends AjaxEnumLinkPanel { - public enum TestEnum { FOO } + + public enum TestEnum { + FOO, + } public EnumPanel(String id, IModel model, IModel enumLabel) { super(id, model, enumLabel); diff --git a/view/src/test/java/se/su/dsv/scipro/components/AjaxLinkPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/AjaxLinkPanelTest.java index 21f7d6e7ce..35b3ddc06d 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/AjaxLinkPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/AjaxLinkPanelTest.java @@ -44,11 +44,13 @@ public class AjaxLinkPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new AjaxLinkPanel("panel", Model.of(project), Model.of(project).map(Project::getTitle)) { - @Override - public void onClick(AjaxRequestTarget target, IModel model) { - //do nothing + panel = tester.startComponentInPage( + new AjaxLinkPanel("panel", Model.of(project), Model.of(project).map(Project::getTitle)) { + @Override + public void onClick(AjaxRequestTarget target, IModel model) { + //do nothing + } } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/components/BootstrapDateTimeComponentTest.java b/view/src/test/java/se/su/dsv/scipro/components/BootstrapDateTimeComponentTest.java index 0f1545f11e..d175e84384 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/BootstrapDateTimeComponentTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/BootstrapDateTimeComponentTest.java @@ -4,9 +4,10 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class BootstrapDateTimeComponentTest extends SciProTest { + @Test public void renders() throws Exception { tester.startComponentInPage(new BootstrapDateTimeComponent("test")); tester.assertComponent("test", BootstrapDateTimeComponent.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/components/DisplayMultiplesPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/DisplayMultiplesPanelTest.java index 598d1dfcdc..53411a83d3 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/DisplayMultiplesPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/DisplayMultiplesPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.components; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.IModel; @@ -14,10 +16,6 @@ import se.su.dsv.scipro.profile.UserLinkPanel; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.util.ArrayList; -import java.util.List; - - @ExtendWith(MockitoExtension.class) public class DisplayMultiplesPanelTest extends SciProTest { @@ -45,15 +43,20 @@ public class DisplayMultiplesPanelTest extends SciProTest { @Test public void testPanelVisible() { - tester.assertComponent(path(panel, DisplayMultiplesPanel.LIST, 0, DisplayMultiplesPanel.COMPONENT), UserLinkPanel.class); + tester.assertComponent( + path(panel, DisplayMultiplesPanel.LIST, 0, DisplayMultiplesPanel.COMPONENT), + UserLinkPanel.class + ); } private void startPanel() { - panel = tester.startComponentInPage(new DisplayMultiplesPanel("panel", new ListModel<>(students)) { - @Override - public Component getComponent(String componentId, IModel model) { - return new UserLinkPanel(COMPONENT, model); + panel = tester.startComponentInPage( + new DisplayMultiplesPanel("panel", new ListModel<>(students)) { + @Override + public Component getComponent(String componentId, IModel model) { + return new UserLinkPanel(COMPONENT, model); + } } - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/components/InfoPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/InfoPanelTest.java index 8b08efbc12..e24c588dc0 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/InfoPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/InfoPanelTest.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.components; +import static se.su.dsv.scipro.components.InfoPanel.*; + import org.apache.wicket.extensions.markup.html.basic.SmartLinkMultiLineLabel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import static se.su.dsv.scipro.components.InfoPanel.*; - public class InfoPanelTest extends SciProTest { private InfoPanel panel; @@ -33,7 +33,7 @@ public class InfoPanelTest extends SciProTest { tester.assertComponent(path(panel, CONTAINER, INFO), SmartLinkMultiLineLabel.class); } - private void startPanel(){ + private void startPanel() { panel = tester.startComponentInPage(new InfoPanel("id", Model.of("bla bla"))); } } diff --git a/view/src/test/java/se/su/dsv/scipro/components/ListAdapterModelTest.java b/view/src/test/java/se/su/dsv/scipro/components/ListAdapterModelTest.java index 864a480cab..7d28fd001d 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/ListAdapterModelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/ListAdapterModelTest.java @@ -1,14 +1,13 @@ package se.su.dsv.scipro.components; import com.google.common.collect.Sets; +import java.util.*; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.*; - public class ListAdapterModelTest { @Test diff --git a/view/src/test/java/se/su/dsv/scipro/components/ListFieldTest.java b/view/src/test/java/se/su/dsv/scipro/components/ListFieldTest.java index a57d6d4c90..b27f463738 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/ListFieldTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/ListFieldTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.components; +import static se.su.dsv.scipro.components.ListFieldTest.ListFieldForm.FORM; +import static se.su.dsv.scipro.components.ListFieldTest.ListFieldForm.LIST_FIELD; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.panel.Panel; @@ -11,13 +17,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static se.su.dsv.scipro.components.ListFieldTest.ListFieldForm.FORM; -import static se.su.dsv.scipro.components.ListFieldTest.ListFieldForm.LIST_FIELD; - public class ListFieldTest extends SciProTest { private ListFieldForm panel; @@ -48,9 +47,15 @@ public class ListFieldTest extends SciProTest { @Test public void testShowsListValues() { - FormComponent listField = (FormComponent) tester.getComponentFromLastRenderedPage(path(panel, FORM, LIST_FIELD)); + FormComponent listField = (FormComponent) tester.getComponentFromLastRenderedPage( + path(panel, FORM, LIST_FIELD) + ); - Assertions.assertEquals(defaultList.stream().collect(Collectors.joining(ListField.SEPARATOR)), listField.getValue(), "Does not show list values"); + Assertions.assertEquals( + defaultList.stream().collect(Collectors.joining(ListField.SEPARATOR)), + listField.getValue(), + "Does not show list values" + ); } public static class ListFieldForm extends Panel { @@ -60,7 +65,6 @@ public class ListFieldTest extends SciProTest { public ListFieldForm(String id, IModel> listIModel) { super(id); - Form form = new Form<>(FORM); form.add(new ListField<>(LIST_FIELD, listIModel, null)); add(form); diff --git a/view/src/test/java/se/su/dsv/scipro/components/SortOrderPanelTest.java b/view/src/test/java/se/su/dsv/scipro/components/SortOrderPanelTest.java index 5e761f4126..c95bbe965c 100644 --- a/view/src/test/java/se/su/dsv/scipro/components/SortOrderPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/components/SortOrderPanelTest.java @@ -19,9 +19,13 @@ public class SortOrderPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { milestonePhaseTemplate = new MilestonePhaseTemplate("title", "desc"); - mileStonePhaseTemplateService = Mockito.mock(MilestonePhaseTemplateService.class, Mockito.withSettings().serializable()); - panel = tester.startComponentInPage(new SortOrderPanel<>("panel", Model.of(milestonePhaseTemplate), mileStonePhaseTemplateService)); - + mileStonePhaseTemplateService = Mockito.mock( + MilestonePhaseTemplateService.class, + Mockito.withSettings().serializable() + ); + panel = tester.startComponentInPage( + new SortOrderPanel<>("panel", Model.of(milestonePhaseTemplate), mileStonePhaseTemplateService) + ); } @Test @@ -34,7 +38,9 @@ public class SortOrderPanelTest extends SciProTest { String moveUpPath = path(panel.getId(), SortOrderPanel.MOVE_UP); tester.assertComponent(moveUpPath, AjaxLink.class); tester.executeAjaxEvent(moveUpPath, "click"); - Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).moveUp(ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).moveUp( + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); } @Test @@ -42,7 +48,8 @@ public class SortOrderPanelTest extends SciProTest { String moveDownPath = path(panel.getId(), SortOrderPanel.MOVE_DOWN); tester.assertComponent(moveDownPath, AjaxLink.class); tester.executeAjaxEvent(moveDownPath, "click"); - Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).moveDown(ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).moveDown( + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/crosscutting/ForwardPhase2FeedbackTest.java b/view/src/test/java/se/su/dsv/scipro/crosscutting/ForwardPhase2FeedbackTest.java index cd27562cfa..a4a9e4e24e 100644 --- a/view/src/test/java/se/su/dsv/scipro/crosscutting/ForwardPhase2FeedbackTest.java +++ b/view/src/test/java/se/su/dsv/scipro/crosscutting/ForwardPhase2FeedbackTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.crosscutting; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.verify; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.Date; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; @@ -11,16 +20,6 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalRejectedEvent; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Date; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.verify; - class ForwardPhase2FeedbackTest extends SciProTest { private ForwardPhase2Feedback forwardPhase2Feedback; diff --git a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotificationsTest.java b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotificationsTest.java index 365af7f95d..592fd368f9 100644 --- a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotificationsTest.java +++ b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerAssignedNotificationsTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.crosscutting; +import static org.mockito.Mockito.*; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.Date; +import java.util.Optional; +import java.util.TreeSet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,20 +27,15 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Date; -import java.util.Optional; -import java.util.TreeSet; - -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class ReviewerAssignedNotificationsTest { + @Mock private RoughDraftApprovalService roughDraftApprovalService; + @Mock private FinalSeminarApprovalService finalSeminarApprovalService; + @Mock private NotificationController notificationController; @@ -44,14 +46,23 @@ public class ReviewerAssignedNotificationsTest { @BeforeEach public void setUp() throws Exception { - reviewerAssignedNotifications = new ReviewerAssignedNotifications(roughDraftApprovalService, finalSeminarApprovalService, notificationController); + reviewerAssignedNotifications = new ReviewerAssignedNotifications( + roughDraftApprovalService, + finalSeminarApprovalService, + notificationController + ); final ProjectType master = new ProjectType(DegreeType.MASTER, "Master", "Master"); reviewer = User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build(); reviewer.setId(1L); TreeSet reviewers = new TreeSet<>(new User.ByNameComparator()); reviewers.addAll(Collections.singleton(reviewer)); - project = Project.builder().title("My project").projectType(master).startDate(LocalDate.now()).reviewers(reviewers).build(); + project = Project.builder() + .title("My project") + .projectType(master) + .startDate(LocalDate.now()) + .reviewers(reviewers) + .build(); when(roughDraftApprovalService.findBy(project)).thenReturn(Optional.empty()); when(finalSeminarApprovalService.findBy(project)).thenReturn(Optional.empty()); @@ -63,38 +74,69 @@ public class ReviewerAssignedNotificationsTest { reviewerAssignedNotifications.reviewerAssigned(new ReviewerAssignedEvent(project, reviewer)); - verify(notificationController, never()).notifyProject(eq(project), eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), any(NotificationSource.class)); + verify(notificationController, never()).notifyProject( + eq(project), + eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), + any(NotificationSource.class) + ); } @Test public void notifies_on_undecided_final_seminar_approval() { - final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval(project, referenceTo(new FileDescription()), "comment", new Date()); + final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval( + project, + referenceTo(new FileDescription()), + "comment", + new Date() + ); when(finalSeminarApprovalService.findBy(project)).thenReturn(Optional.of(finalSeminarApproval)); reviewerAssignedNotifications.reviewerAssigned(new ReviewerAssignedEvent(project, reviewer)); - verify(notificationController).notifyProject(eq(project), eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), any(NotificationSource.class)); + verify(notificationController).notifyProject( + eq(project), + eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), + any(NotificationSource.class) + ); } @Test public void does_not_notify_on_decided_approvals() { - final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval(project, referenceTo(new FileDescription()), "comment", new Date()); + final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval( + project, + referenceTo(new FileDescription()), + "comment", + new Date() + ); finalSeminarApproval.approve("Good", Optional.empty()); when(finalSeminarApprovalService.findBy(project)).thenReturn(Optional.of(finalSeminarApproval)); reviewerAssignedNotifications.reviewerAssigned(new ReviewerAssignedEvent(project, reviewer)); - verify(notificationController, never()).notifyProject(eq(project), eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), any(NotificationSource.class)); + verify(notificationController, never()).notifyProject( + eq(project), + eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), + any(NotificationSource.class) + ); } @Test public void notifies_on_undecided_rough_draft_approval() { - final RoughDraftApproval roughDraftApproval = new RoughDraftApproval(project, referenceTo(new FileDescription()), "comment", new Date()); + final RoughDraftApproval roughDraftApproval = new RoughDraftApproval( + project, + referenceTo(new FileDescription()), + "comment", + new Date() + ); when(roughDraftApprovalService.findBy(project)).thenReturn(Optional.of(roughDraftApproval)); reviewerAssignedNotifications.reviewerAssigned(new ReviewerAssignedEvent(project, reviewer)); - verify(notificationController).notifyProject(eq(project), eq(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED), any(NotificationSource.class)); + verify(notificationController).notifyProject( + eq(project), + eq(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED), + any(NotificationSource.class) + ); } private static FileReference referenceTo(final FileDescription fileDescription) { @@ -102,4 +144,4 @@ public class ReviewerAssignedNotificationsTest { fileReference.setFileDescription(fileDescription); return fileReference; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailerTest.java b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailerTest.java index a23f0c59bf..58512d12df 100644 --- a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailerTest.java +++ b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewerSupportMailerTest.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.crosscutting; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.common.eventbus.EventBus; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,22 +29,21 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ReviewerSupportMailerTest { + @Mock private EventBus eventBus; + @Mock private MailEventService mailEventService; + @Mock private GeneralSystemSettingsService generalSystemSettingsService; + @InjectMocks private ReviewerSupportMailer reviewerSupportMailer; + private FinalSeminarApproval finalSeminarApproval; private RoughDraftApproval roughDraftApproval; @@ -52,7 +56,12 @@ public class ReviewerSupportMailerTest { researchArea.setTitle("IT"); researchAreas.add(researchArea); supervisor.setResearchAreas(new HashSet<>(researchAreas)); - final Project project = Project.builder().title("Title").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + final Project project = Project.builder() + .title("Title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); final FileDescription fileDescription = new FileDescription(); final FileReference fsaThesis = new FileReference(); fsaThesis.setFileDescription(fileDescription); @@ -86,4 +95,4 @@ public class ReviewerSupportMailerTest { generalSystemSettings.setReviewerSupportMail("support@test.se"); when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(generalSystemSettings); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewingNotificationsTest.java b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewingNotificationsTest.java index 269b02937c..340f3e2529 100644 --- a/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewingNotificationsTest.java +++ b/view/src/test/java/se/su/dsv/scipro/crosscutting/ReviewingNotificationsTest.java @@ -1,6 +1,12 @@ package se.su.dsv.scipro.crosscutting; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; + import com.google.common.eventbus.EventBus; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,21 +26,18 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalRequestedEvent; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) public class ReviewingNotificationsTest { + @Mock private EventBus eventBus; + @Mock private NotificationController notificationController; + @InjectMocks private ReviewingNotifications reviewingNotifications; + private Project project; private FinalSeminarApproval finalSeminarApproval; private RoughDraftApproval roughDraftApproval; @@ -61,16 +64,26 @@ public class ReviewingNotificationsTest { @Test public void sends_out_notification_when_a_final_seminar_approval_request_is_sent() { - reviewingNotifications.onFinalSeminarApprovalRequest(new FinalSeminarApprovalRequestEvent(finalSeminarApproval)); + reviewingNotifications.onFinalSeminarApprovalRequest( + new FinalSeminarApprovalRequestEvent(finalSeminarApproval) + ); - verify(notificationController).notifyProject(eq(project), eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), anyNotificationSource()); + verify(notificationController).notifyProject( + eq(project), + eq(ProjectEvent.Event.FINAL_SEMINAR_APPROVAL_REQUESTED), + anyNotificationSource() + ); } @Test public void sends_out_notification_when_a_rough_draft_approval_request_is_sent() { reviewingNotifications.onRoughDraftApprovalRequest(new RoughDraftApprovalRequestedEvent(roughDraftApproval)); - verify(notificationController).notifyProject(eq(project), eq(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED), anyNotificationSource()); + verify(notificationController).notifyProject( + eq(project), + eq(ProjectEvent.Event.ROUGH_DRAFT_APPROVAL_REQUESTED), + anyNotificationSource() + ); } private static NotificationSource anyNotificationSource() { diff --git a/view/src/test/java/se/su/dsv/scipro/data/DetachableServiceModelTest.java b/view/src/test/java/se/su/dsv/scipro/data/DetachableServiceModelTest.java index 8a3dfb1ff5..03f3114ec6 100644 --- a/view/src/test/java/se/su/dsv/scipro/data/DetachableServiceModelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/data/DetachableServiceModelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.data; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.model.IModel; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -8,14 +12,12 @@ import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.system.DomainObject; import se.su.dsv.scipro.system.GenericService; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class DetachableServiceModelTest { + @Mock private GenericService service; + @Mock private DomainObject domainObject; diff --git a/view/src/test/java/se/su/dsv/scipro/dataproviders/FilteredDataProviderTest.java b/view/src/test/java/se/su/dsv/scipro/dataproviders/FilteredDataProviderTest.java index 68a4903be7..6aaaa9e6bb 100644 --- a/view/src/test/java/se/su/dsv/scipro/dataproviders/FilteredDataProviderTest.java +++ b/view/src/test/java/se/su/dsv/scipro/dataproviders/FilteredDataProviderTest.java @@ -1,18 +1,5 @@ package se.su.dsv.scipro.dataproviders; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.FilteredService; - -import java.util.Collections; -import java.util.Iterator; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.eq; @@ -20,13 +7,26 @@ import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.Collections; +import java.util.Iterator; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.FilteredService; +import se.su.dsv.scipro.system.Pageable; + @ExtendWith(MockitoExtension.class) public class FilteredDataProviderTest { + @Mock private FilteredService filteredService; private String filter; - private FilteredDataProvider provider; + private FilteredDataProvider provider; @BeforeEach public void setUp() throws Exception { @@ -45,7 +45,9 @@ public class FilteredDataProviderTest { @Test public void iterator() { DomainObject domainObject = mock(DomainObject.class); - when(filteredService.findAll(eq(filter), isA(Pageable.class))).thenReturn(Collections.singletonList(domainObject)); + when(filteredService.findAll(eq(filter), isA(Pageable.class))).thenReturn( + Collections.singletonList(domainObject) + ); Iterator iterator = provider.iterator(0, Integer.MAX_VALUE); assertEquals(domainObject, iterator.next()); diff --git a/view/src/test/java/se/su/dsv/scipro/dataproviders/GenericDataProviderTest.java b/view/src/test/java/se/su/dsv/scipro/dataproviders/GenericDataProviderTest.java index 0d3f908801..e20b73ec83 100644 --- a/view/src/test/java/se/su/dsv/scipro/dataproviders/GenericDataProviderTest.java +++ b/view/src/test/java/se/su/dsv/scipro/dataproviders/GenericDataProviderTest.java @@ -1,26 +1,26 @@ package se.su.dsv.scipro.dataproviders; -import org.apache.wicket.model.IModel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.system.DomainObject; -import se.su.dsv.scipro.system.GenericService; - -import java.util.Collections; -import java.util.Iterator; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.Collections; +import java.util.Iterator; +import org.apache.wicket.model.IModel; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import se.su.dsv.scipro.system.DomainObject; +import se.su.dsv.scipro.system.GenericService; +import se.su.dsv.scipro.system.Pageable; + @ExtendWith(MockitoExtension.class) public class GenericDataProviderTest { + @Mock private GenericService genericService; diff --git a/view/src/test/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapperTest.java b/view/src/test/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapperTest.java index 58fa11a94b..74f3ab81fb 100644 --- a/view/src/test/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapperTest.java +++ b/view/src/test/java/se/su/dsv/scipro/datatables/AjaxCheckboxWrapperTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.datatables; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; @@ -8,8 +10,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class AjaxCheckboxWrapperTest extends SciProTest { Panel panel; @@ -30,11 +30,11 @@ public class AjaxCheckboxWrapperTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new AjaxCheckboxWrapper("panel", Model.of(true)) { - @Override - public void onChange(AjaxRequestTarget target, boolean selected) { + panel = tester.startComponentInPage( + new AjaxCheckboxWrapper("panel", Model.of(true)) { + @Override + public void onChange(AjaxRequestTarget target, boolean selected) {} } - - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/datatables/project/ProjectDataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/datatables/project/ProjectDataPanelTest.java index 4c1961be0c..f11fded33a 100644 --- a/view/src/test/java/se/su/dsv/scipro/datatables/project/ProjectDataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/datatables/project/ProjectDataPanelTest.java @@ -1,61 +1,67 @@ -package se.su.dsv.scipro.datatables.project; - -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.datatables.AjaxCheckboxWrapper; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectService; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.security.auth.roles.Roles; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.test.ObjectMother; - -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.Mockito.*; - -public class ProjectDataPanelTest extends SciProTest { - - private ProjectDataPanel panel; - - @Test - public void renders() throws Exception { - startPanel(); - } - - @Test - public void clicking_checkbox_calls_inactivate_service_method() { - mockProject(); - startPanel(); - inactivateProject(); - } - - @Test - public void admins_should_not_be_able_to_create_projects() { - setRoles(Roles.ADMIN); - startPanel(); - tester.assertInvisible(path(panel, "newLink")); - } - - private void inactivateProject() { - panel.visitChildren(AjaxCheckboxWrapper.class, (object, visit) -> { - tester.executeAjaxEvent(path(object.getPageRelativePath(), AjaxCheckboxWrapper.CHECKBOX), "click"); - verify(projectService).toggleActiveStatus(any(Project.class), eq(false)); - visit.stop(); - }); - } - - private void mockProject() { - Project project = Project.builder().title("title").projectType(new ProjectType(DegreeType.BACHELOR, "bach", "b")).startDate(LocalDate.now()).projectStatus(ProjectStatus.ACTIVE).build(); - project.setHeadSupervisor(ObjectMother.SOME_USER); - when(projectService.findAll(any(ProjectService.Filter.class), any(Pageable.class))).thenReturn(Collections.singletonList(project)); - when(projectService.count(any(ProjectService.Filter.class))).thenReturn(1L); - } - - private void startPanel() { - panel = tester.startComponentInPage(new ProjectDataPanel("id")); - } -} +package se.su.dsv.scipro.datatables.project; + +import static org.mockito.Mockito.*; + +import java.time.LocalDate; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.datatables.AjaxCheckboxWrapper; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectService; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.security.auth.roles.Roles; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.test.ObjectMother; + +public class ProjectDataPanelTest extends SciProTest { + + private ProjectDataPanel panel; + + @Test + public void renders() throws Exception { + startPanel(); + } + + @Test + public void clicking_checkbox_calls_inactivate_service_method() { + mockProject(); + startPanel(); + inactivateProject(); + } + + @Test + public void admins_should_not_be_able_to_create_projects() { + setRoles(Roles.ADMIN); + startPanel(); + tester.assertInvisible(path(panel, "newLink")); + } + + private void inactivateProject() { + panel.visitChildren(AjaxCheckboxWrapper.class, (object, visit) -> { + tester.executeAjaxEvent(path(object.getPageRelativePath(), AjaxCheckboxWrapper.CHECKBOX), "click"); + verify(projectService).toggleActiveStatus(any(Project.class), eq(false)); + visit.stop(); + }); + } + + private void mockProject() { + Project project = Project.builder() + .title("title") + .projectType(new ProjectType(DegreeType.BACHELOR, "bach", "b")) + .startDate(LocalDate.now()) + .projectStatus(ProjectStatus.ACTIVE) + .build(); + project.setHeadSupervisor(ObjectMother.SOME_USER); + when(projectService.findAll(any(ProjectService.Filter.class), any(Pageable.class))).thenReturn( + Collections.singletonList(project) + ); + when(projectService.count(any(ProjectService.Filter.class))).thenReturn(1L); + } + + private void startPanel() { + panel = tester.startComponentInPage(new ProjectDataPanel("id")); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/datatables/target/EditTargetPanelTest.java b/view/src/test/java/se/su/dsv/scipro/datatables/target/EditTargetPanelTest.java index 6b2048fa42..43f2182259 100644 --- a/view/src/test/java/se/su/dsv/scipro/datatables/target/EditTargetPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/datatables/target/EditTargetPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.datatables.target; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.model.Model; @@ -13,10 +17,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditTargetPanelTest extends SciProTest { private ProjectType bachelor; @@ -31,8 +31,9 @@ public class EditTargetPanelTest extends SciProTest { applicationPeriod.addProjectType(bachelor); employee = User.builder().firstName("Kalle").lastName("Testare").emailAddress("kalle@test.com").build(); - when(targetService.findOne(applicationPeriod, employee, bachelor)) - .thenReturn(new Target(employee, applicationPeriod, bachelor)); + when(targetService.findOne(applicationPeriod, employee, bachelor)).thenReturn( + new Target(employee, applicationPeriod, bachelor) + ); } @Test @@ -64,9 +65,11 @@ public class EditTargetPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new EditTargetPanel("id", Model.of(applicationPeriod), Model.of(employee), Model.of(bachelor), true) { - @Override - public void update(AjaxRequestTarget ajaxTarget, User e) {} - }); + panel = tester.startComponentInPage( + new EditTargetPanel("id", Model.of(applicationPeriod), Model.of(employee), Model.of(bachelor), true) { + @Override + public void update(AjaxRequestTarget ajaxTarget, User e) {} + } + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/files/FileDescriptionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/files/FileDescriptionPanelTest.java index 404255abf1..61f47ef197 100644 --- a/view/src/test/java/se/su/dsv/scipro/files/FileDescriptionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/files/FileDescriptionPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.files; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static se.su.dsv.scipro.files.FileDescriptionPanel.FILE; + import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,9 +17,6 @@ import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static se.su.dsv.scipro.files.FileDescriptionPanel.FILE; - @ExtendWith(MockitoExtension.class) public class FileDescriptionPanelTest extends SciProTest { diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanelTest.java index 6cd1768701..cde85c9bfa 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarDataPanelTest.java @@ -21,7 +21,6 @@ public class AdminFinalSeminarDataPanelTest extends SciProTest { @Test public void testContainsDataTablePanel() { - tester.assertComponent(path(panel.getId(), AdminFinalSeminarDataPanel.DATA_TABEL), ExportableDataPanel.class); + tester.assertComponent(path(panel.getId(), AdminFinalSeminarDataPanel.DATA_TABEL), ExportableDataPanel.class); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPageTest.java index 79147e7456..d0bbbb4cbe 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarExemptionPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import java.util.Collections; +import java.util.List; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -7,14 +9,11 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.ExportableDataPanel; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; - -import java.util.Collections; -import java.util.List; +import se.su.dsv.scipro.system.Pageable; @ExtendWith(MockitoExtension.class) public class AdminFinalSeminarExemptionPageTest extends SciProTest { @@ -23,8 +22,15 @@ public class AdminFinalSeminarExemptionPageTest extends SciProTest { public void setUp() throws Exception { Project project = new Project(); List page = Collections.singletonList(project); - Mockito.when(projectService.findAll(ArgumentMatchers.any(ProjectService.Filter.class), ArgumentMatchers.any(Pageable.class))).thenReturn(page); - Mockito.when(projectService.count(ArgumentMatchers.any(ProjectService.Filter.class))).thenReturn( (long) page.size()); + Mockito.when( + projectService.findAll( + ArgumentMatchers.any(ProjectService.Filter.class), + ArgumentMatchers.any(Pageable.class) + ) + ).thenReturn(page); + Mockito.when(projectService.count(ArgumentMatchers.any(ProjectService.Filter.class))).thenReturn( + (long) page.size() + ); tester.startPage(AdminFinalSeminarExemptionPage.class); } @@ -48,4 +54,4 @@ public class AdminFinalSeminarExemptionPageTest extends SciProTest { public void testContainsFeedbackPanel() { tester.assertComponent(AdminFinalSeminarExemptionPage.FEEDBACK, FeedbackPanel.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPageTest.java index a3571d7ce0..b18316af71 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminFinalSeminarPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminFinalSeminarPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPageTest.java index 706b5aebf8..310a1f1f09 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/AdminFinalSeminarSettingsPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import static se.su.dsv.scipro.finalseminar.AdminFinalSeminarSettingsPage.*; + +import java.util.Arrays; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.ProjectType; -import java.util.Arrays; -import java.util.List; - -import static se.su.dsv.scipro.finalseminar.AdminFinalSeminarSettingsPage.*; - public class AdminFinalSeminarSettingsPageTest extends SciProTest { AdminFinalSeminarSettingsPage page; @@ -76,28 +75,40 @@ public class AdminFinalSeminarSettingsPageTest extends SciProTest { @Test public void testInnerFormContainsMaxOpponentsField() { for (int i = 0; i < levels.size(); i++) { - tester.assertComponent(path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MAX_OPPONENTS), RequiredTextField.class); + tester.assertComponent( + path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MAX_OPPONENTS), + RequiredTextField.class + ); } } @Test public void testInnerFormContainsMaxParticipantsField() { for (int i = 0; i < levels.size(); i++) { - tester.assertComponent(path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MAX_PARTICIPANTS), RequiredTextField.class); + tester.assertComponent( + path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MAX_PARTICIPANTS), + RequiredTextField.class + ); } } @Test public void testInnerFormContainsMinParticipantsField() { for (int i = 0; i < levels.size(); i++) { - tester.assertComponent(path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MIN_PARTICIPANTS), RequiredTextField.class); + tester.assertComponent( + path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MIN_PARTICIPANTS), + RequiredTextField.class + ); } } @Test public void testInnerFormContainsMinOpponentsField() { for (int i = 0; i < levels.size(); i++) { - tester.assertComponent(path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MIN_OPPONENTS), RequiredTextField.class); + tester.assertComponent( + path(SETTINGS_FORM, PROJECT_TYPE_LIST, i, PROJECT_TYPE_FORM, SEMINAR_MIN_OPPONENTS), + RequiredTextField.class + ); } } @@ -114,7 +125,6 @@ public class AdminFinalSeminarSettingsPageTest extends SciProTest { @Test public void testFormContainsCreateDaysAhead() { assertFormComponent(SEMINAR_CREATE_DAYS_AHEAD, RequiredTextField.class); - } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/AttendingPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/AttendingPanelTest.java index f7892f89f4..c1dcdccaec 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/AttendingPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/AttendingPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.Model; @@ -14,16 +23,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.*; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AttendingPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @@ -34,7 +33,11 @@ public class AttendingPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - project = Project.builder().title("some title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); + project = Project.builder() + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); project.setId(9L); user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); @@ -61,7 +64,12 @@ public class AttendingPanelTest extends SciProTest { List oppositions = List.of(finalSeminarOpposition); - when(finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType(isA(ProjectType.class), isA(User.class))).thenReturn(oppositions); + when( + finalSeminarService.findFinalSeminarOppositionsByOpponentAndProjectType( + isA(ProjectType.class), + isA(User.class) + ) + ).thenReturn(oppositions); startPanel(); @@ -91,12 +99,17 @@ public class AttendingPanelTest extends SciProTest { List participations = List.of(finalSeminarActiveParticipation); when(finalSeminarService.findUserParticipating(isA(Project.class), isA(User.class))).thenReturn(participations); - when(finalSeminarActiveParticipationService.findByFinalSeminarUser(finalSeminar, unregisteredUser )).thenReturn(finalSeminarActiveParticipation); + when(finalSeminarActiveParticipationService.findByFinalSeminarUser(finalSeminar, unregisteredUser)).thenReturn( + finalSeminarActiveParticipation + ); startPanel(); tester.assertModelValue(path(panel.getId(), "wmc", "participations"), participations); - tester.assertComponent(path(panel.getId(), "wmc", "participations", "0", "seminarLink"), BookmarkablePageLink.class); + tester.assertComponent( + path(panel.getId(), "wmc", "participations", "0", "seminarLink"), + BookmarkablePageLink.class + ); tester.assertInvisible(path(panel.getId(), "noParticipations")); } @@ -118,7 +131,9 @@ public class AttendingPanelTest extends SciProTest { finalSeminar.addActiveParticipant(participation); when(finalSeminarService.findUserParticipating(project, user)).thenReturn(List.of(participation)); - when(finalSeminarActiveParticipationService.findByFinalSeminarUser(finalSeminar, user)).thenReturn(participation); + when(finalSeminarActiveParticipationService.findByFinalSeminarUser(finalSeminar, user)).thenReturn( + participation + ); startPanel(); tester.clickLink(path(panel, "wmc", "participations", 0, "remove")); @@ -132,6 +147,4 @@ public class AttendingPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new AttendingPanel("panel", Model.of(project))); } - } - diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanelTest.java index 70c92fb5cb..2a23a02d9b 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/DownloadPdfReportPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.model.Model; @@ -18,11 +22,6 @@ import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.test.SeminarBuilder; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZonedDateTime; -import java.util.*; - public class DownloadPdfReportPanelTest extends SciProTest { private static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @@ -63,13 +62,19 @@ public class DownloadPdfReportPanelTest extends SciProTest { @Test public void has_label_for_pdf() { submitAndStartPanel(); - tester.assertComponent(path(panel, DownloadPdfReportPanel.DOWNLOAD_PDF, DownloadPdfReportPanel.PDF_LABEL), Label.class); + tester.assertComponent( + path(panel, DownloadPdfReportPanel.DOWNLOAD_PDF, DownloadPdfReportPanel.PDF_LABEL), + Label.class + ); } @Test public void shows_date_for_report_creation() { submitAndStartPanel(); - tester.assertModelValue(path(panel, DownloadPdfReportPanel.DOWNLOAD_PDF, DownloadPdfReportPanel.PDF_UPLOAD_DATE), gradingReport.getDateCreated()); + tester.assertModelValue( + path(panel, DownloadPdfReportPanel.DOWNLOAD_PDF, DownloadPdfReportPanel.PDF_UPLOAD_DATE), + gradingReport.getDateCreated() + ); } private void submitAndStartPanel() { @@ -78,24 +83,32 @@ public class DownloadPdfReportPanelTest extends SciProTest { } private void prepareReports() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(BACHELOR, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + BACHELOR, + LocalDate.of(2024, Month.JANUARY, 1) + ); List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(0) .description("Description") .descriptionEn("DescriptionEn") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description("Description") .descriptionEn("DescriptionEn") - .build()); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + .build() + ); + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(2) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); gradingReportTemplate.addProjectCriterion("title", "titleEn", 0, gradingCriterionPointTemplates); gradingReport = gradingReportTemplate.createOppositionReport(seminar.getOppositions().iterator().next()); gradingReport.setThesisSummary("some summary"); @@ -105,6 +118,13 @@ public class DownloadPdfReportPanelTest extends SciProTest { } private void startPanel(final FinalSeminar seminar) { - panel = tester.startComponentInPage(new DownloadPdfReportPanel("panel", Model.of(seminar), Model.of(gradingReport), new OppositionReportPdfResource(Model.of(gradingReport)))); + panel = tester.startComponentInPage( + new DownloadPdfReportPanel( + "panel", + Model.of(seminar), + Model.of(gradingReport), + new OppositionReportPdfResource(Model.of(gradingReport)) + ) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPageTest.java index ac26e8d37f..e2843b209d 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/FinalSeminarProjectListPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class FinalSeminarProjectListPageTest extends PageTest { + @Override protected Class getPage() { return FinalSeminarProjectListPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanelTest.java index dba8c05132..e6f8a1730f 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/MoveFinalSeminarPanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -15,15 +22,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.util.Either; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class MoveFinalSeminarPanelTest extends SciProTest { + public static final String panel = "id"; private FinalSeminar seminar; @@ -31,14 +31,19 @@ public class MoveFinalSeminarPanelTest extends SciProTest { public void setUp() throws Exception { prepareFinalSeminar(); tester.startComponentInPage(new MoveFinalSeminarPanel(panel, Model.of(seminar))); - when(finalSeminarService.move(any(FinalSeminar.class), any(LocalDateTime.class))) - .thenReturn(Either.right(seminar)); + when(finalSeminarService.move(any(FinalSeminar.class), any(LocalDateTime.class))).thenReturn( + Either.right(seminar) + ); } private void prepareFinalSeminar() { ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor"); bachelor.getProjectTypeSettings().setMinOpponentsOnFinalSeminar(2); - User supervisor = User.builder().firstName("Hasse").lastName("Handledare").emailAddress("hasse@example.com").build(); + User supervisor = User.builder() + .firstName("Hasse") + .lastName("Handledare") + .emailAddress("hasse@example.com") + .build(); DomainObjects.injectId(supervisor, 234L); Project project = new Project(); project.setId(1L); @@ -64,10 +69,14 @@ public class MoveFinalSeminarPanelTest extends SciProTest { } private void verifyNotificationSent(SeminarEvent.Event event) { - verify(notificationController).notifySeminar(ArgumentMatchers.eq(seminar), ArgumentMatchers.eq(event), any(NotificationSource.class)); + verify(notificationController).notifySeminar( + ArgumentMatchers.eq(seminar), + ArgumentMatchers.eq(event), + any(NotificationSource.class) + ); } private Date calculateDateByInterval(int numberOfDays) { return Date.from(ZonedDateTime.now().plusDays(numberOfDays).toInstant()); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/OppositionReportPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/OppositionReportPageTest.java index cafe8f9928..6e9d239fa4 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/OppositionReportPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/OppositionReportPageTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.ArgumentMatchers.eq; +import static se.su.dsv.scipro.finalseminar.OppositionReportPage.FILL_OUT_REPORT; +import static se.su.dsv.scipro.finalseminar.OppositionReportPage.THESIS_SUMMARY; + +import java.time.LocalDate; +import java.time.Month; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.markup.html.border.Border; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -28,15 +36,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.mockito.ArgumentMatchers.eq; -import static se.su.dsv.scipro.finalseminar.OppositionReportPage.FILL_OUT_REPORT; -import static se.su.dsv.scipro.finalseminar.OppositionReportPage.THESIS_SUMMARY; - public class OppositionReportPageTest extends SciProTest { public static final String CRITERION_DESCRIPTION = "For 1 point: Be nice to your supervisor"; @@ -52,8 +51,18 @@ public class OppositionReportPageTest extends SciProTest { @BeforeEach public void prepareOppositionReport() { bachelor = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); - Project opponentsProject = Project.builder().title("Foo").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(User.builder().firstName("Bob").lastName("Kelso").emailAddress("bob@example.com").build()).build(); - Project projectToOppose = Project.builder().title("Foo").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(User.builder().firstName("Bob").lastName("Kelso").emailAddress("bob@example.com").build()).build(); + Project opponentsProject = Project.builder() + .title("Foo") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(User.builder().firstName("Bob").lastName("Kelso").emailAddress("bob@example.com").build()) + .build(); + Project projectToOppose = Project.builder() + .title("Foo") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(User.builder().firstName("Bob").lastName("Kelso").emailAddress("bob@example.com").build()) + .build(); DomainObjects.injectId(opponentsProject, 666L); DomainObjects.injectId(projectToOppose, 777L); user = new UserBuilder().create(); @@ -61,7 +70,9 @@ public class OppositionReportPageTest extends SciProTest { finalSeminarOpposition = createOpposition(opponentsProject, finalSeminar); Mockito.when(projectService.findOne(ArgumentMatchers.anyLong())).thenReturn(opponentsProject); - Mockito.when(projectService.isPartOfProject(eq(opponentsProject), ArgumentMatchers.any(User.class))).thenReturn(true); + Mockito.when(projectService.isPartOfProject(eq(opponentsProject), ArgumentMatchers.any(User.class))).thenReturn( + true + ); Mockito.when(finalSeminarService.findByProject(opponentsProject)).thenReturn(finalSeminar); } @@ -109,7 +120,10 @@ public class OppositionReportPageTest extends SciProTest { public void opposition_report_has_thesis_summary_text_area() { mockReport(bachelor); startOppositionPage(); - tester.assertComponent(path(FILL_OUT_REPORT, FillOutReportPanel.FORM, FILL_OUT_REPORT + "_" + Border.BODY, THESIS_SUMMARY), TextArea.class); + tester.assertComponent( + path(FILL_OUT_REPORT, FillOutReportPanel.FORM, FILL_OUT_REPORT + "_" + Border.BODY, THESIS_SUMMARY), + TextArea.class + ); } @Test @@ -153,14 +167,18 @@ public class OppositionReportPageTest extends SciProTest { } private GradingReportTemplate createTemplate(ProjectType bachelor) { - GradingReportTemplate reportTemplate = new GradingReportTemplate(bachelor, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate reportTemplate = new GradingReportTemplate( + bachelor, + LocalDate.of(2024, Month.JANUARY, 1) + ); List gradingCriterionPointTemplates = new ArrayList<>(); - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(1) .description(CRITERION_DESCRIPTION) .descriptionEn(CRITERION_DESCRIPTION) - .build()); + .build() + ); reportTemplate.addProjectCriterion(CRITERTION_TITLE, CRITERTION_TITLE, 1, gradingCriterionPointTemplates); return reportTemplate; } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanelTest.java index 60fc095f4d..94870ba641 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/OverviewSeminarPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -16,9 +18,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Date; - @ExtendWith(MockitoExtension.class) public class OverviewSeminarPanelTest extends SciProTest { @@ -28,11 +27,11 @@ public class OverviewSeminarPanelTest extends SciProTest { public void setUp() throws Exception { User user = new UserBuilder().setFirstName("author").setLastName("1").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); FinalSeminar finalSeminar = new FinalSeminar(); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanelTest.java index 1448823f4b..654a665932 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectActiveParticipationListPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,13 +14,8 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import static org.mockito.Mockito.when; - public class ProjectActiveParticipationListPanelTest extends SciProTest { + private Project bills; private FinalSeminarActiveParticipation billsParticipation; @@ -37,11 +37,20 @@ public class ProjectActiveParticipationListPanelTest extends SciProTest { @Test public void lists_correct_oppositions() { - ProjectActiveParticipationListPanel panel = tester.startComponentInPage(new ProjectActiveParticipationListPanel("id", Model.of(bills))); - tester.assertModelValue(path(panel, "authors", 0, "participations"), Collections.singletonList(billsParticipation)); + ProjectActiveParticipationListPanel panel = tester.startComponentInPage( + new ProjectActiveParticipationListPanel("id", Model.of(bills)) + ); + tester.assertModelValue( + path(panel, "authors", 0, "participations"), + Collections.singletonList(billsParticipation) + ); } - private FinalSeminarActiveParticipation newActiveParticipation(final User author, final FinalSeminar finalSeminar, final Project authors) { + private FinalSeminarActiveParticipation newActiveParticipation( + final User author, + final FinalSeminar finalSeminar, + final Project authors + ) { FinalSeminarActiveParticipation finalSeminarActiveParticipation = new FinalSeminarActiveParticipation(); finalSeminarActiveParticipation.setFinalSeminar(finalSeminar); finalSeminarActiveParticipation.setUser(author); @@ -50,8 +59,12 @@ public class ProjectActiveParticipationListPanelTest extends SciProTest { } private User newUser(final long id) { - User user = User.builder().firstName("Spongebob").lastName("Squarepants").emailAddress("spongebob@example.com").build(); + User user = User.builder() + .firstName("Spongebob") + .lastName("Squarepants") + .emailAddress("spongebob@example.com") + .build(); user.setId(id); return user; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanelTest.java index bcef02f1db..477939e717 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectDetailsPanelTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,8 +9,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - public class ProjectDetailsPanelTest extends SciProTest { ProjectDetailsPanel panel; @@ -25,4 +24,4 @@ public class ProjectDetailsPanelTest extends SciProTest { public void renders() throws Exception { panel = tester.startComponentInPage(new ProjectDetailsPanel("id", Model.of(project))); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPageTest.java index 3a931576b2..e02a37d83e 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarDetailsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.Test; @@ -15,9 +17,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Date; - public class ProjectFinalSeminarDetailsPageTest extends SciProTest { @Test @@ -39,7 +38,7 @@ public class ProjectFinalSeminarDetailsPageTest extends SciProTest { assertRendering(AdminStartPage.class); } - private PageParameters getPageParameters( ) { + private PageParameters getPageParameters() { PageParameters parameters = new PageParameters(); parameters.set(PageParameterKeys.MAP.get(Project.class), "1"); return parameters; @@ -58,7 +57,12 @@ public class ProjectFinalSeminarDetailsPageTest extends SciProTest { projectType.setProjectTypeSettings(projectTypeSettings); User supervisor = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); - Project project = Project.builder().title("bla").projectType(projectType).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + Project project = Project.builder() + .title("bla") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); project.setId(23542L); final FinalSeminar finalSeminar = new FinalSeminar(); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPageTest.java index a87f526438..de611bf6f8 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectFinalSeminarPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,8 +15,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - public class ProjectFinalSeminarPageTest extends PageTest { ProjectFinalSeminarPage page; @@ -26,22 +25,24 @@ public class ProjectFinalSeminarPageTest extends PageTest { User student = new UserBuilder().setFirstName("author").setLastName("1").create(); User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); Mockito.when(projectService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(project); - Mockito.when(projectService.isPartOfProject(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class))).thenReturn(true); + Mockito.when( + projectService.isPartOfProject(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class)) + ).thenReturn(true); page = tester.startPage(ProjectFinalSeminarPage.class, getPageParameters()); } @Override protected Class getPage() { - return ProjectFinalSeminarPage.class; //To change body of implemented methods use File | Settings | File Templates. + return ProjectFinalSeminarPage.class; //To change body of implemented methods use File | Settings | File Templates. } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPageTest.java index fc977d606a..0f597eeb4d 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionPageTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.Matchers.hasItem; + +import java.io.Serializable; +import java.time.LocalDate; +import java.util.Collections; +import java.util.Date; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.feedback.FeedbackMessage; @@ -13,10 +20,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; @@ -24,14 +31,6 @@ import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.PageParameterKeys; -import java.io.Serializable; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import static org.hamcrest.Matchers.hasItem; - public class ProjectOppositionPageTest extends PageTest { private Project project; @@ -46,22 +45,33 @@ public class ProjectOppositionPageTest extends PageTest { User supervisor = new UserBuilder().setFirstName("Hej").setLastName("Svej").create(); project = Project.builder() - .title("Wanted Project") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("Wanted Project") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); - Project unwantedProject = Project.builder().title("Some unwanted title").projectType(new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description")).startDate(LocalDate.now()).build(); + Project unwantedProject = Project.builder() + .title("Some unwanted title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description")) + .startDate(LocalDate.now()) + .build(); unwantedProject.setId(9L); finalSeminar.setProject(unwantedProject); finalSeminar.setStartDate(new Date()); PageParameters pageParameters = new PageParameters(); pageParameters.add(PageParameterKeys.MAP.get(Project.class), "1"); Mockito.when(projectService.findOne(ArgumentMatchers.any(Long.class))).thenReturn(project); - Mockito.when(projectService.isPartOfProject(ArgumentMatchers.any(Project.class), ArgumentMatchers.any(User.class))).thenReturn(true); - Mockito.when(finalSeminarService.findAll(ArgumentMatchers.any(FinalSeminarService.Filter.class), ArgumentMatchers.any(Pageable.class))).thenReturn(Collections.singletonList(finalSeminar)); + Mockito.when( + projectService.isPartOfProject(ArgumentMatchers.any(Project.class), ArgumentMatchers.any(User.class)) + ).thenReturn(true); + Mockito.when( + finalSeminarService.findAll( + ArgumentMatchers.any(FinalSeminarService.Filter.class), + ArgumentMatchers.any(Pageable.class) + ) + ).thenReturn(Collections.singletonList(finalSeminar)); Mockito.when(finalSeminarService.count(ArgumentMatchers.any(FinalSeminarService.Filter.class))).thenReturn(1L); Mockito.when(finalSeminarService.canOppose(user, finalSeminar, project)).thenReturn(Either.right(null)); Mockito.when(finalSeminarService.canActiveParticipate(user, finalSeminar)).thenReturn(Either.right(null)); @@ -70,63 +80,91 @@ public class ProjectOppositionPageTest extends PageTest { @Test public void clickingOpposeUpdatesCorrectProject() { - Mockito.when(finalSeminarService.attemptAddOpposition(user, finalSeminar, project)).thenReturn(Either.right(null)); + Mockito.when(finalSeminarService.attemptAddOpposition(user, finalSeminar, project)).thenReturn( + Either.right(null) + ); final Page page = tester.getLastRenderedPage(); - page.visitChildren(OpposeColumnPanel.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - tester.clickLink(path(component.getPageRelativePath(), OpposeColumnPanel.LINK)); - Mockito.verify(finalSeminarService).attemptAddOpposition(user, finalSeminar, project); - visit.stop(); + page.visitChildren( + OpposeColumnPanel.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + tester.clickLink(path(component.getPageRelativePath(), OpposeColumnPanel.LINK)); + Mockito.verify(finalSeminarService).attemptAddOpposition(user, finalSeminar, project); + visit.stop(); + } } - }); + ); } @Test public void clicking_oppose_generates_feedback() { - Mockito.when(finalSeminarService.attemptAddOpposition(user, finalSeminar, project)).thenReturn(Either.right(null)); + Mockito.when(finalSeminarService.attemptAddOpposition(user, finalSeminar, project)).thenReturn( + Either.right(null) + ); final Page page = tester.getLastRenderedPage(); - page.visitChildren(OpposeColumnPanel.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - tester.clickLink(path(component.getPageRelativePath(), OpposeColumnPanel.LINK)); + page.visitChildren( + OpposeColumnPanel.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + tester.clickLink(path(component.getPageRelativePath(), OpposeColumnPanel.LINK)); - List messages = tester.getMessages(FeedbackMessage.SUCCESS); - MatcherAssert.assertThat(messages, hasItem(StringContains.containsString(page.getString("oppositionAdded", Model.of(finalSeminar))))); - visit.stop(); + List messages = tester.getMessages(FeedbackMessage.SUCCESS); + MatcherAssert.assertThat( + messages, + hasItem( + StringContains.containsString(page.getString("oppositionAdded", Model.of(finalSeminar))) + ) + ); + visit.stop(); + } } - }); + ); } @Test public void clickingParticipateUpdatesCorrectProject() { - Mockito.when(finalSeminarService.attemptAddActiveParticipation(user, finalSeminar, project)) - .thenReturn(Either.right(new FinalSeminarActiveParticipation())); + Mockito.when(finalSeminarService.attemptAddActiveParticipation(user, finalSeminar, project)).thenReturn( + Either.right(new FinalSeminarActiveParticipation()) + ); final Page page = tester.getLastRenderedPage(); - page.visitChildren(ParticipateColumnPanel.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - tester.clickLink(path(component.getPageRelativePath(), ParticipateColumnPanel.LINK)); - Mockito.verify(finalSeminarService).attemptAddActiveParticipation(user, finalSeminar, project); - visit.stop(); + page.visitChildren( + ParticipateColumnPanel.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + tester.clickLink(path(component.getPageRelativePath(), ParticipateColumnPanel.LINK)); + Mockito.verify(finalSeminarService).attemptAddActiveParticipation(user, finalSeminar, project); + visit.stop(); + } } - }); + ); } @Test public void clicking_participate_generates_feedback() { - Mockito.when(finalSeminarService.attemptAddActiveParticipation(user, finalSeminar, project)) - .thenReturn(Either.right(new FinalSeminarActiveParticipation())); + Mockito.when(finalSeminarService.attemptAddActiveParticipation(user, finalSeminar, project)).thenReturn( + Either.right(new FinalSeminarActiveParticipation()) + ); final Page page = tester.getLastRenderedPage(); - page.visitChildren(ParticipateColumnPanel.class, new IVisitor() { - @Override - public void component(Component component, IVisit visit) { - tester.clickLink(path(component.getPageRelativePath(), ParticipateColumnPanel.LINK)); - List messages = tester.getMessages(FeedbackMessage.SUCCESS); - MatcherAssert.assertThat(messages, hasItem(StringContains.containsString(page.getString("participationAdded", Model.of(finalSeminar))))); - visit.stop(); + page.visitChildren( + ParticipateColumnPanel.class, + new IVisitor() { + @Override + public void component(Component component, IVisit visit) { + tester.clickLink(path(component.getPageRelativePath(), ParticipateColumnPanel.LINK)); + List messages = tester.getMessages(FeedbackMessage.SUCCESS); + MatcherAssert.assertThat( + messages, + hasItem( + StringContains.containsString(page.getString("participationAdded", Model.of(finalSeminar))) + ) + ); + visit.stop(); + } } - }); + ); } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanelTest.java index be60a84f4a..e522a9e068 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/ProjectOppositionsListPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,12 +14,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - public class ProjectOppositionsListPanelTest extends SciProTest { private Project bills; @@ -39,11 +38,17 @@ public class ProjectOppositionsListPanelTest extends SciProTest { @Test public void lists_correct_oppositions() { - ProjectOppositionsListPanel panel = tester.startComponentInPage(new ProjectOppositionsListPanel("id", Model.of(bills))); + ProjectOppositionsListPanel panel = tester.startComponentInPage( + new ProjectOppositionsListPanel("id", Model.of(bills)) + ); tester.assertModelValue(path(panel, "oppositions"), Collections.singletonList(billsOpposition)); } - private FinalSeminarOpposition newOpposition(final User author, final FinalSeminar finalSeminar, final Project authors) { + private FinalSeminarOpposition newOpposition( + final User author, + final FinalSeminar finalSeminar, + final Project authors + ) { FinalSeminarOpposition finalSeminarOpposition = new FinalSeminarOpposition(); finalSeminarOpposition.setFinalSeminar(finalSeminar); finalSeminarOpposition.setUser(author); @@ -52,8 +57,12 @@ public class ProjectOppositionsListPanelTest extends SciProTest { } private User newUser(final long id) { - User user = User.builder().firstName("Spongebob").lastName("Squarepants").emailAddress("spongebob@example.com").build(); + User user = User.builder() + .firstName("Spongebob") + .lastName("Squarepants") + .emailAddress("spongebob@example.com") + .build(); user.setId(id); return user; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanelTest.java index 74c651bb58..2d8ceecb6f 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarActiveParticipantsPanelTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.Matchers.hasItem; +import static se.su.dsv.scipro.finalseminar.SeminarActiveParticipantsPanel.*; + import com.google.common.collect.Lists; +import java.io.Serializable; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.model.Model; @@ -20,14 +27,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.io.Serializable; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.hamcrest.Matchers.hasItem; -import static se.su.dsv.scipro.finalseminar.SeminarActiveParticipantsPanel.*; - public class SeminarActiveParticipantsPanelTest extends SciProTest { private SeminarActiveParticipantsPanel panel; @@ -46,12 +45,14 @@ public class SeminarActiveParticipantsPanelTest extends SciProTest { final Date startDate = Date.from(ZonedDateTime.now().minusDays(1).toInstant()); finalSeminar.setStartDate(startDate); User supervisorUser = new UserBuilder().create(); - finalSeminar.setProject(Project.builder() + finalSeminar.setProject( + Project.builder() .title("title") .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) .startDate(LocalDate.now()) .headSupervisor(supervisorUser) - .build()); + .build() + ); finalSeminar.setActiveParticipations(participants); participation.setFinalSeminar(finalSeminar); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanelTest.java index 5098e7dbe7..29acf0e527 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCRUDPanelTest.java @@ -1,5 +1,16 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.finalseminar.SeminarCRUDPanel.*; + +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -20,19 +31,8 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.finalseminar.SeminarCRUDPanel.*; - public class SeminarCRUDPanelTest extends SciProTest { + private SeminarCRUDPanel panel; private FinalSeminar seminar; private User supervisor; @@ -65,7 +65,11 @@ public class SeminarCRUDPanelTest extends SciProTest { FormTester formTester = newFormTester(); formTester.submit(); tester.assertNoErrorMessage(); - verify(notificationController, Mockito.never()).notifySeminar(ArgumentMatchers.any(FinalSeminar.class), ArgumentMatchers.any(SeminarEvent.Event.class), ArgumentMatchers.any(NotificationSource.class)); + verify(notificationController, Mockito.never()).notifySeminar( + ArgumentMatchers.any(FinalSeminar.class), + ArgumentMatchers.any(SeminarEvent.Event.class), + ArgumentMatchers.any(NotificationSource.class) + ); } @Test @@ -117,7 +121,9 @@ public class SeminarCRUDPanelTest extends SciProTest { FormTester formTester = newFormTester(); formTester.setValue("details:maxOpponents", Integer.toString(seminar.getMinOpponents() - 1)); formTester.submit(); - tester.assertErrorMessages("The selected number of max oppositions may not be lower than " + seminar.getMinOpponents()); + tester.assertErrorMessages( + "The selected number of max oppositions may not be lower than " + seminar.getMinOpponents() + ); } @Test @@ -163,7 +169,11 @@ public class SeminarCRUDPanelTest extends SciProTest { } private void verifyNotificationSent(SeminarEvent.Event event) { - verify(notificationController).notifySeminar(ArgumentMatchers.eq(seminar), ArgumentMatchers.eq(event), ArgumentMatchers.any(NotificationSource.class)); + verify(notificationController).notifySeminar( + ArgumentMatchers.eq(seminar), + ArgumentMatchers.eq(event), + ArgumentMatchers.any(NotificationSource.class) + ); } private FormTester newFormTester() { @@ -196,4 +206,4 @@ public class SeminarCRUDPanelTest extends SciProTest { final Date date = Date.from(ZonedDateTime.now().plusYears(1).toInstant()); return SciProUtilities.setTimeOfDayTo0000(date); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanelTest.java index 62fde122c4..957d576e8e 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarCancelledInfoPanelTest.java @@ -37,7 +37,10 @@ public class SeminarCancelledInfoPanelTest extends SciProTest { public void testPanelContainsLabel() { seminar.setDeleted(true); startPanel(); - tester.assertComponent(path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO), MultiLineLabel.class); + tester.assertComponent( + path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO), + MultiLineLabel.class + ); } @Test @@ -51,7 +54,9 @@ public class SeminarCancelledInfoPanelTest extends SciProTest { public void testLabelIsVisibleWhenSeminarIsDeleted() { seminar.setDeleted(true); startPanel(); - tester.assertVisible(path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO)); + tester.assertVisible( + path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO) + ); } @Test @@ -65,7 +70,9 @@ public class SeminarCancelledInfoPanelTest extends SciProTest { public void testLabelIsInvisibleWhenSeminarIsNotDeleted() { seminar.setDeleted(false); startPanel(); - tester.assertInvisible(path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO)); + tester.assertInvisible( + path(panel.getId(), SeminarCancelledInfoPanel.CANCELLED, SeminarCancelledInfoPanel.CANCELLED_INFO) + ); } private void startPanel() { diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanelTest.java index dc5e1dc0ec..66e5c2224d 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionPanelTest.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.finalseminar; +import static se.su.dsv.scipro.finalseminar.SeminarOppositionPanel.*; + import com.google.common.collect.Lists; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -16,12 +21,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static se.su.dsv.scipro.finalseminar.SeminarOppositionPanel.*; - public class SeminarOppositionPanelTest extends SciProTest { private SeminarOppositionPanel panel; @@ -49,18 +48,18 @@ public class SeminarOppositionPanelTest extends SciProTest { finalSeminar.setOppositions(opponents); supervisorUser = new UserBuilder().create(); - project = Project.builder().title("title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisorUser) - .build(); + project = Project.builder() + .title("title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisorUser) + .build(); coSupervisorUser = new UserBuilder().create(); project.addCoSupervisor(coSupervisorUser); finalSeminar.setProject(project); - setLoggedInAs(supervisorUser); } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanelTest.java index ce2e33028b..32c67e26ec 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarOppositionReportPanelTest.java @@ -1,6 +1,9 @@ package se.su.dsv.scipro.finalseminar; import com.google.common.collect.Lists; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -18,10 +21,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - public class SeminarOppositionReportPanelTest extends SciProTest { private SeminarOppositionReportPanel panel; @@ -53,26 +52,25 @@ public class SeminarOppositionReportPanelTest extends SciProTest { User supervisorUser = new UserBuilder().create(); TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(respondentUser)); - project = Project.builder().title("title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisorUser) - .projectParticipants(projectParticipants) - .build(); + project = Project.builder() + .title("title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisorUser) + .projectParticipants(projectParticipants) + .build(); coSupervisorUser = new UserBuilder().create(); project.addCoSupervisor(coSupervisorUser); finalSeminar.setProject(project); - setLoggedInAs(supervisorUser); OppositionReport oppositionReport = Mockito.mock(OppositionReport.class); Mockito.when(oppositionReportService.findOrCreateReport(opposition)).thenReturn(oppositionReport); } - @Test public void supervisor_allowed_to_see_opposition_report() { setRoles(Roles.SUPERVISOR); @@ -188,7 +186,10 @@ public class SeminarOppositionReportPanelTest extends SciProTest { fileReference.setFileDescription(opponentReport); opposition.setOpponentReport(fileReference); startPanel(); - tester.assertModelValue(path(panel, "wmc", "reportDownload"), opposition.getOpponentReport().getFileDescription()); + tester.assertModelValue( + path(panel, "wmc", "reportDownload"), + opposition.getOpponentReport().getFileDescription() + ); } @Test @@ -231,8 +232,8 @@ public class SeminarOppositionReportPanelTest extends SciProTest { @Test public void report_attachment_not_visible_if_not_submitted() { - mockPanelWithOppositionReport(opponentUser, true, false); - tester.assertInvisible(path(panel, "wmc", "downloadAttachment")); + mockPanelWithOppositionReport(opponentUser, true, false); + tester.assertInvisible(path(panel, "wmc", "downloadAttachment")); } private void mockPanelWithOppositionReport(User user, boolean hasAttachment, boolean submitted) { @@ -263,4 +264,4 @@ public class SeminarOppositionReportPanelTest extends SciProTest { reviewerUser = new UserBuilder().create(); project.addReviewer(reviewerUser); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarPanelTest.java index 2117e88581..2edb1a7727 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.ArgumentMatchers.any; + +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,15 +22,10 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.mockito.ArgumentMatchers.any; - public class SeminarPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); + @Mock FinalSeminarSettings finalSeminarSettings = new FinalSeminarSettings(); @@ -44,11 +44,11 @@ public class SeminarPanelTest extends SciProTest { User authorUser = new UserBuilder().create(); someProject = Project.builder() - .title("some title") - .projectType(BACHELOR) - .startDate(LocalDate.now()) - .headSupervisor(supervisorUser) - .build(); + .title("some title") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .headSupervisor(supervisorUser) + .build(); someProject.setId(238942L); addCoSupervisorToProject(); @@ -63,7 +63,9 @@ public class SeminarPanelTest extends SciProTest { List respondents = Collections.singletonList(finalSeminarRespondent); Mockito.when(finalSeminarRespondentService.findOrCreate(SOME_FINAL_SEMINAR)).thenReturn(respondents); Mockito.when(projectService.findOne(someProject.getId())).thenReturn(someProject); - Mockito.when(plagiarismControl.getStatus(any(FileDescription.class))).thenReturn(new PlagiarismControl.Status.NotSubmitted()); + Mockito.when(plagiarismControl.getStatus(any(FileDescription.class))).thenReturn( + new PlagiarismControl.Status.NotSubmitted() + ); } private void addCoSupervisorToProject() { @@ -86,7 +88,11 @@ public class SeminarPanelTest extends SciProTest { opposition = new FinalSeminarOpposition(); DomainObjects.injectId(opposition, 42L); opposition.setUser(opponentUser); - Project opponentProject = Project.builder().title("opponentProject").projectType(BACHELOR).startDate(LocalDate.now()).build(); + Project opponentProject = Project.builder() + .title("opponentProject") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .build(); opposition.setProject(opponentProject); opposition.setGrade(grade); seminar.addOpposition(opposition); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanelTest.java index b62eb214e4..38a87a018c 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarRespondentsPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.finalseminar; +import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.FEEDBACK; +import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.RADIOS; +import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.RESPONDENTS; +import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.USER; + +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -14,15 +22,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.FEEDBACK; -import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.RADIOS; -import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.RESPONDENTS; -import static se.su.dsv.scipro.finalseminar.SeminarRespondentsPanel.USER; - public class SeminarRespondentsPanelTest extends SciProTest { private FinalSeminar finalSeminar; @@ -35,12 +34,14 @@ public class SeminarRespondentsPanelTest extends SciProTest { final Date startDate = Date.from(ZonedDateTime.now().minusDays(1).toInstant()); finalSeminar.setStartDate(startDate); User supervisorUser = new UserBuilder().create(); - finalSeminar.setProject(Project.builder() + finalSeminar.setProject( + Project.builder() .title("title") .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) .startDate(LocalDate.now()) .headSupervisor(supervisorUser) - .build()); + .build() + ); respondents = Collections.singletonList(new FinalSeminarRespondent(new UserBuilder().create(), finalSeminar)); setLoggedInAs(supervisorUser); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanelTest.java index ac2a37fde4..2b82bdf4cb 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SeminarThesisPanelTest.java @@ -1,5 +1,16 @@ package se.su.dsv.scipro.finalseminar; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.time.Month; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; import org.apache.wicket.Component; import org.apache.wicket.feedback.FencedFeedbackPanel; import org.apache.wicket.model.Model; @@ -21,18 +32,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SeminarThesisPanelTest extends SciProTest { SeminarThesisPanel panel; @@ -79,7 +78,16 @@ public class SeminarThesisPanelTest extends SciProTest { @Test public void DeadlineInformationContainsDeadlineDate() { // given - ZonedDateTime seminarDate = ZonedDateTime.of(2012, Month.APRIL.getValue(), 21, 10, 10, 0, 0, ZoneId.systemDefault()); + ZonedDateTime seminarDate = ZonedDateTime.of( + 2012, + Month.APRIL.getValue(), + 21, + 10, + 10, + 0, + 0, + ZoneId.systemDefault() + ); int daysAhead = 10; FinalSeminarSettings settings = new FinalSeminarSettings(); @@ -112,7 +120,11 @@ public class SeminarThesisPanelTest extends SciProTest { loggedInUser.setId(7L); setLoggedInAs(loggedInUser); // given - Project project = Project.builder().title("title").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("title") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.setId(5L); project.addProjectParticipant(loggedInUser); FinalSeminar seminar = new FinalSeminar(); @@ -120,7 +132,6 @@ public class SeminarThesisPanelTest extends SciProTest { seminar.setProject(project); seminar.setStartDate(new Date()); - startPanel(seminar); // then @@ -146,7 +157,11 @@ public class SeminarThesisPanelTest extends SciProTest { public void HidesUploadIfThesis() { User loggedIn = new UserBuilder().create(); setLoggedInAs(loggedIn); - Project project = Project.builder().title("hej").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("hej") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.setId(7L); project.addProjectParticipant(loggedIn); // given @@ -175,7 +190,6 @@ public class SeminarThesisPanelTest extends SciProTest { setLoggedInAs(loggedInUser); seminar.setProject(project); - // when startPanel(seminar); @@ -231,7 +245,6 @@ public class SeminarThesisPanelTest extends SciProTest { when(finalSeminarService.hasThesis(isA(FinalSeminar.class))).thenReturn(true); startPanel(seminar); - // then boolean isVisible = panel.get(SeminarThesisPanel.NO_THESIS).isVisibleInHierarchy(); assertFalse(isVisible, "No thesis label shown when exists"); @@ -240,7 +253,11 @@ public class SeminarThesisPanelTest extends SciProTest { @Test public void ShowsDeleteLinkIfSupervisorAndThesis() { User headSupervisor = new UserBuilder().create(); - Project p = Project.builder().title("title").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + Project p = Project.builder() + .title("title") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); p.setId(6L); p.setHeadSupervisor(headSupervisor); setLoggedInAs(headSupervisor); @@ -297,7 +314,12 @@ public class SeminarThesisPanelTest extends SciProTest { private Project mockProject() { User headSupervisor = new UserBuilder().create(); - Project proj = Project.builder().title("hej").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).headSupervisor(headSupervisor).build(); + Project proj = Project.builder() + .title("hej") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); proj.setId(77L); setLoggedInAs(headSupervisor); return proj; @@ -354,7 +376,11 @@ public class SeminarThesisPanelTest extends SciProTest { private void startPanel(final FinalSeminar seminar) { if (seminar.getProject() == null) { ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); - Project project = Project.builder().title("Some title").projectType(projectType).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("Some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .build(); seminar.setProject(project); DomainObjects.injectId(project, 74L); } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPageTest.java index 054375d3a1..42fbbcf387 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarDetailsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.finalseminar; +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,17 +15,12 @@ import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; -import java.util.Date; - public class SupervisorFinalSeminarDetailsPageTest extends SciProTest { - private FinalSeminar finalSeminar; @BeforeEach public void setUp() throws Exception { - ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); ProjectTypeSettings projectTypeSettings = new ProjectTypeSettings(); projectTypeSettings.setMaxFinalSeminarActiveParticipation(1); @@ -31,7 +28,12 @@ public class SupervisorFinalSeminarDetailsPageTest extends SciProTest { projectType.setProjectTypeSettings(projectTypeSettings); User supervisor = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); - Project project = Project.builder().title("bla").projectType(projectType).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + Project project = Project.builder() + .title("bla") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); project.setId(2352350L); finalSeminar = new FinalSeminar(); diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPageTest.java index 292856cd95..0b413bc1c6 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarListingPageTest.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.finalseminar; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; +import static org.mockito.Mockito.lenient; + import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.ProjectModule; -import static org.hamcrest.core.StringContains.containsString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.lenient; - public class SupervisorFinalSeminarListingPageTest extends SciProTest { @Test @@ -54,5 +54,4 @@ public class SupervisorFinalSeminarListingPageTest extends SciProTest { private void assertVisible(String menuChoice) { assertThat(renderedPage(), containsString(menuChoice)); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPageTest.java index 47e7565121..2f828d12a3 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalseminar/SupervisorFinalSeminarPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.finalseminar; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,11 +18,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Date; - -import static org.mockito.Mockito.when; - public class SupervisorFinalSeminarPageTest extends PageTest { private Project project; @@ -28,14 +27,16 @@ public class SupervisorFinalSeminarPageTest extends PageTest { public void setUp() throws Exception { headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(project); - when(projectService.hasSupervisingRole(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class))).thenReturn(true); + when( + projectService.hasSupervisingRole(ArgumentMatchers.isA(Project.class), ArgumentMatchers.isA(User.class)) + ).thenReturn(true); } @Test @@ -72,7 +73,3 @@ public class SupervisorFinalSeminarPageTest extends PageTest { return SupervisorFinalSeminarPage.class; } } - - - - diff --git a/view/src/test/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanelTest.java index 80601aed6e..8dfe28d836 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalthesis/ApproveFinalThesisPanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.finalthesis; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static se.su.dsv.scipro.finalthesis.ApproveFinalThesisPanel.*; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.Date; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -21,21 +28,13 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Collections; -import java.util.Date; - -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.eq; -import static se.su.dsv.scipro.finalthesis.ApproveFinalThesisPanel.*; - public class ApproveFinalThesisPanelTest extends SciProTest { private static final Project SOME_PROJECT = Project.builder() - .title("Title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("Title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); public static final String SOME_CONTENT = "content"; private ApproveFinalThesisPanel panel; @@ -81,7 +80,16 @@ public class ApproveFinalThesisPanelTest extends SciProTest { mockHasFinalThesisAndStartPanel(FinalThesis.Status.NO_DECISION); tester.clickLink(path(panel, THESIS_CONTAINER, THESIS_DECISION_CONTAINER, REJECT)); - tester.clickLink(path(panel, THESIS_CONTAINER, REJECT_CONTAINER, REJECT_PANEL, RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.CANCEL_REJECTION)); + tester.clickLink( + path( + panel, + THESIS_CONTAINER, + REJECT_CONTAINER, + REJECT_PANEL, + RejectFinalThesisPanel.FORM, + RejectFinalThesisPanel.CANCEL_REJECTION + ) + ); tester.assertInvisible(path(panel, THESIS_CONTAINER, REJECT_CONTAINER, REJECT_PANEL)); tester.assertVisible(path(panel, THESIS_CONTAINER, THESIS_DECISION_CONTAINER)); @@ -105,25 +113,32 @@ public class ApproveFinalThesisPanelTest extends SciProTest { User user = new UserBuilder().create(); setLoggedInAs(user); - Mockito.when(projectForumService.createThread(eq(SOME_PROJECT), + Mockito.when( + projectForumService.createThread( + eq(SOME_PROJECT), eq(user), ArgumentMatchers.anyString(), eq(SOME_CONTENT), - anySet())) - .thenReturn(projectThread); + anySet() + ) + ).thenReturn(projectThread); tester.clickLink(path(panel, THESIS_CONTAINER, THESIS_DECISION_CONTAINER, REJECT)); - FormTester formTester = tester.newFormTester(path(panel, THESIS_CONTAINER, REJECT_CONTAINER, REJECT_PANEL, RejectFinalThesisPanel.FORM)); + FormTester formTester = tester.newFormTester( + path(panel, THESIS_CONTAINER, REJECT_CONTAINER, REJECT_PANEL, RejectFinalThesisPanel.FORM) + ); formTester.setValue(path(RejectFinalThesisPanel.CONTENT), SOME_CONTENT); formTester.submit(); Mockito.verify(finalThesisService).reject(eq(SOME_PROJECT), eq(SOME_CONTENT)); - Mockito.verify(projectForumService).createThread(SOME_PROJECT, - SciProSession.get().getUser(), - RejectFinalThesisPanel.REJECTED_SUBJECT, - SOME_CONTENT, - Collections.emptySet()); + Mockito.verify(projectForumService).createThread( + SOME_PROJECT, + SciProSession.get().getUser(), + RejectFinalThesisPanel.REJECTED_SUBJECT, + SOME_CONTENT, + Collections.emptySet() + ); } @Test @@ -181,10 +196,15 @@ public class ApproveFinalThesisPanelTest extends SciProTest { tester.assertInvisible(path(panel, THESIS_CONTAINER)); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER)); - tester.assertComponent(path(panel, WAITING_FOR_AUTHOR_CONTAINER, UPLOAD_FORM_PANEL), FinalThesisUploadFormPanel.class); + tester.assertComponent( + path(panel, WAITING_FOR_AUTHOR_CONTAINER, UPLOAD_FORM_PANEL), + FinalThesisUploadFormPanel.class + ); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_NO_THESIS_LABEL)); tester.assertInvisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.REJECTED_DATE_LABEL)); - tester.assertInvisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_REJECTED_LABEL)); + tester.assertInvisible( + path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_REJECTED_LABEL) + ); tester.assertInvisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.REJECTED_INFO_LABEL)); } @@ -195,8 +215,13 @@ public class ApproveFinalThesisPanelTest extends SciProTest { tester.assertInvisible(path(panel, THESIS_CONTAINER)); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER)); - tester.assertComponent(path(panel, WAITING_FOR_AUTHOR_CONTAINER, UPLOAD_FORM_PANEL), FinalThesisUploadFormPanel.class); - tester.assertInvisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_NO_THESIS_LABEL)); + tester.assertComponent( + path(panel, WAITING_FOR_AUTHOR_CONTAINER, UPLOAD_FORM_PANEL), + FinalThesisUploadFormPanel.class + ); + tester.assertInvisible( + path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_NO_THESIS_LABEL) + ); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.REJECTED_DATE_LABEL)); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.STATUS_REJECTED_LABEL)); tester.assertVisible(path(panel, WAITING_FOR_AUTHOR_CONTAINER, ApproveFinalThesisPanel.REJECTED_INFO_LABEL)); @@ -216,7 +241,10 @@ public class ApproveFinalThesisPanelTest extends SciProTest { public void shows_date_of_uploaded_file() { FinalThesis finalThesis = mockHasFinalThesisAndStartPanel(FinalThesis.Status.NO_DECISION); - tester.assertModelValue(path(panel, THESIS_CONTAINER, THESIS_DECISION_CONTAINER, DATE_LABEL), finalThesis.getDateCreated()); + tester.assertModelValue( + path(panel, THESIS_CONTAINER, THESIS_DECISION_CONTAINER, DATE_LABEL), + finalThesis.getDateCreated() + ); } @Test @@ -264,7 +292,9 @@ public class ApproveFinalThesisPanelTest extends SciProTest { finalThesis.setDateCreated(new Date()); SOME_PROJECT.addReviewer(reviewerUser); - Mockito.lenient().when(finalThesisService.getFinalThesisFileDescription(SOME_PROJECT)).thenReturn(fileDescription); + Mockito.lenient() + .when(finalThesisService.getFinalThesisFileDescription(SOME_PROJECT)) + .thenReturn(fileDescription); Mockito.when(finalThesisService.findByProject(SOME_PROJECT)).thenReturn(finalThesis); return finalThesis; } diff --git a/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisPanelTest.java index c31e91c3a2..fc49104e7c 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.finalthesis; +import static se.su.dsv.scipro.finalthesis.FinalThesis.Status; +import static se.su.dsv.scipro.finalthesis.FinalThesisPanel.*; + +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,12 +19,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.util.Date; - -import static se.su.dsv.scipro.finalthesis.FinalThesis.Status; -import static se.su.dsv.scipro.finalthesis.FinalThesisPanel.*; - public class FinalThesisPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @@ -33,7 +32,9 @@ public class FinalThesisPanelTest extends SciProTest { Mockito.when(finalThesisService.findByProject(project)).thenReturn(SOME_FINAL_THESIS); Mockito.when(finalSeminarService.hasHadFinalSeminar(ArgumentMatchers.any(Project.class))).thenReturn(true); Mockito.when(finalThesisService.isUploadAllowed(ArgumentMatchers.any(Project.class))).thenReturn(true); - Mockito.when(reflectionService.hasToFillInReflection(ArgumentMatchers.eq(project), ArgumentMatchers.any(User.class))).thenReturn(false); + Mockito.when( + reflectionService.hasToFillInReflection(ArgumentMatchers.eq(project), ArgumentMatchers.any(User.class)) + ).thenReturn(false); } @Test @@ -91,7 +92,10 @@ public class FinalThesisPanelTest extends SciProTest { startPanel(BACHELOR); - tester.assertModelValue(path(REVISION_PANEL, FinalThesisPanel.REJECTED_DATE_LABEL), SOME_FINAL_THESIS.getDateRejected()); + tester.assertModelValue( + path(REVISION_PANEL, FinalThesisPanel.REJECTED_DATE_LABEL), + SOME_FINAL_THESIS.getDateRejected() + ); } @Test @@ -123,7 +127,10 @@ public class FinalThesisPanelTest extends SciProTest { startPanel(BACHELOR); - tester.assertModelValue(path(APPROVED_PANEL, FinalThesisPanel.APPROVED_DATE), SOME_FINAL_THESIS.getDateApproved()); + tester.assertModelValue( + path(APPROVED_PANEL, FinalThesisPanel.APPROVED_DATE), + SOME_FINAL_THESIS.getDateApproved() + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanelTest.java index 5ccb95e866..be2b4196fe 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalthesis/FinalThesisUploadFormPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.finalthesis; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static se.su.dsv.scipro.finalthesis.FinalThesisUploadFormPanel.FORM; + +import java.net.URI; +import java.net.URISyntaxException; import org.apache.wicket.model.Model; import org.apache.wicket.util.file.File; import org.apache.wicket.util.tester.FormTester; @@ -16,13 +22,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.net.URI; -import java.net.URISyntaxException; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static se.su.dsv.scipro.finalthesis.FinalThesisUploadFormPanel.FORM; - public class FinalThesisUploadFormPanelTest extends SciProTest { public static final Project SOME_PROJECT = new Project(); @@ -33,9 +32,12 @@ public class FinalThesisUploadFormPanelTest extends SciProTest { public void setUp() throws Exception { SOME_PROJECT.setId(293874L); user = new UserBuilder().create(); - Mockito.lenient().when(finalSeminarService.hasHadFinalSeminar(ArgumentMatchers.any(Project.class))).thenReturn(true); - Mockito.lenient().when(finalThesisService.isUploadAllowed(ArgumentMatchers.any(Project.class))).thenReturn(true); - + Mockito.lenient() + .when(finalSeminarService.hasHadFinalSeminar(ArgumentMatchers.any(Project.class))) + .thenReturn(true); + Mockito.lenient() + .when(finalThesisService.isUploadAllowed(ArgumentMatchers.any(Project.class))) + .thenReturn(true); } @Test @@ -123,5 +125,4 @@ public class FinalThesisUploadFormPanelTest extends SciProTest { URI resource = Thread.currentThread().getContextClassLoader().getResource("final_thesis.txt").toURI(); return new File(resource); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanelTest.java b/view/src/test/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanelTest.java index 50cd51611c..3283d46bd9 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalthesis/RejectFinalThesisPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.finalthesis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + import org.apache.wicket.markup.html.form.AbstractTextComponent; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.link.AbstractLink; @@ -17,9 +20,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.*; - public class RejectFinalThesisPanelTest extends SciProTest { @Mock @@ -39,32 +39,49 @@ public class RejectFinalThesisPanelTest extends SciProTest { @Test public void testContainsContentInput() { - tester.assertComponent(path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.CONTENT), AbstractTextComponent.class); + tester.assertComponent( + path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.CONTENT), + AbstractTextComponent.class + ); } @Test public void testContainsUploadField() { - tester.assertComponent(path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.ATTACHMENT), FileUploadField.class); + tester.assertComponent( + path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.ATTACHMENT), + FileUploadField.class + ); } @Test public void testContainsFeedbackPanel() { - - tester.assertComponent(path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.FEEDBACK), FeedbackPanel.class); + tester.assertComponent( + path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.FEEDBACK), + FeedbackPanel.class + ); } @Test public void testContainsCancelLink() { - - tester.assertComponent(path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.CANCEL_REJECTION), AbstractLink.class); + tester.assertComponent( + path(panel.getId(), RejectFinalThesisPanel.FORM, RejectFinalThesisPanel.CANCEL_REJECTION), + AbstractLink.class + ); } @Test public void testSubmittingFormCreatesThread() throws Exception { ProjectThread thread = new ForumBuilder().createThread(); thread.getForumThread().addPost(new ForumBuilder().createPost()); - when(projectForumService.createThread(isA(Project.class), isA(User.class), isA(String.class), - isA(String.class), anySet())).thenReturn(thread); + when( + projectForumService.createThread( + isA(Project.class), + isA(User.class), + isA(String.class), + isA(String.class), + anySet() + ) + ).thenReturn(thread); // given User user = new UserBuilder().setFirstName("Kalle").setLastName("Testare").create(); @@ -75,7 +92,7 @@ public class RejectFinalThesisPanelTest extends SciProTest { setLoggedInAs(user); // when - FormTester formTester = tester.newFormTester(path(panel.getId(), RejectFinalThesisPanel.FORM)); + FormTester formTester = tester.newFormTester(path(panel.getId(), RejectFinalThesisPanel.FORM)); formTester.setFile(RejectFinalThesisPanel.ATTACHMENT, file, contentType); formTester.setValue(RejectFinalThesisPanel.CONTENT, content); formTester.submit(); @@ -87,8 +104,4 @@ public class RejectFinalThesisPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new RejectFinalThesisPanel("panel", Model.of(project))); } - - - } - diff --git a/view/src/test/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPageTest.java b/view/src/test/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPageTest.java index 8d8625563a..799f75d0f6 100644 --- a/view/src/test/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/finalthesis/SupervisorFinalThesisListingPageTest.java @@ -1,40 +1,41 @@ -package se.su.dsv.scipro.finalthesis; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -public class SupervisorFinalThesisListingPageTest extends SciProTest { - - @BeforeEach - public void setUp() throws Exception { - when(finalThesisService.findAll(any(FinalThesisService.Filter.class), any(Pageable.class))).thenReturn(Collections.singletonList(createFinalThesis())); - when(finalThesisService.count(any(FinalThesisService.Filter.class))).thenReturn(1L); - } - - @Test - public void renders() throws Exception { - tester.startPage(SupervisorFinalThesisListingPage.class); - tester.assertRenderedPage(SupervisorFinalThesisListingPage.class); - } - - private FinalThesis createFinalThesis() { - final ProjectType projectType = new ProjectType(); - final User supervisor = new User(); - final Project project = new Project(); - project.setHeadSupervisor(supervisor); - project.setProjectType(projectType); - final FinalThesis finalThesis = new FinalThesis(); - finalThesis.setProject(project); - return finalThesis; - } -} +package se.su.dsv.scipro.finalthesis; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; + +public class SupervisorFinalThesisListingPageTest extends SciProTest { + + @BeforeEach + public void setUp() throws Exception { + when(finalThesisService.findAll(any(FinalThesisService.Filter.class), any(Pageable.class))).thenReturn( + Collections.singletonList(createFinalThesis()) + ); + when(finalThesisService.count(any(FinalThesisService.Filter.class))).thenReturn(1L); + } + + @Test + public void renders() throws Exception { + tester.startPage(SupervisorFinalThesisListingPage.class); + tester.assertRenderedPage(SupervisorFinalThesisListingPage.class); + } + + private FinalThesis createFinalThesis() { + final ProjectType projectType = new ProjectType(); + final User supervisor = new User(); + final Project project = new Project(); + project.setHeadSupervisor(supervisor); + project.setProjectType(projectType); + final FinalThesis finalThesis = new FinalThesis(); + finalThesis.setProject(project); + return finalThesis; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanelTest.java b/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanelTest.java index 1243774845..f3e2a48aa7 100644 --- a/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingColumnPanelTest.java @@ -31,10 +31,11 @@ public class FirstMeetingColumnPanelTest extends SciProTest { } private void startPanel() { - tester.startComponentInPage(new FirstMeetingColumnPanel("id", Model.of(idea)) { - @Override - protected void onColumnClick(AjaxRequestTarget target, IModel model) { + tester.startComponentInPage( + new FirstMeetingColumnPanel("id", Model.of(idea)) { + @Override + protected void onColumnClick(AjaxRequestTarget target, IModel model) {} } - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanelTest.java b/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanelTest.java index ff2fd43cd1..1aab2d34ed 100644 --- a/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/firstmeeting/FirstMeetingPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.firstmeeting; +import static java.lang.String.format; +import static se.su.dsv.scipro.firstmeeting.FirstMeetingPanel.*; + +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.*; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.Assertions; @@ -18,15 +26,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.*; - -import static java.lang.String.format; -import static se.su.dsv.scipro.firstmeeting.FirstMeetingPanel.*; - public class FirstMeetingPanelTest extends SciProTest { private FirstMeetingPanel panel; @@ -38,9 +37,10 @@ public class FirstMeetingPanelTest extends SciProTest { LocalDate courseStartDate = LocalDate.now(); idea = createCompletedIdea(courseStartDate); - final ZonedDateTime firstMetingDate = idea.getApplicationPeriod() - .getCourseStartDateTime() - .atZone(ZoneId.systemDefault()); + final ZonedDateTime firstMetingDate = idea + .getApplicationPeriod() + .getCourseStartDateTime() + .atZone(ZoneId.systemDefault()); firstMeeting = new FirstMeeting(Date.from(firstMetingDate.toInstant()), idea); } @@ -107,7 +107,9 @@ public class FirstMeetingPanelTest extends SciProTest { startPanel(); Date date = createDateThreeDaysFromNow(); String formattedDate = new SimpleDateFormat(dateService.getFormat(DateStyle.DATETIME)).format(date); - Mockito.when(dateService.format(ArgumentMatchers.any(Date.class), ArgumentMatchers.eq(DateStyle.DATETIME))).thenReturn(formattedDate); + Mockito.when( + dateService.format(ArgumentMatchers.any(Date.class), ArgumentMatchers.eq(DateStyle.DATETIME)) + ).thenReturn(formattedDate); scheduleMeeting(date); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePageTest.java index 437a0fcaa3..76b6faec54 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/ProjectForumBasePageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.forum.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.TreeSet; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -19,13 +25,6 @@ import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; -import java.util.TreeSet; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class ProjectForumBasePageTest extends SciProTest { Project project; @@ -37,12 +36,12 @@ public class ProjectForumBasePageTest extends SciProTest { TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(student)); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .projectParticipants(projectParticipants) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePageTest.java index 4de292ae91..01328c98c8 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/SupervisorForumBasePageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -18,11 +22,6 @@ import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorForumBasePageTest extends SciProTest { Project project; @@ -32,11 +31,11 @@ public class SupervisorForumBasePageTest extends SciProTest { User headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); User student = new UserBuilder().setFirstName("author").setLastName("1").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); when(projectService.hasSupervisingRole(isA(Project.class), isA(User.class))).thenReturn(true); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPageTest.java index f8b6a864ba..bc76d3857e 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectCreateForumThreadPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -14,12 +18,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - - public class ProjectCreateForumThreadPageTest extends PageTest { ProjectCreateForumThreadPage page; @@ -35,11 +33,11 @@ public class ProjectCreateForumThreadPageTest extends PageTest { User student = new UserBuilder().setFirstName("author").setLastName("1").create(); User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPageTest.java index 6fd2ce48cb..ad91b95d9a 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectThreadedForumPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.Mockito.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.Mockito.isA; -import static org.mockito.Mockito.when; - public class ProjectThreadedForumPageTest extends PageTest { Project project; @@ -27,11 +26,11 @@ public class ProjectThreadedForumPageTest extends PageTest { User student = new UserBuilder().setFirstName("author").setLastName("1").create(); User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); project.setStartDate(LocalDate.now()); @@ -54,7 +53,10 @@ public class ProjectThreadedForumPageTest extends PageTest { @Test public void testClickCreateLinkTakesUserToCreatePage() { - tester.assertBookmarkablePageLink(ProjectThreadedForumPage.CREATE_THREAD_LINK, ProjectCreateForumThreadPage.class, getPageParameters()); + tester.assertBookmarkablePageLink( + ProjectThreadedForumPage.CREATE_THREAD_LINK, + ProjectCreateForumThreadPage.class, + getPageParameters() + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPageTest.java index cb33ae557b..af632106d6 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/ProjectViewForumThreadPageTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.TreeSet; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -17,14 +24,6 @@ import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; -import java.util.TreeSet; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.when; - public class ProjectViewForumThreadPageTest extends PageTest { Page page; @@ -38,12 +37,12 @@ public class ProjectViewForumThreadPageTest extends PageTest { TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(student)); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .projectParticipants(projectParticipants) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPageTest.java index 13773a4c72..7c6279e67e 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorCreateForumThreadPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -15,11 +19,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorCreateForumThreadPageTest extends PageTest { @Override @@ -38,11 +37,11 @@ public class SupervisorCreateForumThreadPageTest extends PageTest { public void setUp() throws Exception { User headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPageTest.java index 0b3b5f491f..255e38d59a 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorThreadedForumPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.Mockito.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.Mockito.isA; -import static org.mockito.Mockito.when; - public class SupervisorThreadedForumPageTest extends PageTest { SupervisorThreadedForumPage page; @@ -39,11 +38,11 @@ public class SupervisorThreadedForumPageTest extends PageTest { public void setUp() throws Exception { User headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); project.setStartDate(LocalDate.now()); when(projectService.findOne(isA(Long.class))).thenReturn(project); @@ -54,7 +53,10 @@ public class SupervisorThreadedForumPageTest extends PageTest { @Test public void testClickCreateLinkTakesUserToCreatePage() { - tester.assertBookmarkablePageLink(SupervisorThreadedForumPage.CREATE_THREAD_LINK, SupervisorCreateForumThreadPage.class, getPageParameters()); + tester.assertBookmarkablePageLink( + SupervisorThreadedForumPage.CREATE_THREAD_LINK, + SupervisorCreateForumThreadPage.class, + getPageParameters() + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPageTest.java index 46201ace07..b80342d196 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/pages/threaded/SupervisorViewForumThreadPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.pages.threaded; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -17,11 +21,6 @@ import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorViewForumThreadPageTest extends PageTest { Page page; @@ -42,14 +41,13 @@ public class SupervisorViewForumThreadPageTest extends PageTest { @BeforeEach public void setUp() throws Exception { - User headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); thread = new ForumBuilder().createThread(); diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanelTest.java index ab6e716354..49a0278784 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ForumPostPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -7,8 +9,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.test.ForumBuilder; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class ForumPostPanelTest extends SciProTest { ForumPostPanel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanelTest.java index 098c1d28c5..02ad031f6e 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumReplyPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +import java.io.Serializable; import org.apache.wicket.model.Model; import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; import org.apache.wicket.util.tester.FormTester; @@ -10,13 +16,6 @@ import se.su.dsv.scipro.forum.dataobjects.ProjectThread; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ForumBuilder; -import java.io.Serializable; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.verify; -import static org.mockito.internal.verification.VerificationModeFactory.times; - public class SubmitForumReplyPanelTest extends SciProTest { SubmitForumReplyPanel panel; @@ -37,16 +36,22 @@ public class SubmitForumReplyPanelTest extends SciProTest { submit(); tester.assertNoErrorMessage(); - verify(projectForumService, times(1)).createReply(isA(ProjectThread.class), isA(User.class), isA(String.class), - anySet()); + verify(projectForumService, times(1)).createReply( + isA(ProjectThread.class), + isA(User.class), + isA(String.class), + anySet() + ); tester.assertModelValue(path(panel.getId(), "form", "content"), ""); } private ProjectThread mockForumThread() { ProjectThread thread = new ForumBuilder().createThread(); - lenient().when(projectForumService.createReply( - any(ProjectThread.class), any(User.class), any(String.class), anySet())) - .thenReturn(new ForumBuilder().createPost()); + lenient() + .when( + projectForumService.createReply(any(ProjectThread.class), any(User.class), any(String.class), anySet()) + ) + .thenReturn(new ForumBuilder().createPost()); return thread; } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanelTest.java index b3b1e1e550..82c893e095 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/SubmitForumThreadPanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +import java.time.LocalDate; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -15,14 +22,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.internal.verification.VerificationModeFactory.times; - public class SubmitForumThreadPanelTest extends SciProTest { SubmitForumThreadPanel panel; @@ -36,11 +35,11 @@ public class SubmitForumThreadPanelTest extends SciProTest { User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); startPanel(); @@ -53,8 +52,15 @@ public class SubmitForumThreadPanelTest extends SciProTest { @Test public void testSaveForm() { - when(projectForumService.createThread(isA(Project.class), isA(User.class), isA(String.class), - isA(String.class), anySet())).thenReturn(thread); + when( + projectForumService.createThread( + isA(Project.class), + isA(User.class), + isA(String.class), + isA(String.class), + anySet() + ) + ).thenReturn(thread); User user = new UserBuilder().setFirstName("Kalle").setLastName("Testare").create(); setLoggedInAs(user); @@ -67,11 +73,18 @@ public class SubmitForumThreadPanelTest extends SciProTest { tester.assertNoErrorMessage(); - verify(projectForumService, times(1)).createThread(isA(Project.class), isA(User.class), isA(String.class), isA(String.class), - anySet()); + verify(projectForumService, times(1)).createThread( + isA(Project.class), + isA(User.class), + isA(String.class), + isA(String.class), + anySet() + ); } private void startPanel() { - panel = tester.startComponentInPage(new SubmitForumThreadPanel<>("panel", new ProjectForum(projectForumService, Model.of(project)))); + panel = tester.startComponentInPage( + new SubmitForumThreadPanel<>("panel", new ProjectForum(projectForumService, Model.of(project))) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanelTest.java index 2fa58c874c..89f646f576 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadReadStatePanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -11,10 +15,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.*; - public class ThreadReadStatePanelTest extends SciProTest { ThreadReadStatePanel panel; @@ -58,5 +58,4 @@ public class ThreadReadStatePanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new ThreadReadStatePanel("panel", Model.of(forumThread))); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanelTest.java index 32d2970742..8c99db6c4f 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ThreadsOverviewPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.forum.panels.threaded; +import java.util.Arrays; +import java.util.List; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.pages.InternalErrorPage; import org.apache.wicket.model.IModel; @@ -14,9 +16,6 @@ import se.su.dsv.scipro.forum.dataobjects.ForumPost; import se.su.dsv.scipro.forum.dataobjects.ForumThread; import se.su.dsv.scipro.system.User; -import java.util.Arrays; -import java.util.List; - @ExtendWith(MockitoExtension.class) public class ThreadsOverviewPanelTest extends SciProTest { @@ -35,15 +34,22 @@ public class ThreadsOverviewPanelTest extends SciProTest { private void startPanel() { IModel> listIModel = Model.ofList(threads); - tester.startComponentInPage(new ThreadsOverviewPanel<>("id", listIModel, new Discussable() { - @Override - public IModel discussion(final IModel a) { - return a; - } - }, (id, thread) -> { - final BookmarkablePageLink link = new BookmarkablePageLink<>(id, InternalErrorPage.class); - return link; - })); + tester.startComponentInPage( + new ThreadsOverviewPanel<>( + "id", + listIModel, + new Discussable() { + @Override + public IModel discussion(final IModel a) { + return a; + } + }, + (id, thread) -> { + final BookmarkablePageLink link = new BookmarkablePageLink<>(id, InternalErrorPage.class); + return link; + } + ) + ); } private ForumThread createThread() { @@ -54,4 +60,4 @@ public class ThreadsOverviewPanelTest extends SciProTest { groupForumThread.addPost(post); return groupForumThread; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanelTest.java index 6c314bb294..a28c9c6f3e 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewForumThreadPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Arrays; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.model.Model; import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; @@ -20,15 +28,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.when; - public class ViewForumThreadPanelTest extends SciProTest { ViewForumThreadPanel panel; @@ -43,11 +42,11 @@ public class ViewForumThreadPanelTest extends SciProTest { User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); lenient().when(projectForumService.getPosts(isA(ProjectThread.class))).thenReturn(Arrays.asList(post, post)); @@ -63,25 +62,40 @@ public class ViewForumThreadPanelTest extends SciProTest { public void testListItemContainsPostDetailsPanel() { startPanel(); tester.assertComponent( - path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.POST_LIST, 0, ViewForumThreadPanel.POST), ForumPostPanel.class); + path( + panel.getId(), + ViewForumThreadPanel.WRAPPER, + ViewForumThreadPanel.POST_LIST, + 0, + ViewForumThreadPanel.POST + ), + ForumPostPanel.class + ); } @Test public void testPanelContainsTopReplyLink() { startPanel(); - tester.assertComponent(path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK), AjaxLink.class); + tester.assertComponent( + path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK), + AjaxLink.class + ); } @Test public void testReplyLinkVisibility() { startPanel(); - boolean isTopLinkVisible = panel.get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)).isVisibleInHierarchy(); + boolean isTopLinkVisible = panel + .get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)) + .isVisibleInHierarchy(); assertTrue(isTopLinkVisible); } @Test public void testSubmittingReplyThroughUpperReplyPanelRendersWrapper() { - when(projectForumService.createReply(any(ProjectThread.class), any(User.class), any(String.class), anySet())).thenReturn(post); + when( + projectForumService.createReply(any(ProjectThread.class), any(User.class), any(String.class), anySet()) + ).thenReturn(post); startPanel(); tester.clickLink(path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)); @@ -95,17 +109,27 @@ public class ViewForumThreadPanelTest extends SciProTest { tester.clickLink(path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)); tester.assertComponentOnAjaxResponse(path(panel.getId(), ViewForumThreadPanel.WRAPPER)); - boolean isPanelVisible = panel.get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_PANEL)).isVisibleInHierarchy(); + boolean isPanelVisible = panel + .get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_PANEL)) + .isVisibleInHierarchy(); assertTrue(isPanelVisible); - boolean isLinkVisible = panel.get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)).isVisibleInHierarchy(); + boolean isLinkVisible = panel + .get(path(ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.TOP_REPLY_LINK)) + .isVisibleInHierarchy(); assertFalse(isLinkVisible); } @Test public void back_link_not_visible_if_not_forum_thread() { ReviewerThread reviewerThread = mockReviewerThread(); - panel = tester.startComponentInPage(new ViewForumThreadPanel<>("panel", Model.of(reviewerThread.getProject()), new ReviewerInteractionForumThread(reviewerInteractionService))); + panel = tester.startComponentInPage( + new ViewForumThreadPanel<>( + "panel", + Model.of(reviewerThread.getProject()), + new ReviewerInteractionForumThread(reviewerInteractionService) + ) + ); tester.assertInvisible(path(panel.getId(), ViewForumThreadPanel.WRAPPER, ViewForumThreadPanel.BACK_LINK)); } @@ -121,8 +145,10 @@ public class ViewForumThreadPanelTest extends SciProTest { } private void testFormSubmission(final String panelId) { - SubmitForumReplyPanel replyPanel = (SubmitForumReplyPanel) panel.get(path(ViewForumThreadPanel.WRAPPER, panelId)); - FormTester formTester = tester.newFormTester(replyPanel.getPageRelativePath()+ ":form"); + SubmitForumReplyPanel replyPanel = (SubmitForumReplyPanel) panel.get( + path(ViewForumThreadPanel.WRAPPER, panelId) + ); + FormTester formTester = tester.newFormTester(replyPanel.getPageRelativePath() + ":form"); formTester.setValue("content", "content"); MockHttpServletRequest servletRequest = tester.getRequest(); servletRequest.setUseMultiPartContentType(true); @@ -131,6 +157,8 @@ public class ViewForumThreadPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new ViewForumThreadPanel<>("panel", Model.of(thread), new ProjectForumThread(projectForumService))); + panel = tester.startComponentInPage( + new ViewForumThreadPanel<>("panel", Model.of(thread), new ProjectForumThread(projectForumService)) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanelTest.java b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanelTest.java index f0ca03d9bc..2056880ec8 100644 --- a/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/forum/panels/threaded/ViewProjectForumThreadPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.forum.panels.threaded; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -12,10 +16,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ForumBuilder; import se.su.dsv.scipro.test.ObjectMother; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public class ViewProjectForumThreadPanelTest extends SciProTest { private ViewForumThreadPanel panel; @@ -36,6 +36,13 @@ public class ViewProjectForumThreadPanelTest extends SciProTest { private void startPanel() { ProjectThread thread = new ForumBuilder().createThread(); IModel projectModel = Model.of(thread.getProject()); - panel = tester.startComponentInPage(new ViewProjectForumThreadPanel("panel", Model.of(thread), new ProjectForumThread(projectForumService), projectModel)); + panel = tester.startComponentInPage( + new ViewProjectForumThreadPanel( + "panel", + Model.of(thread), + new ProjectForumThread(projectForumService), + projectModel + ) + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPageTest.java index 03168198f6..02332d7a8c 100644 --- a/view/src/test/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/generalsystemsettings/AdminGeneralSettingsPageTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.generalsystemsettings; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; import org.apache.wicket.Page; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -11,14 +18,6 @@ import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.components.ListField; import se.su.dsv.scipro.security.auth.roles.Roles; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class AdminGeneralSettingsPageTest extends PageTest { @@ -45,22 +44,28 @@ public class AdminGeneralSettingsPageTest extends PageTest { List mails = Arrays.asList("kalle@testare.dsv.su.se", "rasmus@luffen.dsv.su.se"); // when - submitForm(AdminGeneralSettingsPage.ALARM_MAILS, mails.stream().collect(Collectors.joining(ListField.SEPARATOR))); + submitForm( + AdminGeneralSettingsPage.ALARM_MAILS, + mails.stream().collect(Collectors.joining(ListField.SEPARATOR)) + ); // then GeneralSystemSettings settings = captureSaveArgument(); List alarmMails = settings.getAlarmMails(); assertEquals(mails.size(), alarmMails.size(), "Did not save the correct number of emails"); } - + @Test public void testSavesSupervisoChangeMails() { - List mails = Arrays.asList("test@test.dsv.su.se", "test2@dsv.su.se"); - submitForm(AdminGeneralSettingsPage.SUPERVISOR_CHANGE_MAILS, mails.stream().collect(Collectors.joining(ListField.SEPARATOR))); - - GeneralSystemSettings settings = captureSaveArgument(); - List supervisorChangeMails = settings.getSupervisorChangeMails(); - assertEquals(mails.size(), supervisorChangeMails.size()); + List mails = Arrays.asList("test@test.dsv.su.se", "test2@dsv.su.se"); + submitForm( + AdminGeneralSettingsPage.SUPERVISOR_CHANGE_MAILS, + mails.stream().collect(Collectors.joining(ListField.SEPARATOR)) + ); + + GeneralSystemSettings settings = captureSaveArgument(); + List supervisorChangeMails = settings.getSupervisorChangeMails(); + assertEquals(mails.size(), supervisorChangeMails.size()); } private GeneralSystemSettings captureSaveArgument() { @@ -74,5 +79,4 @@ public class AdminGeneralSettingsPageTest extends PageTest { formTester.setValue(component, value); formTester.submit(); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/grading/CriteriaPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/CriteriaPanelTest.java index 608659db2f..4c26f4119f 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/CriteriaPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/CriteriaPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.grading; +import static se.su.dsv.scipro.grading.CriteriaPanel.*; + +import java.time.LocalDate; +import java.time.Month; +import java.util.*; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.RadioChoice; import org.apache.wicket.model.LoadableDetachableModel; @@ -16,16 +21,14 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.util.*; - -import static se.su.dsv.scipro.grading.CriteriaPanel.*; - public class CriteriaPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - public static final Project SOME_PROJECT = Project.builder().title("Grading report project").projectType(BACHELOR).startDate(LocalDate.now()).build(); + public static final Project SOME_PROJECT = Project.builder() + .title("Grading report project") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .build(); public static final User SOME_USER = new UserBuilder().setFirstName("Author").setLastName("One").create(); public static final User SOME_USER_2 = new UserBuilder().setFirstName("Author").setLastName("two").create(); @@ -90,12 +93,17 @@ public class CriteriaPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new CriteriaPanel("id", new LoadableDetachableModel<>() { - @Override - protected SupervisorGradingReport load() { - return gradingReport; - } - })); + panel = tester.startComponentInPage( + new CriteriaPanel( + "id", + new LoadableDetachableModel<>() { + @Override + protected SupervisorGradingReport load() { + return gradingReport; + } + } + ) + ); } @Override @@ -111,10 +119,17 @@ public class CriteriaPanelTest extends SciProTest { } private void prepareReports() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(BACHELOR, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + BACHELOR, + LocalDate.of(2024, Month.JANUARY, 1) + ); gradingReportTemplate.addIndividualCriterion("Projektkriterium", "Project criterion", 1, getPointTemplates(2)); - gradingReportTemplate.addIndividualCriterion("Individuellt kriterium", "Individual criterion", 0, getPointTemplates(2)); + gradingReportTemplate.addIndividualCriterion( + "Individuellt kriterium", + "Individual criterion", + 0, + getPointTemplates(2) + ); gradingReport = gradingReportTemplate.createSupervisorReport(SOME_PROJECT, SOME_USER); for (GradingCriterion gradingCriterion : gradingReport.getGradingCriteria()) { gradingCriterion.setPoints(1); @@ -125,11 +140,13 @@ public class CriteriaPanelTest extends SciProTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/view/src/test/java/se/su/dsv/scipro/grading/FillOutReportPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/FillOutReportPanelTest.java index 209a783033..e8e9367d12 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/FillOutReportPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/FillOutReportPanelTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.grading; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.grading.FillOutReportPanel.*; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.apache.wicket.markup.html.form.SubmitLink; import org.apache.wicket.model.Model; import org.apache.wicket.protocol.http.mock.MockHttpServletRequest; @@ -19,17 +29,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.grading.FillOutReportPanel.*; - public class FillOutReportPanelTest extends SciProTest { private OppositionReport oppositionReport; @@ -43,10 +42,14 @@ public class FillOutReportPanelTest extends SciProTest { FinalSeminar finalSeminar = new FinalSeminar(); ProjectType projectType = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); User headSupervisorUser = new UserBuilder().create(); - Project project = Project.builder().title("title").projectType(projectType).startDate(LocalDate.now()).headSupervisor(headSupervisorUser).build(); + Project project = Project.builder() + .title("title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisorUser) + .build(); finalSeminar.setProject(project); - GradingReportTemplate template = new GradingReportTemplate(projectType, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate template = new GradingReportTemplate(projectType, LocalDate.of(2024, Month.JANUARY, 1)); template.addProjectCriterion("U1", "U1", 1, getPointTemplates(1)); FinalSeminarOpposition finalSeminarOpposition = new FinalSeminarOpposition(); finalSeminarOpposition.setFinalSeminar(finalSeminar); @@ -59,11 +62,13 @@ public class FillOutReportPanelTest extends SciProTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } @@ -75,17 +80,26 @@ public class FillOutReportPanelTest extends SciProTest { @Test public void displays_criteria_titles() { - tester.assertModelValue(path(panel, FORM, GRADING_CRITERIA, 0, TITLE), oppositionReport.getCriteria().get(0).getTitle()); + tester.assertModelValue( + path(panel, FORM, GRADING_CRITERIA, 0, TITLE), + oppositionReport.getCriteria().get(0).getTitle() + ); } @Test public void displays_criteria_descriptions() { - tester.assertModelValue(path(panel, FORM, GRADING_CRITERIA, 0, DESCRIPTION), oppositionReport.getCriteria().get(0).getDescription()); + tester.assertModelValue( + path(panel, FORM, GRADING_CRITERIA, 0, DESCRIPTION), + oppositionReport.getCriteria().get(0).getDescription() + ); } @Test public void has_text_area_for_feedback() { - tester.assertModelValue(path(panel, FORM, GRADING_CRITERIA, 0, FEEDBACK), oppositionReport.getCriteria().get(0).getFeedback()); + tester.assertModelValue( + path(panel, FORM, GRADING_CRITERIA, 0, FEEDBACK), + oppositionReport.getCriteria().get(0).getFeedback() + ); } @Test @@ -185,5 +199,4 @@ public class FillOutReportPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new FillOutReportPanel<>("id", Model.of(oppositionReport))); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPdfTest.java b/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPdfTest.java index 4a8ddf031c..141f8e3285 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPdfTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPdfTest.java @@ -1,15 +1,15 @@ package se.su.dsv.scipro.grading; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.*; import net.sf.jasperreports.engine.*; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.report.GradingCriterion; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.*; - public class GradingReportPdfTest { + @Test public void generate_pdf() throws JRException { final GradingReportPdf gradingReport = new GradingReportPdf() { @@ -100,7 +100,11 @@ public class GradingReportPdfTest { }; final InputStream stream = GradingReportPdf.class.getResourceAsStream("/template.jrxml"); final JasperReport jasperReport = JasperCompileManager.compileReport(stream); - JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<>(), new JRBeanCollectionDataSource(List.of(gradingReport))); + JasperPrint jasperPrint = JasperFillManager.fillReport( + jasperReport, + new HashMap<>(), + new JRBeanCollectionDataSource(List.of(gradingReport)) + ); JasperExportManager.exportReportToPdfStream(jasperPrint, OutputStream.nullOutputStream()); } } diff --git a/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPointsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPointsPanelTest.java index cc0c6799df..caa5835e3f 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPointsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/GradingReportPointsPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.grading; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.grading.GradingReportPointsPanel.GRADE; +import static se.su.dsv.scipro.grading.GradingReportPointsPanel.POINTS_LABEL; + +import java.time.LocalDate; +import java.time.Month; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,20 +21,14 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.util.ArrayList; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.grading.GradingReportPointsPanel.GRADE; -import static se.su.dsv.scipro.grading.GradingReportPointsPanel.POINTS_LABEL; - public class GradingReportPointsPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - public static final Project SOME_PROJECT = Project.builder().title("Grading report project").projectType(BACHELOR).startDate(LocalDate.now()).build(); + public static final Project SOME_PROJECT = Project.builder() + .title("Grading report project") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .build(); public static final User SOME_USER = new UserBuilder().setFirstName("Author").setLastName("One").create(); @Mock @@ -58,12 +61,16 @@ public class GradingReportPointsPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new GradingReportPointsPanel("id", Model.of(gradingReport), gradeCalculator)); + panel = tester.startComponentInPage( + new GradingReportPointsPanel("id", Model.of(gradingReport), gradeCalculator) + ); } private void prepareReports() { - GradingReportTemplate gradingReportTemplate = new GradingReportTemplate(BACHELOR, - LocalDate.of(2024, Month.JANUARY, 1)); + GradingReportTemplate gradingReportTemplate = new GradingReportTemplate( + BACHELOR, + LocalDate.of(2024, Month.JANUARY, 1) + ); gradingReportTemplate.addProjectCriterion("title", "titleEn", 0, getPointTemplates(2)); gradingReport = gradingReportTemplate.createSupervisorReport(SOME_PROJECT, SOME_USER); for (GradingCriterion gradingCriterion : gradingReport.getGradingCriteria()) { @@ -75,11 +82,13 @@ public class GradingReportPointsPanelTest extends SciProTest { private List getPointTemplates(int maxPoint) { List gradingCriterionPointTemplates = new ArrayList<>(); for (int i = 0; i <= maxPoint; i++) { - gradingCriterionPointTemplates.add(new GradingCriterionPointTemplate.Builder() + gradingCriterionPointTemplates.add( + new GradingCriterionPointTemplate.Builder() .point(i) .description("Description") .descriptionEn("DescriptionEn") - .build()); + .build() + ); } return gradingCriterionPointTemplates; } diff --git a/view/src/test/java/se/su/dsv/scipro/grading/PublicationMetadataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/PublicationMetadataPanelTest.java index 30f8ab054f..7dfe35d81b 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/PublicationMetadataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/PublicationMetadataPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.grading; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.model.IModel; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -7,12 +12,8 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - class PublicationMetadataPanelTest extends SciProTest { + private Project project; @BeforeEach @@ -42,4 +43,4 @@ class PublicationMetadataPanelTest extends SciProTest { private PublicationMetadataPanel startPanel() { return tester.startComponentInPage(new PublicationMetadataPanel("id", () -> project)); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/grading/SendToExaminerTest.java b/view/src/test/java/se/su/dsv/scipro/grading/SendToExaminerTest.java index c7387f7d5f..af5c1e93bd 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/SendToExaminerTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/SendToExaminerTest.java @@ -1,5 +1,20 @@ package se.su.dsv.scipro.grading; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.Optional; +import java.util.Set; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; @@ -20,22 +35,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.Either; import se.su.dsv.scipro.util.JavascriptEventConfirmation; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.Month; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class SendToExaminerTest extends SciProTest { private static final String TOKEN = "token"; @@ -45,64 +44,69 @@ public class SendToExaminerTest extends SciProTest { tester.getSession().setMetaData(OAuth.TOKEN, TOKEN); ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); User obama = User.builder() - .firstName("Barack") - .lastName("Obama") - .emailAddress("obama@example.com") - .identifier(44) - .build(); + .firstName("Barack") + .lastName("Obama") + .emailAddress("obama@example.com") + .identifier(44) + .build(); User biden = User.builder() - .firstName("Joe") - .lastName("Biden") - .emailAddress("joe@example.com") - .identifier(46) - .build(); + .firstName("Joe") + .lastName("Biden") + .emailAddress("joe@example.com") + .identifier(46) + .build(); biden.setId(46L); Project project = Project.builder() - .title("My project") - .projectType(bachelor) - .startDate(LocalDate.of(2023, Month.JANUARY, 6)) - .headSupervisor(obama) - .projectParticipants(Set.of(biden)) - .identifier(1888) - .build(); + .title("My project") + .projectType(bachelor) + .startDate(LocalDate.of(2023, Month.JANUARY, 6)) + .headSupervisor(obama) + .projectParticipants(Set.of(biden)) + .identifier(1888) + .build(); project.setId(8L); Examination pam = new Examination( - 1, - new Name("Problem och metod", "Problem and method"), - "KX1P", - BigDecimal.valueOf(6), - List.of( - new Grade(Grade.Type.PASSING, "P"), - new Grade(Grade.Type.FAILING, "F"))); + 1, + new Name("Problem och metod", "Problem and method"), + "KX1P", + BigDecimal.valueOf(6), + List.of(new Grade(Grade.Type.PASSING, "P"), new Grade(Grade.Type.FAILING, "F")) + ); Examination gw = new Examination( - 2, - new Name("Examensarbete", "Graduation work"), - "KX1E", - BigDecimal.valueOf(9), - List.of( - new Grade(Grade.Type.PASSING, "A"), - new Grade(Grade.Type.PASSING, "B"), - new Grade(Grade.Type.PASSING, "C"), - new Grade(Grade.Type.PASSING, "D"), - new Grade(Grade.Type.PASSING, "E"), - new Grade(Grade.Type.FAILING, "F"))); - when(gradingService.getExaminations(TOKEN, project.getIdentifier(), biden.getIdentifier())) - .thenReturn(List.of(pam, gw)); + 2, + new Name("Examensarbete", "Graduation work"), + "KX1E", + BigDecimal.valueOf(9), + List.of( + new Grade(Grade.Type.PASSING, "A"), + new Grade(Grade.Type.PASSING, "B"), + new Grade(Grade.Type.PASSING, "C"), + new Grade(Grade.Type.PASSING, "D"), + new Grade(Grade.Type.PASSING, "E"), + new Grade(Grade.Type.FAILING, "F") + ) + ); + when(gradingService.getExaminations(TOKEN, project.getIdentifier(), biden.getIdentifier())).thenReturn( + List.of(pam, gw) + ); // results for problem and method - when(gradingService.getResult(TOKEN, project.getIdentifier(), biden.getIdentifier(), pam.id())) - .thenReturn(Either.right(Optional.of(new Result("P", LocalDate.of(2023, Month.JANUARY, 20))))); + when(gradingService.getResult(TOKEN, project.getIdentifier(), biden.getIdentifier(), pam.id())).thenReturn( + Either.right(Optional.of(new Result("P", LocalDate.of(2023, Month.JANUARY, 20)))) + ); // results for graduation work - when(gradingService.getResult(TOKEN, project.getIdentifier(), biden.getIdentifier(), gw.id())) - .thenReturn(Either.right(Optional.empty())); + when(gradingService.getResult(TOKEN, project.getIdentifier(), biden.getIdentifier(), gw.id())).thenReturn( + Either.right(Optional.empty()) + ); LocalDate thesisUploadDate = LocalDate.of(2023, Month.FEBRUARY, 1); ZonedDateTime thesisUploadTimestamp = ZonedDateTime.of( - thesisUploadDate, - LocalTime.NOON, - ZoneId.systemDefault()); + thesisUploadDate, + LocalTime.NOON, + ZoneId.systemDefault() + ); FileDescription fileDescription = new FileDescription(); fileDescription.setDateCreated(java.util.Date.from(thesisUploadTimestamp.toInstant())); FileReference thesisDocument = new FileReference(); @@ -121,83 +125,96 @@ public class SendToExaminerTest extends SciProTest { finalThesis.setTextMatchingDocument(textMatchingReference); when(finalThesisService.findByProject(project)).thenReturn(finalThesis); - SupervisorGradingReport supervisorGradingReport = new SupervisorGradingReportFactory() - .create(project, biden); + SupervisorGradingReport supervisorGradingReport = new SupervisorGradingReportFactory().create(project, biden); supervisorGradingReport.setMotivation("The best speech I ever heard"); - when(gradingReportService.getSupervisorGradingReport(project, biden)) - .thenReturn(supervisorGradingReport); + when(gradingReportService.getSupervisorGradingReport(project, biden)).thenReturn(supervisorGradingReport); GradingReport.Grade grade = GradingReport.Grade.B; - when(gradeCalculatorService.getSupervisorCalculator(project)) - .thenReturn(fixedGrade(grade)); + when(gradeCalculatorService.getSupervisorCalculator(project)).thenReturn(fixedGrade(grade)); - when(daisyAPI.sendPublication(anyLong(), any())) - .thenReturn(true); - when(daisyAPI.sendPublicationFile(anyLong(), any(), any())) - .thenReturn(true); - when(daisyAPI.getThesis(project.getIdentifier())) - .thenReturn(Optional.of(daisyThesis())); - when(gradingService.sendTextMatchingDocument(any(), anyLong(), any(), any())) - .thenReturn(Either.right(null)); + when(daisyAPI.sendPublication(anyLong(), any())).thenReturn(true); + when(daisyAPI.sendPublicationFile(anyLong(), any(), any())).thenReturn(true); + when(daisyAPI.getThesis(project.getIdentifier())).thenReturn(Optional.of(daisyThesis())); + when(gradingService.sendTextMatchingDocument(any(), anyLong(), any(), any())).thenReturn(Either.right(null)); - when(gradingService.reportGrade(TOKEN, project.getIdentifier(), biden.getIdentifier(), gw.id(), grade.name(), thesisUploadDate)) - .thenReturn(Either.right(null)); - when(gradingService.sendProtocol(any(), anyLong(), anyLong(), anyInt(), any(), any())) - .thenReturn(Either.right(null)); + when( + gradingService.reportGrade( + TOKEN, + project.getIdentifier(), + biden.getIdentifier(), + gw.id(), + grade.name(), + thesisUploadDate + ) + ).thenReturn(Either.right(null)); + when(gradingService.sendProtocol(any(), anyLong(), anyLong(), anyInt(), any(), any())).thenReturn( + Either.right(null) + ); tester.startComponentInPage(new SendToExaminer("id", () -> project, () -> biden, () -> null)); FormTester formTester = tester.newFormTester(path("id", "form")); formTester.submit(); - verify(gradingService).reportGrade(TOKEN, project.getIdentifier(), biden.getIdentifier(), gw.id(), grade.name(), finalThesis.getUploadDate()); + verify(gradingService).reportGrade( + TOKEN, + project.getIdentifier(), + biden.getIdentifier(), + gw.id(), + grade.name(), + finalThesis.getUploadDate() + ); } @Test public void author_without_active_participations_done_should_generate_confirmation_on_sending_to_examiner() { ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); User obama = User.builder() - .firstName("Barack") - .lastName("Obama") - .emailAddress("obama@example.com") - .identifier(44) - .build(); + .firstName("Barack") + .lastName("Obama") + .emailAddress("obama@example.com") + .identifier(44) + .build(); User biden = User.builder() - .firstName("Joe") - .lastName("Biden") - .emailAddress("joe@example.com") - .identifier(46) - .build(); + .firstName("Joe") + .lastName("Biden") + .emailAddress("joe@example.com") + .identifier(46) + .build(); biden.setId(46L); Project project = Project.builder() - .title("My project") - .projectType(bachelor) - .startDate(LocalDate.of(2023, Month.JANUARY, 6)) - .headSupervisor(obama) - .projectParticipants(Set.of(biden)) - .identifier(1888) - .build(); + .title("My project") + .projectType(bachelor) + .startDate(LocalDate.of(2023, Month.JANUARY, 6)) + .headSupervisor(obama) + .projectParticipants(Set.of(biden)) + .identifier(1888) + .build(); project.setId(8L); Examination gw = new Examination( - 2, - new Name("Examensarbete", "Graduation work"), - "KX1E", - BigDecimal.valueOf(9), - List.of( - new Grade(Grade.Type.PASSING, "A"), - new Grade(Grade.Type.PASSING, "B"), - new Grade(Grade.Type.PASSING, "C"), - new Grade(Grade.Type.PASSING, "D"), - new Grade(Grade.Type.PASSING, "E"), - new Grade(Grade.Type.FAILING, "F"))); + 2, + new Name("Examensarbete", "Graduation work"), + "KX1E", + BigDecimal.valueOf(9), + List.of( + new Grade(Grade.Type.PASSING, "A"), + new Grade(Grade.Type.PASSING, "B"), + new Grade(Grade.Type.PASSING, "C"), + new Grade(Grade.Type.PASSING, "D"), + new Grade(Grade.Type.PASSING, "E"), + new Grade(Grade.Type.FAILING, "F") + ) + ); - when(gradingService.getExaminations(any(), anyLong(), anyLong())) - .thenReturn(List.of(gw)); - when(gradingService.getResult(any(), anyLong(), anyLong(), anyLong())) - .thenReturn(Either.right(Optional.empty())); + when(gradingService.getExaminations(any(), anyLong(), anyLong())).thenReturn(List.of(gw)); + when(gradingService.getResult(any(), anyLong(), anyLong(), anyLong())).thenReturn( + Either.right(Optional.empty()) + ); - tester.startComponentInPage(new SendToExaminer("id", () -> project, () -> biden, () -> "please check active participations")); + tester.startComponentInPage( + new SendToExaminer("id", () -> project, () -> biden, () -> "please check active participations") + ); tester.assertBehavior(path("id", "form", "send"), JavascriptEventConfirmation.class); } @@ -225,4 +242,4 @@ public class SendToExaminerTest extends SciProTest { } }; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/grading/SupervisorGradingReportPageTest.java b/view/src/test/java/se/su/dsv/scipro/grading/SupervisorGradingReportPageTest.java index 35811a2bc5..5f7f5cfda6 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/SupervisorGradingReportPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/SupervisorGradingReportPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; import org.apache.wicket.Page; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,21 +25,14 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.Instant; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; - -import static org.mockito.Mockito.when; - public class SupervisorGradingReportPageTest extends SupervisorPageTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); public static final Project SOME_PROJECT = Project.builder() - .title("some title") - .projectType(BACHELOR) - .startDate(LocalDate.now()) - .build(); + .title("some title") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .build(); @Override protected Class getPage() { diff --git a/view/src/test/java/se/su/dsv/scipro/grading/TemplatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/TemplatePanelTest.java index 7d9a1a3b5e..cfcdb6977a 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/TemplatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/TemplatePanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.grading; +import static se.su.dsv.scipro.grading.TemplatePanel.BACHELOR_CONTAINER; +import static se.su.dsv.scipro.grading.TemplatePanel.MASTER_15_CONTAINER; +import static se.su.dsv.scipro.grading.TemplatePanel.MASTER_30_CONTAINER; + +import java.time.LocalDate; +import java.time.Month; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; @@ -7,13 +13,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.time.Month; - -import static se.su.dsv.scipro.grading.TemplatePanel.BACHELOR_CONTAINER; -import static se.su.dsv.scipro.grading.TemplatePanel.MASTER_15_CONTAINER; -import static se.su.dsv.scipro.grading.TemplatePanel.MASTER_30_CONTAINER; - public class TemplatePanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @@ -70,7 +69,11 @@ public class TemplatePanelTest extends SciProTest { } private void startPanel(ProjectType projectType, int credits) { - Project project = Project.builder().title("some title").projectType(projectType).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .build(); project.setStartDate(LocalDate.of(2017, Month.MAY, 29)); project.setCredits(credits); panel = tester.startComponentInPage(new TemplatePanel("id", Model.of(project))); diff --git a/view/src/test/java/se/su/dsv/scipro/grading/ThesisApprovedPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/ThesisApprovedPanelTest.java index 5a13e8e940..1d1240281a 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/ThesisApprovedPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/ThesisApprovedPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.grading; +import java.time.LocalDate; +import java.time.Month; +import java.util.Date; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -10,13 +13,13 @@ import se.su.dsv.scipro.report.GradingReportTemplate; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.time.Month; -import java.util.Date; - public class ThesisApprovedPanelTest extends SciProTest { - public static Project SOME_PROJECT = Project.builder().title("Title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); + public static Project SOME_PROJECT = Project.builder() + .title("Title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); public static final FinalThesis FINAL_THESIS = new FinalThesis(); private ThesisApprovedPanel panel; @@ -32,9 +35,9 @@ public class ThesisApprovedPanelTest extends SciProTest { ProjectType projectType = new ProjectType(ProjectType.MASTER, "Master", "Master"); projectType.setId(1L); - Mockito.when(gradingReportService.getTemplate(SOME_PROJECT)).thenReturn(new GradingReportTemplate(projectType, - LocalDate.of(2024, Month.JANUARY, 1))); + Mockito.when(gradingReportService.getTemplate(SOME_PROJECT)).thenReturn( + new GradingReportTemplate(projectType, LocalDate.of(2024, Month.JANUARY, 1)) + ); panel = tester.startComponentInPage(new ThesisApprovedPanel("panel", Model.of(SOME_PROJECT))); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/grading/UploadTextMatchingPanelTest.java b/view/src/test/java/se/su/dsv/scipro/grading/UploadTextMatchingPanelTest.java index 67e4c0fd74..e1c91f9c65 100644 --- a/view/src/test/java/se/su/dsv/scipro/grading/UploadTextMatchingPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/grading/UploadTextMatchingPanelTest.java @@ -1,5 +1,17 @@ package se.su.dsv.scipro.grading; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URISyntaxException; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.Month; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.util.file.File; import org.apache.wicket.util.tester.FormTester; @@ -13,25 +25,13 @@ import se.su.dsv.scipro.finalthesis.RejectFinalThesisPanelTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.ProjectType; -import java.net.URISyntaxException; -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.Month; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class UploadTextMatchingPanelTest extends SciProTest { public static final ZonedDateTime FINAL_THESIS_APPROVED = ZonedDateTime.of( - LocalDate.of(2023, Month.MAY, 18), - LocalTime.NOON, - ZoneId.systemDefault()); + LocalDate.of(2023, Month.MAY, 18), + LocalTime.NOON, + ZoneId.systemDefault() + ); private Project project; @@ -39,10 +39,10 @@ public class UploadTextMatchingPanelTest extends SciProTest { public void setUp() { ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor"); project = Project.builder() - .title("Project title") - .projectType(bachelor) - .startDate(LocalDate.of(2023, Month.JANUARY, 17)) - .build(); + .title("Project title") + .projectType(bachelor) + .startDate(LocalDate.of(2023, Month.JANUARY, 17)) + .build(); } @Test @@ -93,7 +93,7 @@ public class UploadTextMatchingPanelTest extends SciProTest { } private FinalThesis newFinalThesisWithoutPlagiarismAnalysis() { - FinalThesis finalThesis = new FinalThesis(); + FinalThesis finalThesis = new FinalThesis(); finalThesis.setProject(project); finalThesis.setStatus(FinalThesis.Status.APPROVED); finalThesis.setDateApproved(Date.from(FINAL_THESIS_APPROVED.toInstant())); diff --git a/view/src/test/java/se/su/dsv/scipro/group/AuthorGroupPageTest.java b/view/src/test/java/se/su/dsv/scipro/group/AuthorGroupPageTest.java index ea3ecaf26b..d26475a49c 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/AuthorGroupPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/AuthorGroupPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.group; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -10,12 +15,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class AuthorGroupPageTest extends PageTest { private User student; @@ -23,11 +22,19 @@ public class AuthorGroupPageTest extends PageTest { @BeforeEach public void setUp() throws Exception { - final User supervisor = User.builder().firstName("John").lastName("Smith").emailAddress("john@example.com").build(); + final User supervisor = User.builder() + .firstName("John") + .lastName("Smith") + .emailAddress("john@example.com") + .build(); supervisor.setId(1L); student = User.builder().firstName("Stina").lastName("Student").emailAddress("stina@example.com").build(); student.setId(2L); - final Project project = Project.builder().title("Some project").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + final Project project = Project.builder() + .title("Some project") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.addProjectParticipant(student); group = new Group(); group.setId(1L); @@ -55,4 +62,4 @@ public class AuthorGroupPageTest extends PageTest { pageParameters.add(PageParameterKeys.MAP.get(Group.class), 1); return pageParameters; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/AuthorMyGroupsPageTest.java b/view/src/test/java/se/su/dsv/scipro/group/AuthorMyGroupsPageTest.java index f0fcfff968..6e07fb3b93 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/AuthorMyGroupsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/AuthorMyGroupsPageTest.java @@ -20,5 +20,4 @@ public class AuthorMyGroupsPageTest extends SciProTest { public void renders() throws Exception { tester.assertRenderedPage(SupervisorMyGroupsPage.class); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/CreateThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/group/CreateThreadPageTest.java index 7dd1f35426..26bfe10b33 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/CreateThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/CreateThreadPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.group; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -9,21 +14,27 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class CreateThreadPageTest extends PageTest { @BeforeEach public void setUp() throws Exception { - final User supervisor = User.builder().firstName("John").lastName("Smith").emailAddress("john@example.com").build(); + final User supervisor = User.builder() + .firstName("John") + .lastName("Smith") + .emailAddress("john@example.com") + .build(); supervisor.setId(1L); - final User student = User.builder().firstName("Stina").lastName("Student").emailAddress("stina@example.com").build(); + final User student = User.builder() + .firstName("Stina") + .lastName("Student") + .emailAddress("stina@example.com") + .build(); student.setId(2L); - final Project project = Project.builder().title("Some project").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + final Project project = Project.builder() + .title("Some project") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.addProjectParticipant(student); final Group group = new Group(); group.setId(1L); @@ -44,4 +55,4 @@ public class CreateThreadPageTest extends PageTest { parameters.set(PageParameterKeys.MAP.get(Group.class), "1"); return parameters; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/EditGroupPanelTest.java b/view/src/test/java/se/su/dsv/scipro/group/EditGroupPanelTest.java index fd8a498b05..d73dc26f54 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/EditGroupPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/EditGroupPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.group; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -8,15 +16,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.util.Collections; -import java.util.HashSet; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditGroupPanelTest extends SciProTest { EditGroupPanel panel; @@ -49,7 +48,11 @@ public class EditGroupPanelTest extends SciProTest { } private Project createProject() { - Project project = Project.builder().title("title").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("title") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.setId(565L); return project; } @@ -61,4 +64,4 @@ public class EditGroupPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new EditGroupPanel("id", Model.of(group))); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/GroupDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/group/GroupDetailsPanelTest.java index 90ad8e395c..9a8b4b8d52 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/GroupDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/GroupDetailsPanelTest.java @@ -45,5 +45,4 @@ public class GroupDetailsPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new GroupDetailsPanel("id", Model.of(group))); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/GroupsOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/group/GroupsOverviewPanelTest.java index 87362d2040..0b43269c14 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/GroupsOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/GroupsOverviewPanelTest.java @@ -1,71 +1,76 @@ -package se.su.dsv.scipro.group; - -import org.apache.wicket.markup.html.link.BookmarkablePageLink; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.supervisor.pages.SupervisorGroupPage; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.util.Collections; - -import static org.mockito.Mockito.when; - -public class GroupsOverviewPanelTest extends SciProTest { - - @Test - public void renders() throws Exception { - startPanel(); - } - - @Test - public void lists_all_groups_that_the_project_is_involved_in() { - mockExistingGroup(); - startPanel(); - tester.assertModelValue(path("id", "groupList"), Collections.singletonList(getGroup())); - } - - @Test - public void group_link() { - mockExistingGroup(); - startPanel(); - tester.assertBookmarkablePageLink(path("id", "groupList", 0, "groupLink"), SupervisorGroupPage.class, mockPP()); - } - - @Test - public void hide_panel_if_no_groups_are_connected_to_project() { - startPanel(); - tester.assertInvisible("id"); - } - - private PageParameters mockPP() { - PageParameters pageParameters = new PageParameters(); - pageParameters.add(PageParameterKeys.MAP.get(Group.class), 6L); - return pageParameters; - } - - private void mockExistingGroup() { - GroupService.Filter filter = new GroupService.Filter(); - filter.setProject(ObjectMother.SOME_PROJECT); - when(groupService.findAll(filter)).thenReturn(Collections.singletonList(getGroup())); - } - - private Group getGroup() { - Group group = new Group(); - group.setTitle("group title"); - group.setUser(ObjectMother.SOME_USER); - group.setId(6L); - return group; - } - - private GroupsOverviewPanel startPanel() { - return tester.startComponentInPage(new GroupsOverviewPanel("id", Model.of(ObjectMother.SOME_PROJECT), new GroupsOverviewPanel.GroupLinkSupplier() { - @Override - public BookmarkablePageLink newGroupLink(String id, PageParameters pp) { - return new BookmarkablePageLink<>(id, SupervisorGroupPage.class, pp); - } - })); - } -} +package se.su.dsv.scipro.group; + +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.apache.wicket.markup.html.link.BookmarkablePageLink; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.supervisor.pages.SupervisorGroupPage; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class GroupsOverviewPanelTest extends SciProTest { + + @Test + public void renders() throws Exception { + startPanel(); + } + + @Test + public void lists_all_groups_that_the_project_is_involved_in() { + mockExistingGroup(); + startPanel(); + tester.assertModelValue(path("id", "groupList"), Collections.singletonList(getGroup())); + } + + @Test + public void group_link() { + mockExistingGroup(); + startPanel(); + tester.assertBookmarkablePageLink(path("id", "groupList", 0, "groupLink"), SupervisorGroupPage.class, mockPP()); + } + + @Test + public void hide_panel_if_no_groups_are_connected_to_project() { + startPanel(); + tester.assertInvisible("id"); + } + + private PageParameters mockPP() { + PageParameters pageParameters = new PageParameters(); + pageParameters.add(PageParameterKeys.MAP.get(Group.class), 6L); + return pageParameters; + } + + private void mockExistingGroup() { + GroupService.Filter filter = new GroupService.Filter(); + filter.setProject(ObjectMother.SOME_PROJECT); + when(groupService.findAll(filter)).thenReturn(Collections.singletonList(getGroup())); + } + + private Group getGroup() { + Group group = new Group(); + group.setTitle("group title"); + group.setUser(ObjectMother.SOME_USER); + group.setId(6L); + return group; + } + + private GroupsOverviewPanel startPanel() { + return tester.startComponentInPage( + new GroupsOverviewPanel( + "id", + Model.of(ObjectMother.SOME_PROJECT), + new GroupsOverviewPanel.GroupLinkSupplier() { + @Override + public BookmarkablePageLink newGroupLink(String id, PageParameters pp) { + return new BookmarkablePageLink<>(id, SupervisorGroupPage.class, pp); + } + } + ) + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/group/ViewGroupProjectsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/group/ViewGroupProjectsPanelTest.java index b5ae617880..0d6fa5e346 100644 --- a/view/src/test/java/se/su/dsv/scipro/group/ViewGroupProjectsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/group/ViewGroupProjectsPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.group; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.HashSet; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,10 +17,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.HashSet; - public class ViewGroupProjectsPanelTest extends SciProTest { ViewGroupProjectsPanel panel; @@ -25,8 +24,10 @@ public class ViewGroupProjectsPanelTest extends SciProTest { @Mock protected DeliveryConfigurationService deliveryConfigurationService; + @Mock protected ReceiverConfigurationService receiverConfigurationService; + private User supervisor; private User reviewer; private User coSupervisor; @@ -50,7 +51,11 @@ public class ViewGroupProjectsPanelTest extends SciProTest { @Test public void link_to_supervisor_details_when_clicking_title() throws Exception { startPanel(); - tester.assertBookmarkablePageLink(path(panel, "projects", 0, "titleLink"), SupervisorProjectDetailsPage.class, getPageParameters()); + tester.assertBookmarkablePageLink( + path(panel, "projects", 0, "titleLink"), + SupervisorProjectDetailsPage.class, + getPageParameters() + ); } @Test @@ -93,7 +98,11 @@ public class ViewGroupProjectsPanelTest extends SciProTest { } private Project project() { - Project project = Project.builder().title("title").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); + Project project = Project.builder() + .title("title") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); project.setId(55L); project.setHeadSupervisor(supervisor); project.addReviewer(reviewer); @@ -104,4 +113,4 @@ public class ViewGroupProjectsPanelTest extends SciProTest { private void startPanel() { panel = tester.startComponentInPage(new ViewGroupProjectsPanel("id", Model.of(group))); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/latestevents/LatestEventsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/latestevents/LatestEventsPanelTest.java index d6df9496ea..001bd2830b 100644 --- a/view/src/test/java/se/su/dsv/scipro/latestevents/LatestEventsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/latestevents/LatestEventsPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.latestevents; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -20,27 +29,26 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.Pair; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class LatestEventsPanelTest extends SciProTest { - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "Some project type", "Some description"); + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType( + DegreeType.BACHELOR, + "Some project type", + "Some description" + ); Project project; LatestEventsPanel panel; @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().create(); - project = Project.builder().title("Some title").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).headSupervisor(user).build(); + project = Project.builder() + .title("Some title") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); } @Test @@ -83,8 +91,9 @@ public class LatestEventsPanelTest extends SciProTest { pf.setFileReference(fileReference); List projectFiles = new ArrayList<>(); projectFiles.add(pf); - when(projectFileService.latestUpload(isA(Project.class), eq(LatestEventsPanel.AMOUNT))).thenReturn(projectFiles); - + when(projectFileService.latestUpload(isA(Project.class), eq(LatestEventsPanel.AMOUNT))).thenReturn( + projectFiles + ); } private void addForumEvent() { @@ -100,5 +109,4 @@ public class LatestEventsPanelTest extends SciProTest { forumPosts.add(new Pair<>(ft, fp)); when(projectForumService.latestPost(isA(Project.class), eq(LatestEventsPanel.AMOUNT))).thenReturn(forumPosts); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPageTest.java b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPageTest.java index 25c0dd84e7..d3530ec58a 100644 --- a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/FirstTimeRegistrationPageTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.loginlogout.pages; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.request.mapper.parameter.PageParameters; @@ -12,9 +15,6 @@ import se.su.dsv.scipro.system.PasswordHandler; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.system.Username; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - public class FirstTimeRegistrationPageTest extends SciProTest { @Test @@ -89,7 +89,11 @@ public class FirstTimeRegistrationPageTest extends SciProTest { @Test public void has_link_to_login_page() { startPage(); - tester.assertBookmarkablePageLink("back", (Class) tester.getApplication().getHomePage(), new PageParameters()); + tester.assertBookmarkablePageLink( + "back", + (Class) tester.getApplication().getHomePage(), + new PageParameters() + ); } private void startPage() { diff --git a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LoginPageTest.java b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LoginPageTest.java index 7f9530be6e..44b7c8c455 100644 --- a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LoginPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LoginPageTest.java @@ -1,13 +1,13 @@ package se.su.dsv.scipro.loginlogout.pages; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - public class LoginPageTest extends SciProTest { @BeforeEach @@ -41,7 +41,6 @@ public class LoginPageTest extends SciProTest { tester.assertRenderedPage(LoginPage.class); } - private void mockSSOSettings(boolean showSingleSignOn) { GeneralSystemSettings settings = new GeneralSystemSettings(); settings.setShowSingleSignOn(showSingleSignOn); diff --git a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LogoutPageTest.java b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LogoutPageTest.java index a79b5b3412..879199e281 100644 --- a/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LogoutPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/loginlogout/pages/LogoutPageTest.java @@ -5,6 +5,7 @@ import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.admin.pages.AdminStartPage; public class LogoutPageTest extends PageTest { + @Override protected Class getPage() { return AdminStartPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/loginlogout/panels/LoginPanelTest.java b/view/src/test/java/se/su/dsv/scipro/loginlogout/panels/LoginPanelTest.java index 62eb654564..1e430a844a 100644 --- a/view/src/test/java/se/su/dsv/scipro/loginlogout/panels/LoginPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/loginlogout/panels/LoginPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.loginlogout.panels; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,11 +14,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - public class LoginPanelTest extends SciProTest { private LoginPanel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanelTest.java index 206adbfb13..a386b5ae81 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AbstractAdminIdeaPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.markup.html.form.FormComponent; import org.junit.jupiter.api.Assertions; @@ -10,10 +13,6 @@ import org.mockito.Mockito; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.test.DomainObjects; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - public class AbstractAdminIdeaPanelTest extends SciProTest { private AbstractAdminIdeaPanel panel; @@ -38,7 +37,7 @@ public class AbstractAdminIdeaPanelTest extends SciProTest { startPanel(); filterApplicationPeriod(wanted); - ArgumentCaptor captor = ArgumentCaptor.forClass(IdeaService.Filter.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(IdeaService.Filter.class); Mockito.verify(ideaService, Mockito.atLeastOnce()).count(captor.capture()); Assertions.assertEquals(wanted, captor.getValue().getApplicationPeriod()); } @@ -51,9 +50,14 @@ public class AbstractAdminIdeaPanelTest extends SciProTest { } private void filterApplicationPeriod(ApplicationPeriod wanted) { - FormComponent applicationPeriodFilter = (FormComponent) tester.getComponentFromLastRenderedPage(path(panel, "filter", "applicationPeriodFilter")); + FormComponent applicationPeriodFilter = (FormComponent) tester.getComponentFromLastRenderedPage( + path(panel, "filter", "applicationPeriodFilter") + ); applicationPeriodFilter.setDefaultModelObject(wanted); - tester.getRequest().getPostParameters().setParameterValue(applicationPeriodFilter.getInputName(), String.valueOf(wanted.getId())); + tester + .getRequest() + .getPostParameters() + .setParameterValue(applicationPeriodFilter.getInputName(), String.valueOf(wanted.getId())); tester.executeAjaxEvent(path(panel, "filter", "applicationPeriodFilter"), "change"); } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanelTest.java index 3087ad027d..b76620abb5 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AcceptIdeaDialogPanelTest.java @@ -1,85 +1,91 @@ -package se.su.dsv.scipro.match; - -import org.apache.wicket.model.Model; -import org.apache.wicket.util.tester.FormTester; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.system.*; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.util.Pair; - -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class AcceptIdeaDialogPanelTest extends SciProTest{ - - private Idea idea; - private ApplicationPeriod applicationPeriod; - - @BeforeEach - public void setUp() throws Exception { - when(userService.findOne(ArgumentMatchers.any())).thenReturn(ObjectMother.SOME_USER); - idea = getIdea(); - applicationPeriod = new ApplicationPeriod(); - } - - @Test - public void renders_as_confirmed() { - assert startPanel() != null; - } - - @Test - public void select_idea() { - validateStudentAcceptance(true, "test"); - startPanel(); - submitForm(); - verify(ideaService).acceptIdea(eq(idea), eq(SciProSession.get().getUser()), any(), isNull(), eq(applicationPeriod)); - } - - @Test - public void select_idea_fails() { - String errorMessage = "this didn't work!"; - validateStudentAcceptance(false, errorMessage); - startPanel(); - submitForm(); - tester.assertErrorMessages(errorMessage); - } - - private void submitForm() { - FormTester formTester = tester.newFormTester(path("panel", "form")); - formTester.setValue("contract", true); - tester.executeAjaxEvent(path("panel", "form", "selectLink"), "click"); - } - - private void validateStudentAcceptance(boolean b, String reason) { - when(ideaService.validateStudentAcceptance(idea, - SciProSession.get().getUser(), null, applicationPeriod)).thenReturn( - new Pair<>(b, reason)); - } - - private AcceptIdeaDialogPanel startPanel() { - return tester.startComponentInPage(new AcceptIdeaDialogPanel("panel", - Model.of(idea), Model.of(applicationPeriod))); - } - - private Idea getIdea() { - Language english = Language.ENGLISH; - idea = new Idea(); - idea.setId(1L); - Match match = new Match(); - match.setStatus(Idea.Status.MATCHED); - idea.setMatch(match); - idea.setType(Idea.Type.SUPERVISOR); - idea.setProjectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - idea.setLanguages(Collections.singleton(english)); - ApplicationPeriod applicationPeriod = new ApplicationPeriod(); - idea.setApplicationPeriod(applicationPeriod); - return idea; - } -} +package se.su.dsv.scipro.match; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.apache.wicket.model.Model; +import org.apache.wicket.util.tester.FormTester; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.*; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.util.Pair; + +public class AcceptIdeaDialogPanelTest extends SciProTest { + + private Idea idea; + private ApplicationPeriod applicationPeriod; + + @BeforeEach + public void setUp() throws Exception { + when(userService.findOne(ArgumentMatchers.any())).thenReturn(ObjectMother.SOME_USER); + idea = getIdea(); + applicationPeriod = new ApplicationPeriod(); + } + + @Test + public void renders_as_confirmed() { + assert startPanel() != null; + } + + @Test + public void select_idea() { + validateStudentAcceptance(true, "test"); + startPanel(); + submitForm(); + verify(ideaService).acceptIdea( + eq(idea), + eq(SciProSession.get().getUser()), + any(), + isNull(), + eq(applicationPeriod) + ); + } + + @Test + public void select_idea_fails() { + String errorMessage = "this didn't work!"; + validateStudentAcceptance(false, errorMessage); + startPanel(); + submitForm(); + tester.assertErrorMessages(errorMessage); + } + + private void submitForm() { + FormTester formTester = tester.newFormTester(path("panel", "form")); + formTester.setValue("contract", true); + tester.executeAjaxEvent(path("panel", "form", "selectLink"), "click"); + } + + private void validateStudentAcceptance(boolean b, String reason) { + when( + ideaService.validateStudentAcceptance(idea, SciProSession.get().getUser(), null, applicationPeriod) + ).thenReturn(new Pair<>(b, reason)); + } + + private AcceptIdeaDialogPanel startPanel() { + return tester.startComponentInPage( + new AcceptIdeaDialogPanel("panel", Model.of(idea), Model.of(applicationPeriod)) + ); + } + + private Idea getIdea() { + Language english = Language.ENGLISH; + idea = new Idea(); + idea.setId(1L); + Match match = new Match(); + match.setStatus(Idea.Status.MATCHED); + idea.setMatch(match); + idea.setType(Idea.Type.SUPERVISOR); + idea.setProjectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); + idea.setLanguages(Collections.singleton(english)); + ApplicationPeriod applicationPeriod = new ApplicationPeriod(); + idea.setApplicationPeriod(applicationPeriod); + return idea; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanelTest.java index 5c594b2985..a5da0c1857 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsCrudPanelTest.java @@ -1,56 +1,58 @@ -package se.su.dsv.scipro.match; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - -public class AdminIdeaDetailsCrudPanelTest extends SciProTest { - - private Idea idea; - - @BeforeEach - public void setUp() throws Exception { - final ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); - idea = new Idea(); - idea.setProjectType(bachelor); - } - - @Test - public void renders_as_supervisor_idea() { - User supervisor = User.builder().firstName("Bob").lastName("Supervisor").emailAddress("bob@example.com").build(); - Match match = new Match(); - match.setSupervisor(supervisor); - idea.setMatch(match); - startPanel(Idea.Type.SUPERVISOR); - } - - @Test - public void renders_as_student_idea() { - User author = User.builder().firstName("Anna").lastName("Author").emailAddress("anna@example.com").build(); - author.setId(23452L); - IdeaParticipation participation = new IdeaParticipation(author, idea); - idea.addIdeaParticipation(participation); - idea.setMatch(new Match()); - startPanel(Idea.Type.STUDENT); - } - - private void startPanel(Idea.Type type) { - idea.setType(type); - tester.startComponentInPage(new AdminIdeaDetailsCrudPanel("id", Model.of(idea)) { - @Override - public void updateTarget(AjaxRequestTarget target) { - - } - - @Override - public void updateAndClose(AjaxRequestTarget target) { - - } - }); - } -} +package se.su.dsv.scipro.match; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; + +public class AdminIdeaDetailsCrudPanelTest extends SciProTest { + + private Idea idea; + + @BeforeEach + public void setUp() throws Exception { + final ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); + idea = new Idea(); + idea.setProjectType(bachelor); + } + + @Test + public void renders_as_supervisor_idea() { + User supervisor = User.builder() + .firstName("Bob") + .lastName("Supervisor") + .emailAddress("bob@example.com") + .build(); + Match match = new Match(); + match.setSupervisor(supervisor); + idea.setMatch(match); + startPanel(Idea.Type.SUPERVISOR); + } + + @Test + public void renders_as_student_idea() { + User author = User.builder().firstName("Anna").lastName("Author").emailAddress("anna@example.com").build(); + author.setId(23452L); + IdeaParticipation participation = new IdeaParticipation(author, idea); + idea.addIdeaParticipation(participation); + idea.setMatch(new Match()); + startPanel(Idea.Type.STUDENT); + } + + private void startPanel(Idea.Type type) { + idea.setType(type); + tester.startComponentInPage( + new AdminIdeaDetailsCrudPanel("id", Model.of(idea)) { + @Override + public void updateTarget(AjaxRequestTarget target) {} + + @Override + public void updateAndClose(AjaxRequestTarget target) {} + } + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanelTest.java index 18db311be0..4ac6a4bdbb 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaDetailsPanelTest.java @@ -1,26 +1,27 @@ -package se.su.dsv.scipro.match; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.test.ObjectMother; - -public class AdminIdeaDetailsPanelTest extends SciProTest { - - @Test - public void renders() throws Exception { - tester.startComponentInPage(new AdminIdeaDetailsPanel("id", Model.of(idea()), new WebMarkupContainer("wmc")) { - @Override - public void update(AjaxRequestTarget target) { - } - }); - } - - private Idea idea() { - Idea idea = new ObjectMother.IdeaBuilder().create(); - idea.setType(Idea.Type.SUPERVISOR); - return idea; - } -} +package se.su.dsv.scipro.match; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.test.ObjectMother; + +public class AdminIdeaDetailsPanelTest extends SciProTest { + + @Test + public void renders() throws Exception { + tester.startComponentInPage( + new AdminIdeaDetailsPanel("id", Model.of(idea()), new WebMarkupContainer("wmc")) { + @Override + public void update(AjaxRequestTarget target) {} + } + ); + } + + private Idea idea() { + Idea idea = new ObjectMother.IdeaBuilder().create(); + idea.setType(Idea.Type.SUPERVISOR); + return idea; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanelTest.java index 87b1b16b15..931f874496 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaHistoryPanelTest.java @@ -7,6 +7,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.ExportableDataPanel; public class AdminIdeaHistoryPanelTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { tester.startComponentInPage(new AdminIdeaHistoryPanel("id", new Model<>(new Idea()))); @@ -15,7 +16,5 @@ public class AdminIdeaHistoryPanelTest extends SciProTest { @Test public void test_data_table() { tester.assertComponent(path("id", AdminIdeaHistoryPanel.DATA_TABLE), ExportableDataPanel.class); - } } - diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanelTest.java index b0897b0e92..7c58dcddc3 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaOverviewPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; + +import java.util.ArrayList; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.markup.html.panel.Panel; import org.junit.jupiter.api.Assertions; @@ -7,17 +10,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.AjaxConfirmationLink; -import java.util.ArrayList; - -import static java.util.Arrays.asList; - public class AdminIdeaOverviewPanelTest extends SciProTest { private AdminIdeaOverviewPanel panel; @@ -64,7 +63,11 @@ public class AdminIdeaOverviewPanelTest extends SciProTest { Panel dataTable = (Panel) panel.get(AbstractAdminIdeaPanel.DATA_TABLE); dataTable.visitChildren(AjaxCheckBox.class, (checkbox, visit) -> { tester.executeAjaxEvent(checkbox.getPageRelativePath(), "click"); - Mockito.verify(ideaService).inactivateIdea(ArgumentMatchers.eq(idea), ArgumentMatchers.eq(idea.isInactive()), ArgumentMatchers.eq(admin)); + Mockito.verify(ideaService).inactivateIdea( + ArgumentMatchers.eq(idea), + ArgumentMatchers.eq(idea.isInactive()), + ArgumentMatchers.eq(admin) + ); }); } @@ -75,7 +78,9 @@ public class AdminIdeaOverviewPanelTest extends SciProTest { idea.setMatch(match); idea.setType(Idea.Type.STUDENT); idea.setProjectType(new ProjectType(ProjectType.BACHELOR, "bachelor", "bachelor")); - Mockito.when(ideaService.findAll(ArgumentMatchers.any(IdeaService.Filter.class), ArgumentMatchers.any(Pageable.class))).thenReturn(asList(idea)); + Mockito.when( + ideaService.findAll(ArgumentMatchers.any(IdeaService.Filter.class), ArgumentMatchers.any(Pageable.class)) + ).thenReturn(asList(idea)); Mockito.when(ideaService.count(ArgumentMatchers.any(IdeaService.Filter.class))).thenReturn(1L); } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaPopupPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaPopupPageTest.java index 1618d30d8c..954d15d82b 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaPopupPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaPopupPageTest.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import se.su.dsv.scipro.SciProTest; -import java.util.ArrayList; - public class AdminIdeaPopupPageTest extends SciProTest { @BeforeEach diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPageTest.java index 0aa07c583d..f3aaa28097 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatisticsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import java.util.Collections; +import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.behavior.AbstractAjaxBehavior; @@ -9,12 +11,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.ExportableDataPanel; - -import java.util.Collections; -import java.util.List; +import se.su.dsv.scipro.system.Pageable; public class AdminIdeaStatisticsPageTest extends SciProTest { @@ -37,7 +36,10 @@ public class AdminIdeaStatisticsPageTest extends SciProTest { @Test public void changing_filter_updates_table() { - Behavior behavior = WicketTesterHelper.findBehavior(getStatusCheckbox(), AjaxFormChoiceComponentUpdatingBehavior.class); + Behavior behavior = WicketTesterHelper.findBehavior( + getStatusCheckbox(), + AjaxFormChoiceComponentUpdatingBehavior.class + ); tester.executeBehavior((AbstractAjaxBehavior) behavior); tester.assertComponentOnAjaxResponse(path(AdminIdeaStatisticsPage.TABLE)); } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPageTest.java index 9b4259d5ca..01da213319 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminIdeaStatusStatisticsPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -7,13 +8,13 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.test.ObjectMother; -import java.util.Collections; - public class AdminIdeaStatusStatisticsPageTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - Mockito.when(projectTypeService.findWithModule(ProjectModule.MATCH)).thenReturn(Collections.singletonList(ObjectMother.BACHELOR)); + Mockito.when(projectTypeService.findWithModule(ProjectModule.MATCH)).thenReturn( + Collections.singletonList(ObjectMother.BACHELOR) + ); tester.startPage(AdminIdeaStatusStatisticsPage.class); } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordCrudPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordCrudPanelTest.java index 470b12fab5..8909e8d781 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordCrudPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordCrudPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.match; +import java.util.Collections; +import java.util.List; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -9,14 +11,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.ExportableDataPanel; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.test.DomainObjects; -import java.util.Collections; -import java.util.List; - public class AdminKeywordCrudPanelTest extends SciProTest { AdminKeywordCrudPanel panel; @@ -50,36 +49,44 @@ public class AdminKeywordCrudPanelTest extends SciProTest { @Test public void testClickOnLazyDeleteCheckBoxRendersWMC() { - panel.visitChildren(AjaxCheckBox.class, (IVisitor) (component, visit) -> { - tester.executeAjaxEvent(component.getPageRelativePath(), "click"); - ExportableDataPanel dataPanel = (ExportableDataPanel) panel.get(AdminKeywordCrudPanel.DATA_TABLE); - tester.assertComponentOnAjaxResponse(dataPanel); - visit.stop(); - }); + panel.visitChildren( + AjaxCheckBox.class, + (IVisitor) (component, visit) -> { + tester.executeAjaxEvent(component.getPageRelativePath(), "click"); + ExportableDataPanel dataPanel = (ExportableDataPanel) panel.get(AdminKeywordCrudPanel.DATA_TABLE); + tester.assertComponentOnAjaxResponse(dataPanel); + visit.stop(); + } + ); } @Test public void testClickOnEditOpensDialog() { - panel.visitChildren(AjaxLink.class, (IVisitor) (component, visit) -> { - if(component.getParent().getParent().getId().equals(EDIT_COLUMN_ID)) { - tester.executeAjaxEvent(component.getPageRelativePath(), "click"); - tester.assertComponentOnAjaxResponse(path(panel.getId(), AdminKeywordCrudPanel.DIALOG)); + panel.visitChildren( + AjaxLink.class, + (IVisitor) (component, visit) -> { + if (component.getParent().getParent().getId().equals(EDIT_COLUMN_ID)) { + tester.executeAjaxEvent(component.getPageRelativePath(), "click"); + tester.assertComponentOnAjaxResponse(path(panel.getId(), AdminKeywordCrudPanel.DIALOG)); + } } - }); + ); } @Test public void testClickOnDeleteCallsService() { - panel.visitChildren(AjaxLink.class, (IVisitor) (component, visit) -> { - if(component.getParent().getParent().getId().equals(DELETE_COLUMN_ID)) { - tester.executeAjaxEvent(component.getPageRelativePath(), "click"); - Mockito.verify(keywordService, Mockito.times(1)).delete(ArgumentMatchers.isA(Long.class)); - tester.assertNoErrorMessage(); + panel.visitChildren( + AjaxLink.class, + (IVisitor) (component, visit) -> { + if (component.getParent().getParent().getId().equals(DELETE_COLUMN_ID)) { + tester.executeAjaxEvent(component.getPageRelativePath(), "click"); + Mockito.verify(keywordService, Mockito.times(1)).delete(ArgumentMatchers.isA(Long.class)); + tester.assertNoErrorMessage(); + } } - }); + ); } static final String EDIT_COLUMN_ID = "4"; static final String DELETE_COLUMN_ID = "5"; - } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanelTest.java index 4a291079d8..532d14e555 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminKeywordSwitchPanelTest.java @@ -14,6 +14,7 @@ import se.su.dsv.scipro.SciProTest; public class AdminKeywordSwitchPanelTest extends SciProTest { AdminKeywordSwitchPanel panel; + @Mock FeedbackPanel feedbackPanel; diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminManageIdeaPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminManageIdeaPageTest.java index bf42a6007b..f1ebc43299 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminManageIdeaPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminManageIdeaPageTest.java @@ -1,12 +1,11 @@ package se.su.dsv.scipro.match; +import java.util.ArrayList; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import se.su.dsv.scipro.SciProTest; -import java.util.ArrayList; - public class AdminManageIdeaPageTest extends SciProTest { @BeforeEach diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPageTest.java index 47d6942ad7..c1df487016 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminManageMatchPeriodsPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminManageMatchPeriodsPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminManageMatchPeriodsPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminProgramPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminProgramPageTest.java index 15936b511d..468c65a143 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminProgramPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminProgramPageTest.java @@ -1,23 +1,21 @@ package se.su.dsv.scipro.match; -import org.apache.wicket.Page; -import org.junit.jupiter.api.BeforeEach; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.PageTest; -import se.su.dsv.scipro.system.Program; - -import java.util.Collections; - import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; +import java.util.Collections; +import org.apache.wicket.Page; +import org.junit.jupiter.api.BeforeEach; +import se.su.dsv.scipro.PageTest; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.Program; + public class AdminProgramPageTest extends PageTest { AdminProgramPage page; @BeforeEach public void setUp() throws Exception { - Program program = new Program(); program.setName("Super program"); program.setNameEn("Super program"); @@ -33,5 +31,4 @@ public class AdminProgramPageTest extends PageTest { protected Class getPage() { return AdminProgramPage.class; } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanelTest.java index b7945c525a..9c9e96f2ab 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaCrudPanelTest.java @@ -6,6 +6,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.ExportableDataPanel; public class AdminResearchAreaCrudPanelTest extends SciProTest { + private AdminResearchAreaCrudPanel panel; @BeforeEach @@ -16,6 +17,5 @@ public class AdminResearchAreaCrudPanelTest extends SciProTest { @Test public void test_datatable() { tester.assertComponent(path(panel.getId(), AdminResearchAreaCrudPanel.DATA_TABLE), ExportableDataPanel.class); - } } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanelTest.java index 4b3fb8be1c..f820f43dbc 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaEditPanelTest.java @@ -1,49 +1,48 @@ -package se.su.dsv.scipro.match; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.ResearchArea; - -import java.util.Collections; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class AdminResearchAreaEditPanelTest extends SciProTest{ - - private ResearchArea area; - private Keyword keyword; - - @BeforeEach - public void setUp() throws Exception { - area = new ResearchArea(); - keyword = new Keyword("k"); - when(keywordService.findByResearchArea(area)) - .thenReturn(Collections.singletonList(keyword)); - } - - @Test - public void renders() throws Exception { - startPanel(); - } - - @Test - public void remove_relationship_link_works() { - startPanel(); - tester.clickLink(path("id", "container", "listView", "0","removeLink")); - verify(keywordService).deleteConnection(keyword, area); - } - - private void startPanel() { - tester.startComponentInPage(new AdminResearchAreaEditPanel("id", Model.of(area)) { - @Override - protected void updateTarget(AjaxRequestTarget target) { - //do something - } - }); - } - -} +package se.su.dsv.scipro.match; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.ResearchArea; + +public class AdminResearchAreaEditPanelTest extends SciProTest { + + private ResearchArea area; + private Keyword keyword; + + @BeforeEach + public void setUp() throws Exception { + area = new ResearchArea(); + keyword = new Keyword("k"); + when(keywordService.findByResearchArea(area)).thenReturn(Collections.singletonList(keyword)); + } + + @Test + public void renders() throws Exception { + startPanel(); + } + + @Test + public void remove_relationship_link_works() { + startPanel(); + tester.clickLink(path("id", "container", "listView", "0", "removeLink")); + verify(keywordService).deleteConnection(keyword, area); + } + + private void startPanel() { + tester.startComponentInPage( + new AdminResearchAreaEditPanel("id", Model.of(area)) { + @Override + protected void updateTarget(AjaxRequestTarget target) { + //do something + } + } + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanelTest.java index ac2b1dbb6f..5881ab56f7 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaKeywordPanelTest.java @@ -8,6 +8,7 @@ import se.su.dsv.scipro.components.ExportableDataPanel; import se.su.dsv.scipro.system.ResearchArea; public class AdminResearchAreaKeywordPanelTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { tester.startComponentInPage(new AdminResearchAreaKeywordPanel("id", new Model<>(new ResearchArea()))); @@ -16,6 +17,5 @@ public class AdminResearchAreaKeywordPanelTest extends SciProTest { @Test public void test_data_table() { tester.assertComponent(path("id", AdminResearchAreaKeywordPanel.DATA_TABLE), ExportableDataPanel.class); - } } diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanelTest.java index 425e707f48..e08adaa763 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminResearchAreaSupervisorPanelTest.java @@ -8,6 +8,7 @@ import se.su.dsv.scipro.components.ExportableDataPanel; import se.su.dsv.scipro.system.ResearchArea; public class AdminResearchAreaSupervisorPanelTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { tester.startComponentInPage(new AdminResearchAreaSupervisorPanel("id", new Model<>(new ResearchArea()))); @@ -16,7 +17,5 @@ public class AdminResearchAreaSupervisorPanelTest extends SciProTest { @Test public void test_data_table() { tester.assertComponent(path("id", AdminResearchAreaSupervisorPanel.DATA_TABLE), ExportableDataPanel.class); - } } - diff --git a/view/src/test/java/se/su/dsv/scipro/match/AdminUnitPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/AdminUnitPageTest.java index e215bb5869..d936c59d7a 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/AdminUnitPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/AdminUnitPageTest.java @@ -1,23 +1,21 @@ package se.su.dsv.scipro.match; -import org.apache.wicket.Page; -import org.junit.jupiter.api.BeforeEach; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.PageTest; -import se.su.dsv.scipro.system.Unit; - -import java.util.Arrays; - import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; +import java.util.Arrays; +import org.apache.wicket.Page; +import org.junit.jupiter.api.BeforeEach; +import se.su.dsv.scipro.PageTest; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.Unit; + public class AdminUnitPageTest extends PageTest { AdminUnitPage page; @BeforeEach public void setUp() throws Exception { - Unit unit = new Unit(); unit.setTitle("Super unit"); unit.setId(1L); @@ -31,4 +29,4 @@ public class AdminUnitPageTest extends PageTest { protected Class getPage() { return AdminUnitPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/EditKeywordPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/EditKeywordPanelTest.java index 4c0f938712..7983fd2807 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/EditKeywordPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/EditKeywordPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -7,10 +11,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditKeywordPanelTest extends SciProTest { EditKeywordPanel panel; @@ -40,11 +40,11 @@ public class EditKeywordPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new EditKeywordPanel("id", Model.of(keyword)) { - @Override - public void onSave(AjaxRequestTarget target) { - + panel = tester.startComponentInPage( + new EditKeywordPanel("id", Model.of(keyword)) { + @Override + public void onSave(AjaxRequestTarget target) {} } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/EditProgramPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/EditProgramPanelTest.java index 799324e1a8..e28be906fe 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/EditProgramPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/EditProgramPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -8,10 +12,6 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.Program; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditProgramPanelTest extends SciProTest { EditProgramPanel panel; @@ -27,7 +27,11 @@ public class EditProgramPanelTest extends SciProTest { @Test public void must_enter_program() { tester.executeAjaxEvent(path(panel.getId(), "form", "save"), "click"); - tester.assertErrorMessages(panel.getString("name.Required"), panel.getString("nameEn.Required"), panel.getString("code.Required")); + tester.assertErrorMessages( + panel.getString("name.Required"), + panel.getString("nameEn.Required"), + panel.getString("code.Required") + ); } @Test @@ -43,10 +47,11 @@ public class EditProgramPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new EditProgramPanel("id", Model.of(program)) { - @Override - public void onSave(AjaxRequestTarget target) { + panel = tester.startComponentInPage( + new EditProgramPanel("id", Model.of(program)) { + @Override + public void onSave(AjaxRequestTarget target) {} } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/EditResearchAreaPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/EditResearchAreaPanelTest.java index 455c67336a..281dca5b9d 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/EditResearchAreaPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/EditResearchAreaPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -8,10 +12,6 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.ResearchArea; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditResearchAreaPanelTest extends SciProTest { EditResearchAreaPanel panel; @@ -41,11 +41,11 @@ public class EditResearchAreaPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new EditResearchAreaPanel("id", Model.of(researchArea)) { - @Override - public void onSave(AjaxRequestTarget target) { - + panel = tester.startComponentInPage( + new EditResearchAreaPanel("id", Model.of(researchArea)) { + @Override + public void onSave(AjaxRequestTarget target) {} } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/EditUnitPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/EditUnitPanelTest.java index b2ad9438c3..ee5cbd9faf 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/EditUnitPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/EditUnitPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -8,10 +12,6 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.Unit; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class EditUnitPanelTest extends SciProTest { EditUnitPanel panel; @@ -41,11 +41,11 @@ public class EditUnitPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new EditUnitPanel("id", Model.of(unit)) { - @Override - public void onSave(AjaxRequestTarget target) { - + panel = tester.startComponentInPage( + new EditUnitPanel("id", Model.of(unit)) { + @Override + public void onSave(AjaxRequestTarget target) {} } - }); + ); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/IdeaDownloadPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/IdeaDownloadPanelTest.java index 603c3fe020..d3ad4e2c50 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/IdeaDownloadPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/IdeaDownloadPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.match; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.EnumSet; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,10 +11,6 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.test.ObjectMother; -import java.util.EnumSet; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class IdeaDownloadPanelTest extends SciProTest { private IdeaDownloadPanel panel; @@ -37,5 +36,4 @@ public class IdeaDownloadPanelTest extends SciProTest { public void panel_rendered() { assertNotNull(panel, "Could not render panel"); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/IdeaExportPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/IdeaExportPanelTest.java index 2a04e46827..ea5ff8fff6 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/IdeaExportPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/IdeaExportPanelTest.java @@ -1,14 +1,14 @@ package se.su.dsv.scipro.match; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class IdeaExportPanelTest extends SciProTest { IdeaExportPanel panel; @@ -98,7 +98,9 @@ public class IdeaExportPanelTest extends SciProTest { // then tester.assertComponent(path(panel, "reason"), Label.class); - String renderedReason = tester.getComponentFromLastRenderedPage(path(panel, "reason")).getDefaultModelObjectAsString(); + String renderedReason = tester + .getComponentFromLastRenderedPage(path(panel, "reason")) + .getDefaultModelObjectAsString(); assertTrue(renderedReason.contains(reason), "Rendered reason does not contain export failure reason"); } diff --git a/view/src/test/java/se/su/dsv/scipro/match/KeywordFilterPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/KeywordFilterPanelTest.java index f82ee1134e..5beaa1e974 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/KeywordFilterPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/KeywordFilterPanelTest.java @@ -1,13 +1,12 @@ package se.su.dsv.scipro.match; +import java.util.HashSet; +import java.util.Set; import org.apache.wicket.model.IModel; import org.apache.wicket.model.util.SetModel; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; -import java.util.HashSet; -import java.util.Set; - public class KeywordFilterPanelTest extends SciProTest { KeywordFilterPanel panel; @@ -22,5 +21,4 @@ public class KeywordFilterPanelTest extends SciProTest { panel = new KeywordFilterPanel("panel", model); panel = tester.startComponentInPage(panel); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/match/ManualMatchingTest.java b/view/src/test/java/se/su/dsv/scipro/match/ManualMatchingTest.java index d7fffcb737..d7733a443f 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ManualMatchingTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ManualMatchingTest.java @@ -4,8 +4,9 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class ManualMatchingTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(ManualMatching.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanelTest.java index 54e33738fe..779cadf9ef 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ProjectAllSupervisorIdeasPanelTest.java @@ -21,6 +21,8 @@ public class ProjectAllSupervisorIdeasPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new ProjectAllSupervisorIdeasPanel("id", Model.of(new ApplicationPeriod()))); + panel = tester.startComponentInPage( + new ProjectAllSupervisorIdeasPanel("id", Model.of(new ApplicationPeriod())) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPageTest.java index a015704573..fc02509226 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -11,8 +12,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.List; - public class ProjectIdeaSubmissionPageTest extends PageTest { @BeforeEach @@ -22,8 +21,12 @@ public class ProjectIdeaSubmissionPageTest extends PageTest { User user = new UserBuilder().create(); setLoggedInAs(user); Mockito.lenient().when(userService.findOne(ArgumentMatchers.isA(Long.class))).thenReturn(user); - Mockito.lenient().when(applicationPeriodService.findOne(ArgumentMatchers.anyLong())).thenReturn(applicationPeriod); - Mockito.when(applicationPeriodService.getCurrentStudentPeriods(user)).thenReturn(List.of(new OpenPeriod(applicationPeriod, List.of()))); + Mockito.lenient() + .when(applicationPeriodService.findOne(ArgumentMatchers.anyLong())) + .thenReturn(applicationPeriod); + Mockito.when(applicationPeriodService.getCurrentStudentPeriods(user)).thenReturn( + List.of(new OpenPeriod(applicationPeriod, List.of())) + ); } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanelTest.java index 7587bbb0ca..f3d54949e0 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ProjectIdeaSubmissionPanelTest.java @@ -1,5 +1,18 @@ package se.su.dsv.scipro.match; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.match.ProjectIdeaSubmissionPanel.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.markup.html.form.ValidationErrorFeedback; import org.apache.wicket.markup.html.panel.FeedbackPanel; @@ -14,20 +27,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.*; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.match.ProjectIdeaSubmissionPanel.*; - public class ProjectIdeaSubmissionPanelTest extends SciProTest { private User user; @@ -42,8 +41,9 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { setLoggedInAs(user); idea = createIdea(2, 2); - when(applicationPeriodService.getTypesForStudent(idea.getApplicationPeriod(), user)) - .thenReturn(new ArrayList<>(idea.getApplicationPeriod().getProjectTypes())); + when(applicationPeriodService.getTypesForStudent(idea.getApplicationPeriod(), user)).thenReturn( + new ArrayList<>(idea.getApplicationPeriod().getProjectTypes()) + ); when(applicationPeriodService.isOpen(idea.getApplicationPeriod())).thenReturn(true); } @@ -56,7 +56,10 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { public void submit_form_without_selecting_partner_on_bachelor_level_fails() { startPanel(idea); fillInFormAndSubmit(); - assertSpecificFeedback(feedbackPath("coAuthorFeedback"), panel.getString("too.few.authors", Model.of(createProjectType(2, 2)))); + assertSpecificFeedback( + feedbackPath("coAuthorFeedback"), + panel.getString("too.few.authors", Model.of(createProjectType(2, 2))) + ); } @Test @@ -78,21 +81,30 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { @Test public void submit_form_when_co_author_already_participating_on_another_idea() { User coAuthor = mockCoAuthor(); - when(ideaService.authorParticipatingOnOtherActiveIdea(coAuthor, idea.getApplicationPeriod(), idea)).thenReturn(true); + when(ideaService.authorParticipatingOnOtherActiveIdea(coAuthor, idea.getApplicationPeriod(), idea)).thenReturn( + true + ); startPanel(idea); fillInFormAndSubmit(coAuthor.getId(), true); - assertSpecificFeedback(feedbackPath("coAuthorFeedback"), panel.getString("coAuthorParticipating", Model.of(coAuthor))); + assertSpecificFeedback( + feedbackPath("coAuthorFeedback"), + panel.getString("coAuthorParticipating", Model.of(coAuthor)) + ); } @Test public void submit_form_when_project_type_max_authors_is_exceeded_fails() { User coAuthor = mockCoAuthor(); final Idea masterIdea = createIdea(1, 1); - when(applicationPeriodService.getTypesForStudent(masterIdea.getApplicationPeriod(), user)) - .thenReturn(new ArrayList<>(masterIdea.getApplicationPeriod().getProjectTypes())); + when(applicationPeriodService.getTypesForStudent(masterIdea.getApplicationPeriod(), user)).thenReturn( + new ArrayList<>(masterIdea.getApplicationPeriod().getProjectTypes()) + ); startPanel(masterIdea); fillInFormAndSubmit(coAuthor.getId(), true); - assertSpecificFeedback(feedbackPath("coAuthorFeedback"), panel.getString("too.many.authors", Model.of(createProjectType(1, 1)))); + assertSpecificFeedback( + feedbackPath("coAuthorFeedback"), + panel.getString("too.many.authors", Model.of(createProjectType(1, 1))) + ); } @Test @@ -104,20 +116,32 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { @Test public void can_not_submit_idea_if_already_has_active_project() { - when(projectService.getActiveProjectsByUserAndProjectType(eq(user), any(ProjectType.class))).thenReturn(Collections.singletonList(new Project())); + when(projectService.getActiveProjectsByUserAndProjectType(eq(user), any(ProjectType.class))).thenReturn( + Collections.singletonList(new Project()) + ); startPanel(idea); fillInFormAndSubmit(); - tester.assertFeedback(path(panel, "feedback"), panel.getString("you.already.have.an.active.project.on.this.level")); + tester.assertFeedback( + path(panel, "feedback"), + panel.getString("you.already.have.an.active.project.on.this.level") + ); } @Test public void can_not_submit_idea_if_co_author_has_active_project() { final User coAuthor = mockCoAuthor(); - when(projectService.getActiveProjectsByUserAndProjectType(eq(user), any(ProjectType.class))).thenReturn(List.of()); - when(projectService.getActiveProjectsByUserAndProjectType(eq(coAuthor), any(ProjectType.class))).thenReturn(Collections.singletonList(new Project())); + when(projectService.getActiveProjectsByUserAndProjectType(eq(user), any(ProjectType.class))).thenReturn( + List.of() + ); + when(projectService.getActiveProjectsByUserAndProjectType(eq(coAuthor), any(ProjectType.class))).thenReturn( + Collections.singletonList(new Project()) + ); startPanel(idea); fillInFormAndSubmit(coAuthor.getId(), true); - tester.assertFeedback(path(panel, "feedback"), panel.getString("partner.already.has.an.active.project.on.this.level", Model.of(coAuthor))); + tester.assertFeedback( + path(panel, "feedback"), + panel.getString("partner.already.has.an.active.project.on.this.level", Model.of(coAuthor)) + ); } private User mockCoAuthor() { @@ -180,7 +204,9 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { private ApplicationPeriod createApplicationPeriod(int minAuthors, int maxAuthors) { ApplicationPeriod applicationPeriod = new ApplicationPeriod(); applicationPeriod.setId(1L); - applicationPeriod.setProjectTypes(new HashSet<>(Collections.singletonList(createProjectType(minAuthors, maxAuthors)))); + applicationPeriod.setProjectTypes( + new HashSet<>(Collections.singletonList(createProjectType(minAuthors, maxAuthors))) + ); applicationPeriod.setStartDate(LocalDate.MIN); applicationPeriod.setEndDate(LocalDate.now().plusDays(1)); return applicationPeriod; @@ -199,13 +225,17 @@ public class ProjectIdeaSubmissionPanelTest extends SciProTest { private void assertSpecificFeedback(final String feedbackPanelPath, final String... messages) { final FeedbackPanel fbp = (FeedbackPanel) tester.getComponentFromLastRenderedPage(feedbackPanelPath); final IModel> model = fbp.getFeedbackMessagesModel(); - final Iterable renderedMessages = model.getObject().stream() - .map(input -> input.getMessage() instanceof ValidationErrorFeedback - ? ((ValidationErrorFeedback) input.getMessage()).getMessage().toString() - : input.getMessage().toString()).toList(); + final Iterable renderedMessages = model + .getObject() + .stream() + .map(input -> + input.getMessage() instanceof ValidationErrorFeedback + ? ((ValidationErrorFeedback) input.getMessage()).getMessage().toString() + : input.getMessage().toString() + ) + .toList(); for (String message : messages) { assertThat(renderedMessages, hasItem(equalTo(message))); } } } - diff --git a/view/src/test/java/se/su/dsv/scipro/match/ProjectMyIdeasPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/ProjectMyIdeasPanelTest.java index 4a5364fb62..405211a826 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ProjectMyIdeasPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ProjectMyIdeasPanelTest.java @@ -7,6 +7,7 @@ import se.su.dsv.scipro.components.ExportableDataPanel; import se.su.dsv.scipro.system.User; public class ProjectMyIdeasPanelTest extends SciProTest { + ProjectMyIdeasPanel panel; @BeforeEach @@ -21,6 +22,6 @@ public class ProjectMyIdeasPanelTest extends SciProTest { @Test public void testContainsDataTablePanel() { - tester.assertComponent(path(panel.getId(), ProjectMyIdeasPanel.DATA_TABLE), ExportableDataPanel.class); + tester.assertComponent(path(panel.getId(), ProjectMyIdeasPanel.DATA_TABLE), ExportableDataPanel.class); } } diff --git a/view/src/test/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPageTest.java index 0295352b43..e60f9e946a 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/ProjectNewAllSupervisorIdeasPageTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import java.util.List; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -11,8 +12,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.List; - public class ProjectNewAllSupervisorIdeasPageTest extends PageTest { @BeforeEach @@ -21,8 +20,12 @@ public class ProjectNewAllSupervisorIdeasPageTest extends PageTest { applicationPeriod.setId(1L); User user = new UserBuilder().create(); setLoggedInAs(user); - Mockito.lenient().when(applicationPeriodService.findOne(ArgumentMatchers.anyLong())).thenReturn(applicationPeriod); - Mockito.when(applicationPeriodService.getCurrentStudentPeriods(user)).thenReturn(List.of(new OpenPeriod(applicationPeriod, List.of()))); + Mockito.lenient() + .when(applicationPeriodService.findOne(ArgumentMatchers.anyLong())) + .thenReturn(applicationPeriod); + Mockito.when(applicationPeriodService.getCurrentStudentPeriods(user)).thenReturn( + List.of(new OpenPeriod(applicationPeriod, List.of())) + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanelTest.java index 5647b6f5ee..b71b817a49 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/StudentApplicationPeriodInfoPanelTest.java @@ -1,40 +1,54 @@ package se.su.dsv.scipro.match; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.User; - -import java.util.Collections; -import java.util.List; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static se.su.dsv.scipro.match.StudentApplicationPeriodInfoPanel.*; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.User; + public class StudentApplicationPeriodInfoPanelTest extends SciProTest { + @Test public void can_create_ideas_in_exempted_periods() { final ApplicationPeriod somePeriod = createSomePeriod(); - when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn(Collections.singletonList(new ExemptedPeriod(somePeriod, List.of(ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA)))); - final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage(StudentApplicationPeriodInfoPanel.class); + when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn( + Collections.singletonList( + new ExemptedPeriod(somePeriod, List.of(ApplicationPeriodExemption.Type.SUBMIT_STUDENT_IDEA)) + ) + ); + final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage( + StudentApplicationPeriodInfoPanel.class + ); tester.assertVisible(path(panel, PERIOD_LIST, 0, STUDENT_CONTAINER, CREATE)); } @Test public void can_create_ideas_in_open_periods() { final ApplicationPeriod somePeriod = createSomePeriod(); - when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn(Collections.singletonList(new OpenPeriod(somePeriod, Collections.emptyList()))); - final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage(StudentApplicationPeriodInfoPanel.class); + when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn( + Collections.singletonList(new OpenPeriod(somePeriod, Collections.emptyList())) + ); + final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage( + StudentApplicationPeriodInfoPanel.class + ); tester.assertVisible(path(panel, PERIOD_LIST, 0, STUDENT_CONTAINER, CREATE)); } @Test public void can_not_create_or_select_idea_if_already_participant() { final ApplicationPeriod somePeriod = createSomePeriod(); - when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn(Collections.singletonList(new OpenPeriod(somePeriod, Collections.emptyList()))); + when(applicationPeriodService.getCurrentStudentPeriods(any(User.class))).thenReturn( + Collections.singletonList(new OpenPeriod(somePeriod, Collections.emptyList())) + ); when(ideaService.authorParticipatingOnActiveIdea(any(User.class), eq(somePeriod))).thenReturn(true); - final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage(StudentApplicationPeriodInfoPanel.class); + final StudentApplicationPeriodInfoPanel panel = tester.startComponentInPage( + StudentApplicationPeriodInfoPanel.class + ); tester.assertInvisible(path(panel, PERIOD_LIST, 0, STUDENT_CONTAINER)); } @@ -43,4 +57,4 @@ public class StudentApplicationPeriodInfoPanelTest extends SciProTest { applicationPeriod.setId(1L); return applicationPeriod; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanelTest.java index fa73a34f0e..2462820277 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/StudentIdeaStatusColumnPanelTest.java @@ -40,9 +40,14 @@ public class StudentIdeaStatusColumnPanelTest extends SciProTest { match.setSupervisor(new User()); idea.addIdeaParticipation(new IdeaParticipation(new User(), idea)); idea.setApplicationPeriod(new ApplicationPeriod()); - Mockito.when(applicationPeriodService.courseStartHasPassed(ArgumentMatchers.any(ApplicationPeriod.class))).thenReturn(true); + Mockito.when( + applicationPeriodService.courseStartHasPassed(ArgumentMatchers.any(ApplicationPeriod.class)) + ).thenReturn(true); startPanel(); - tester.assertLabel(path(panel, "label"), "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you."); + tester.assertLabel( + path(panel, "label"), + "Matched, project creation delayed. This is under investigation and handled manually. No action needed from you." + ); } private void startPanel() { diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPageTest.java index f3af1151c3..bac616456b 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPageTest.java @@ -1,20 +1,20 @@ package se.su.dsv.scipro.match; +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.Page; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.system.User; -import java.time.LocalDate; -import java.util.Collections; - public class SupervisorAllStudentIdeasPageTest extends PageTest { @Test public void shows_label_if_no_current_period() { - Mockito.when(applicationPeriodService.getCurrentSupervisorPeriods(Mockito.any(User.class))) - .thenReturn(Collections.emptyList()); + Mockito.when(applicationPeriodService.getCurrentSupervisorPeriods(Mockito.any(User.class))).thenReturn( + Collections.emptyList() + ); startPage(); @@ -25,8 +25,9 @@ public class SupervisorAllStudentIdeasPageTest extends PageTest { public void displays_panel_with_current_period_if_there_is_one() { ApplicationPeriod applicationPeriod = createCurrentPeriod(); Mockito.when(applicationPeriodService.isVisibleForSupervisors(applicationPeriod)).thenReturn(true); - Mockito.when(applicationPeriodService.getCurrentSupervisorPeriods(Mockito.any(User.class))) - .thenReturn(Collections.singletonList(applicationPeriod)); + Mockito.when(applicationPeriodService.getCurrentSupervisorPeriods(Mockito.any(User.class))).thenReturn( + Collections.singletonList(applicationPeriod) + ); startPage(); diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanelTest.java index 4b65de31dd..72747cb125 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorAllStudentIdeasPanelTest.java @@ -1,19 +1,18 @@ package se.su.dsv.scipro.match; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; - -import java.time.LocalDate; -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.time.LocalDate; +import java.util.Collections; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; + public class SupervisorAllStudentIdeasPanelTest extends SciProTest { SupervisorAllStudentIdeasPanel panel; @@ -25,32 +24,40 @@ public class SupervisorAllStudentIdeasPanelTest extends SciProTest { @Test public void testRenders() { - panel = tester.startComponentInPage(new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod()))); + panel = tester.startComponentInPage( + new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod())) + ); tester.assertNoErrorMessage(); } @Test public void is_keyword_filtering_panel_invisible() { - panel = tester.startComponentInPage(new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod()))); + panel = tester.startComponentInPage( + new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod())) + ); tester.assertInvisible(path(panel, "keywordFilter")); } @Test public void renders_with_a_matched_student_idea() { Match match = new Match(); - match.setSupervisor(User.builder().firstName("Bob").lastName("Supervisor").emailAddress("bob@example.com").build()); + match.setSupervisor( + User.builder().firstName("Bob").lastName("Supervisor").emailAddress("bob@example.com").build() + ); final ProjectType projectType = new ProjectType(); final Idea matchedIdea = new Idea(); matchedIdea.setType(Idea.Type.STUDENT); matchedIdea.setMatch(match); matchedIdea.setProjectType(projectType); - when(ideaService.count(any(IdeaService.Filter.class))) - .thenReturn(1L); - when(ideaService.findAll(any(IdeaService.Filter.class), any(Pageable.class))) - .thenReturn(Collections.singletonList(matchedIdea)); + when(ideaService.count(any(IdeaService.Filter.class))).thenReturn(1L); + when(ideaService.findAll(any(IdeaService.Filter.class), any(Pageable.class))).thenReturn( + Collections.singletonList(matchedIdea) + ); - panel = tester.startComponentInPage(new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod()))); + panel = tester.startComponentInPage( + new SupervisorAllStudentIdeasPanel("panel", Model.of(createCurrentPeriod())) + ); } private ApplicationPeriod createCurrentPeriod() { diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanelTest.java index f03ec6479f..fa2dfe25a6 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorApplicationPeriodInfoPanelTest.java @@ -1,33 +1,41 @@ package se.su.dsv.scipro.match; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.system.User; - -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static se.su.dsv.scipro.match.SupervisorApplicationPeriodInfoPanel.PERIOD_LIST; import static se.su.dsv.scipro.match.SupervisorApplicationPeriodInfoPanel.SELECT_STUDENT; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.User; + public class SupervisorApplicationPeriodInfoPanelTest extends SciProTest { + @Test public void can_select_student_ideas_if_target_has_not_been_met() { final ApplicationPeriod somePeriod = createSomePeriod(); - when(applicationPeriodService.getCurrentSupervisorPeriods(any(User.class))).thenReturn(Collections.singletonList(somePeriod)); + when(applicationPeriodService.getCurrentSupervisorPeriods(any(User.class))).thenReturn( + Collections.singletonList(somePeriod) + ); when(targetService.hasTargetsLeft(eq(somePeriod), any(User.class))).thenReturn(true); - final SupervisorApplicationPeriodInfoPanel panel = tester.startComponentInPage(SupervisorApplicationPeriodInfoPanel.class); + final SupervisorApplicationPeriodInfoPanel panel = tester.startComponentInPage( + SupervisorApplicationPeriodInfoPanel.class + ); tester.assertVisible(path(panel, PERIOD_LIST, 0, SELECT_STUDENT)); } @Test public void can_not_select_student_ideas_if_target_has_been_met() { final ApplicationPeriod somePeriod = createSomePeriod(); - when(applicationPeriodService.getCurrentSupervisorPeriods(any(User.class))).thenReturn(Collections.singletonList(somePeriod)); + when(applicationPeriodService.getCurrentSupervisorPeriods(any(User.class))).thenReturn( + Collections.singletonList(somePeriod) + ); when(targetService.hasTargetsLeft(eq(somePeriod), any(User.class))).thenReturn(false); - final SupervisorApplicationPeriodInfoPanel panel = tester.startComponentInPage(SupervisorApplicationPeriodInfoPanel.class); + final SupervisorApplicationPeriodInfoPanel panel = tester.startComponentInPage( + SupervisorApplicationPeriodInfoPanel.class + ); tester.assertInvisible(path(panel, PERIOD_LIST, 0, SELECT_STUDENT)); } @@ -36,4 +44,4 @@ public class SupervisorApplicationPeriodInfoPanelTest extends SciProTest { somePeriod.setId(1L); return somePeriod; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanelTest.java index 644875bc53..e86cfd772f 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorEditIdeaPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.match; +import static java.util.Arrays.asList; +import static se.su.dsv.scipro.match.SupervisorEditIdeaPanel.IDEA_FORM; +import static se.su.dsv.scipro.match.SupervisorEditIdeaPanel.PROJECT_TYPE; + +import java.util.List; import org.apache.wicket.markup.html.form.RadioChoice; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Assertions; @@ -12,19 +17,15 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; -import java.util.List; - -import static java.util.Arrays.asList; -import static se.su.dsv.scipro.match.SupervisorEditIdeaPanel.IDEA_FORM; -import static se.su.dsv.scipro.match.SupervisorEditIdeaPanel.PROJECT_TYPE; - public class SupervisorEditIdeaPanelTest extends SciProTest { private SupervisorEditIdeaPanel panel; @BeforeEach public void setUp() throws Exception { - Mockito.when(userService.findOne(SciProSession.get().getUser().getId())).thenReturn(SciProSession.get().getUser()); + Mockito.when(userService.findOne(SciProSession.get().getUser().getId())).thenReturn( + SciProSession.get().getUser() + ); } @Test @@ -39,7 +40,9 @@ public class SupervisorEditIdeaPanelTest extends SciProTest { Mockito.when(projectTypeService.findWithModule(ProjectModule.MATCH)).thenReturn(choices); startPanel(); - RadioChoice projectTypeChoice = (RadioChoice) panel.get(path(IDEA_FORM, PROJECT_TYPE)); + RadioChoice projectTypeChoice = (RadioChoice) panel.get( + path(IDEA_FORM, PROJECT_TYPE) + ); Assertions.assertEquals(choices, projectTypeChoice.getChoices()); } @@ -49,7 +52,6 @@ public class SupervisorEditIdeaPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new SupervisorEditIdeaPanel("id", - Model.of(new Idea()), true)); + panel = tester.startComponentInPage(new SupervisorEditIdeaPanel("id", Model.of(new Idea()), true)); } } diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPageTest.java index 3e803aeafc..79f52bc01f 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import java.util.*; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -8,11 +12,6 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import java.util.*; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public class SupervisorIdeaDetailsPageTest extends PageTest { @BeforeEach @@ -38,4 +37,4 @@ public class SupervisorIdeaDetailsPageTest extends PageTest { protected Class getPage() { return SupervisorIdeaDetailsPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanelTest.java index 97f1504de2..89586e7f73 100755 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaDetailsPanelTest.java @@ -1,5 +1,6 @@ package se.su.dsv.scipro.match; +import java.util.Collections; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,8 +10,6 @@ import se.su.dsv.scipro.system.Language; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ResearchArea; -import java.util.Collections; - public class SupervisorIdeaDetailsPanelTest extends SciProTest { SupervisorIdeaDetailsPanel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaStartPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaStartPageTest.java index cfce46dc52..2c11a5495c 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaStartPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaStartPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class SupervisorIdeaStartPageTest extends PageTest { + @Override protected Class getPage() { return SupervisorIdeaStartPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPageTest.java index ac9c94d4ac..4d85d4a12a 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorIdeaSubmissionPageTest.java @@ -8,6 +8,7 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; public class SupervisorIdeaSubmissionPageTest extends PageTest { + @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().create(); diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanelTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanelTest.java index ea61feda65..137603b491 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorMyIdeasPanelTest.java @@ -1,24 +1,23 @@ package se.su.dsv.scipro.match; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.test.UserBuilder; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class SupervisorMyIdeasPanelTest extends SciProTest { private static final String TITLE_LINK = "id:dataTable:body:rows:1:cells:3:cell:link"; diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPageTest.java index 563fa84b9c..8b03c8af22 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorNewAllSupervisorIdeasPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class SupervisorNewAllSupervisorIdeasPageTest extends PageTest { + @Override protected Class getPage() { return SupervisorNewAllSupervisorIdeasPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPageTest.java b/view/src/test/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPageTest.java index c16967be56..680610af3a 100644 --- a/view/src/test/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/match/SupervisorSelectableStudentIdeasPageTest.java @@ -7,6 +7,7 @@ import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.util.PageParameterKeys; public class SupervisorSelectableStudentIdeasPageTest extends PageTest { + @Override protected Class getPage() { return SupervisorSelectableStudentIdeasPage.class; @@ -22,6 +23,10 @@ public class SupervisorSelectableStudentIdeasPageTest extends PageTest { @Test public void link_back_to_my_ideas() { startPage(); - tester.assertBookmarkablePageLink(SupervisorSelectableStudentIdeasPage.BACK_LINK, SupervisorIdeaStartPage.class, new PageParameters()); + tester.assertBookmarkablePageLink( + SupervisorSelectableStudentIdeasPage.BACK_LINK, + SupervisorIdeaStartPage.class, + new PageParameters() + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanelTest.java index 81ecc068ed..2226495642 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestoneActivityPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import java.util.Collections; +import java.util.List; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.markup.html.form.*; @@ -14,16 +16,13 @@ import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.internal.verification.VerificationModeFactory; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.system.Event; import se.su.dsv.scipro.system.EventService; import se.su.dsv.scipro.system.ProjectType; - -import java.util.Collections; -import java.util.List; +import se.su.dsv.scipro.system.Sort; public class EditMilestoneActivityPanelTest extends SciProTest { @@ -39,8 +38,14 @@ public class EditMilestoneActivityPanelTest extends SciProTest { projectTypes = Collections.singletonList(new ProjectType(ProjectType.BACHELOR, "bachelor", "master")); Mockito.when(projectTypeService.findAllActive()).thenReturn(projectTypes); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("title", "desc"); - Mockito.when(mileStonePhaseTemplateService.findAll(ArgumentMatchers.isA(Sort.class))).thenReturn(Collections.singletonList(phase)); - activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "Activity title", "Description"); + Mockito.when(mileStonePhaseTemplateService.findAll(ArgumentMatchers.isA(Sort.class))).thenReturn( + Collections.singletonList(phase) + ); + activity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "Activity title", + "Description" + ); activity.setMilestonePhaseTemplate(phase); startPanel(activity); @@ -106,7 +111,10 @@ public class EditMilestoneActivityPanelTest extends SciProTest { tester.clickLink(formPath(EditMilestoneActivityPanel.SAVE)); tester.assertNoErrorMessage(); - Mockito.verify(milestoneActivityTemplateService, VerificationModeFactory.times(1)).save(ArgumentMatchers.isA(MilestoneActivityTemplate.class), ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(milestoneActivityTemplateService, VerificationModeFactory.times(1)).save( + ArgumentMatchers.isA(MilestoneActivityTemplate.class), + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); } @Test @@ -139,7 +147,10 @@ public class EditMilestoneActivityPanelTest extends SciProTest { private MilestoneActivityTemplate captureSave() { ArgumentCaptor captor = ArgumentCaptor.forClass(MilestoneActivityTemplate.class); - Mockito.verify(milestoneActivityTemplateService).save(captor.capture(), ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(milestoneActivityTemplateService).save( + captor.capture(), + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); return captor.getValue(); } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestonePhasePanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestonePhasePanelTest.java index ac50fedf9f..5acec77cdb 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestonePhasePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/EditMilestonePhasePanelTest.java @@ -74,7 +74,9 @@ public class EditMilestonePhasePanelTest extends SciProTest { @Test public void testSubmitCorrectForm() { submitForm("Title", "Description"); - Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).save(ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(mileStonePhaseTemplateService, VerificationModeFactory.times(1)).save( + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/MilestoneActivityAdminPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/MilestoneActivityAdminPanelTest.java index dd503603e4..b4ee0c09b4 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/MilestoneActivityAdminPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/MilestoneActivityAdminPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import java.util.Collections; +import java.util.List; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; @@ -9,15 +11,12 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.DisplayMultiplesPanel; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.system.EventService; - -import java.util.Collections; -import java.util.List; +import se.su.dsv.scipro.system.Sort; public class MilestoneActivityAdminPanelTest extends SciProTest { @@ -31,13 +30,16 @@ public class MilestoneActivityAdminPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - - activityList = Collections.singletonList(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "Create final seminar", "Description")); + activityList = Collections.singletonList( + new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "Create final seminar", "Description") + ); phase = new MilestonePhaseTemplate("This is a title", "This is a description"); phaseList = Collections.singletonList(phase); Mockito.when(mileStonePhaseTemplateService.findAll(ArgumentMatchers.isA(Sort.class))).thenReturn(phaseList); - Mockito.when(milestoneActivityTemplateService.findByMileStonePhase(ArgumentMatchers.isA(MilestonePhaseTemplate.class))).thenReturn(activityList); + Mockito.when( + milestoneActivityTemplateService.findByMileStonePhase(ArgumentMatchers.isA(MilestonePhaseTemplate.class)) + ).thenReturn(activityList); startPanel(); } @@ -59,7 +61,11 @@ public class MilestoneActivityAdminPanelTest extends SciProTest { @Test public void testPanelContainsPhaseList() { - String listPath = path(panel.getId(), MileStoneActivityAdminPanel.LIST_CONTAINER, MileStoneActivityAdminPanel.PHASE_LIST); + String listPath = path( + panel.getId(), + MileStoneActivityAdminPanel.LIST_CONTAINER, + MileStoneActivityAdminPanel.PHASE_LIST + ); tester.assertComponent(listPath, ListView.class); tester.assertModelValue(listPath, phaseList); } @@ -105,7 +111,10 @@ public class MilestoneActivityAdminPanelTest extends SciProTest { activity.setMilestonePhaseTemplate(new MilestonePhaseTemplate("title", "desc")); boolean deleted = activity.isDeleted(); tester.executeAjaxEvent(activityPath(MileStoneActivityAdminPanel.STATE_SWITCH), "click"); - Mockito.verify(milestoneActivityTemplateService, Mockito.times(1)).save(ArgumentMatchers.eq(activity), ArgumentMatchers.isA(MilestonePhaseTemplate.class)); + Mockito.verify(milestoneActivityTemplateService, Mockito.times(1)).save( + ArgumentMatchers.eq(activity), + ArgumentMatchers.isA(MilestonePhaseTemplate.class) + ); Assertions.assertNotSame(deleted, activity.isDeleted()); } @@ -120,10 +129,24 @@ public class MilestoneActivityAdminPanelTest extends SciProTest { } private String phasePath(String... paths) { - return path(panel.getId(), MileStoneActivityAdminPanel.LIST_CONTAINER, MileStoneActivityAdminPanel.PHASE_LIST, 0, path((Object[]) paths)); + return path( + panel.getId(), + MileStoneActivityAdminPanel.LIST_CONTAINER, + MileStoneActivityAdminPanel.PHASE_LIST, + 0, + path((Object[]) paths) + ); } private String activityPath(String... paths) { - return path(panel.getId(), MileStoneActivityAdminPanel.LIST_CONTAINER, MileStoneActivityAdminPanel.PHASE_LIST, 0, MileStoneActivityAdminPanel.MILESTONE_LIST, 0, path((Object[]) paths)); + return path( + panel.getId(), + MileStoneActivityAdminPanel.LIST_CONTAINER, + MileStoneActivityAdminPanel.PHASE_LIST, + 0, + MileStoneActivityAdminPanel.MILESTONE_LIST, + 0, + path((Object[]) paths) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/MilestonePhaseAdminPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/MilestonePhaseAdminPanelTest.java index 3c32df6acd..54242f08dd 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/MilestonePhaseAdminPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/MilestonePhaseAdminPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.milestones; +import java.util.Collections; +import java.util.List; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; @@ -8,13 +10,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Sort; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.SortOrderPanel; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; - -import java.util.Collections; -import java.util.List; +import se.su.dsv.scipro.system.Sort; public class MilestonePhaseAdminPanelTest extends SciProTest { @@ -41,7 +40,11 @@ public class MilestonePhaseAdminPanelTest extends SciProTest { @Test public void testPanelContainsPhaseList() { - String listPath = path(panel.getId(), MileStonePhaseAdminPanel.LIST_CONTAINER, MileStonePhaseAdminPanel.PHASE_LIST); + String listPath = path( + panel.getId(), + MileStonePhaseAdminPanel.LIST_CONTAINER, + MileStonePhaseAdminPanel.PHASE_LIST + ); tester.assertComponent(listPath, ListView.class); tester.assertModelValue(listPath, phaseList); } @@ -85,6 +88,12 @@ public class MilestonePhaseAdminPanelTest extends SciProTest { } private String phasePath(String... paths) { - return path(panel.getId(), MileStonePhaseAdminPanel.LIST_CONTAINER, MileStonePhaseAdminPanel.PHASE_LIST, 0, path((Object[]) paths)); + return path( + panel.getId(), + MileStonePhaseAdminPanel.LIST_CONTAINER, + MileStonePhaseAdminPanel.PHASE_LIST, + 0, + path((Object[]) paths) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/pages/ProjectMilestonePageTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/pages/ProjectMilestonePageTest.java index f7f6b96d4d..d7da895384 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/pages/ProjectMilestonePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/pages/ProjectMilestonePageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.milestones.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -12,11 +16,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class ProjectMilestonePageTest extends PageTest { ProjectMileStonePage page; @@ -27,11 +26,11 @@ public class ProjectMilestonePageTest extends PageTest { User student = new UserBuilder().setFirstName("author").setLastName("1").create(); User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/pages/SupervisorMilestonePageTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/pages/SupervisorMilestonePageTest.java index 415511f473..2ca6364667 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/pages/SupervisorMilestonePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/pages/SupervisorMilestonePageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.milestones.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,11 +18,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorMilestonePageTest extends PageTest { SupervisorMileStonePage page; @@ -30,11 +29,11 @@ public class SupervisorMilestonePageTest extends PageTest { User student = new UserBuilder().setFirstName("author").setLastName("1").create(); User student2 = new UserBuilder().setFirstName("author").setLastName("2").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(isA(Long.class))).thenReturn(project); when(projectService.hasSupervisingRole(isA(Project.class), isA(User.class))).thenReturn(true); @@ -53,7 +52,6 @@ public class SupervisorMilestonePageTest extends PageTest { return pp; } - @Test public void testPageContainsOverviewPanel() { tester.assertComponent(SupervisorMileStonePage.OVERVIEW_PANEL, MileStoneOverviewPanel.class); diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCheckBoxPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCheckBoxPanelTest.java index dfda356676..98320958d9 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCheckBoxPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCheckBoxPanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.milestones.panels; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; +import static se.su.dsv.scipro.milestones.panels.MileStoneCheckBoxPanel.CHECKBOX; +import static se.su.dsv.scipro.milestones.panels.MileStoneCheckBoxPanel.CREATE_SEMINAR; + +import java.time.LocalDate; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -13,14 +20,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.*; -import static se.su.dsv.scipro.milestones.panels.MileStoneCheckBoxPanel.CHECKBOX; -import static se.su.dsv.scipro.milestones.panels.MileStoneCheckBoxPanel.CREATE_SEMINAR; - public class MilestoneCheckBoxPanelTest extends SciProTest { private MileStoneCheckBoxPanel panel; @@ -29,10 +28,10 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); DomainObjects.injectId(project, 1L); MilestoneActivityTemplate activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT); @@ -50,14 +49,20 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { @Test public void testShowCheckBoxIfActivityIsCorrectTypeAndHasNoException() { - startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), MilestoneActivityTemplate.Type.PROJECT); + startPanel( + Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), + MilestoneActivityTemplate.Type.PROJECT + ); boolean isVisible = panel.get(CHECKBOX).isVisibleInHierarchy(); assertTrue(isVisible); } @Test public void testHideCheckBoxIfActivityIsWrongType() { - startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), MilestoneActivityTemplate.Type.STUDENT); + startPanel( + Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), + MilestoneActivityTemplate.Type.STUDENT + ); boolean isVisible = panel.get(CHECKBOX).isVisibleInHierarchy(); assertFalse(isVisible); } @@ -66,27 +71,45 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { public void testClickOnProjectCheckBoxCallsCorrectServiceMethod() { String checkBoxPath = path(panel.getId(), CHECKBOX); tester.executeAjaxEvent(checkBoxPath, "click"); - verify(mileStoneService, times(1)).setConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class), eq(true)); + verify(mileStoneService, times(1)).setConfirmed( + isA(Project.class), + isA(MilestoneActivityTemplate.class), + eq(true) + ); } @Test public void testClickOnUnconfirmedStudentCheckBoxChangesToConfirmed() { MilestoneActivityTemplate activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.STUDENT); - when(mileStoneService.isConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class))).thenReturn(false); + when( + mileStoneService.isConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class)) + ).thenReturn(false); startPanel(Model.of(activity), Model.of(new User())); tester.executeAjaxEvent(path(panel.getId(), CHECKBOX), "click"); - verify(mileStoneService, times(1)).setConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class), eq(true)); + verify(mileStoneService, times(1)).setConfirmed( + isA(Project.class), + isA(User.class), + isA(MilestoneActivityTemplate.class), + eq(true) + ); } @Test public void testClickOnConfirmedStudentCheckBoxChangesToUnconfirmed() { MilestoneActivityTemplate activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.STUDENT); - when(mileStoneService.isConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class))).thenReturn(true); + when( + mileStoneService.isConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class)) + ).thenReturn(true); startPanel(Model.of(activity), Model.of(new User())); tester.executeAjaxEvent(path(panel.getId(), CHECKBOX), "click"); - verify(mileStoneService, times(1)).setConfirmed(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class), eq(false)); + verify(mileStoneService, times(1)).setConfirmed( + isA(Project.class), + isA(User.class), + isA(MilestoneActivityTemplate.class), + eq(false) + ); } @Test @@ -96,12 +119,20 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { when(mileStoneService.isConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(true); startPanel(Model.of(activity), MilestoneActivityTemplate.Type.PROJECT); tester.executeAjaxEvent(checkBoxPath, "click"); - verify(mileStoneService, times(1)).setConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class), eq(false)); + verify(mileStoneService, times(1)).setConfirmed( + isA(Project.class), + isA(MilestoneActivityTemplate.class), + eq(false) + ); when(mileStoneService.isConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(false); startPanel(Model.of(activity), MilestoneActivityTemplate.Type.PROJECT); tester.executeAjaxEvent(checkBoxPath, "click"); - verify(mileStoneService, times(1)).setConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class), eq(true)); + verify(mileStoneService, times(1)).setConfirmed( + isA(Project.class), + isA(MilestoneActivityTemplate.class), + eq(true) + ); } @Test @@ -118,7 +149,10 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { @Test public void testHideSeminarLinkIfActivityDoesNotHaveSeminarException() { when(mileStoneService.isConfirmed(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(false); - startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), MilestoneActivityTemplate.Type.PROJECT); + startPanel( + Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), + MilestoneActivityTemplate.Type.PROJECT + ); boolean isVisible = panel.get(CREATE_SEMINAR).isVisibleInHierarchy(); assertFalse(isVisible); @@ -147,11 +181,23 @@ public class MilestoneCheckBoxPanelTest extends SciProTest { } private void startPanel(final IModel activityModel, final IModel studentModel) { - panel = tester.startComponentInPage(new MileStoneCheckBoxPanel("panel", Model.of(project), activityModel, studentModel, MilestoneActivityTemplate.Type.STUDENT)); + panel = tester.startComponentInPage( + new MileStoneCheckBoxPanel( + "panel", + Model.of(project), + activityModel, + studentModel, + MilestoneActivityTemplate.Type.STUDENT + ) + ); } - private void startPanel(final IModel activityModel, final MilestoneActivityTemplate.Type type) { - panel = tester.startComponentInPage(new MileStoneCheckBoxPanel("panel", Model.of(project), activityModel, type)); + private void startPanel( + final IModel activityModel, + final MilestoneActivityTemplate.Type type + ) { + panel = tester.startComponentInPage( + new MileStoneCheckBoxPanel("panel", Model.of(project), activityModel, type) + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCounterPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCounterPanelTest.java index fbb8254762..8e24912e8c 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCounterPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneCounterPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.milestones.panels; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -10,12 +15,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class MilestoneCounterPanelTest extends SciProTest { MileStoneCounterPanel panel; @@ -27,7 +26,13 @@ public class MilestoneCounterPanelTest extends SciProTest { project = new Project(); project.setProjectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); project.setStartDate(LocalDate.now().minusDays(1)); - when(milestoneActivityTemplateService.countActivities(isA(MilestoneActivityTemplate.Type.class), eq(project.getProjectType()), eq(project.getStartDate()))).thenReturn(TOTAL); + when( + milestoneActivityTemplateService.countActivities( + isA(MilestoneActivityTemplate.Type.class), + eq(project.getProjectType()), + eq(project.getStartDate()) + ) + ).thenReturn(TOTAL); startPanel(); } @@ -49,7 +54,14 @@ public class MilestoneCounterPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new MileStoneCounterPanel("panel", Model.of(COMPLETED), MilestoneActivityTemplate.Type.PROJECT, Model.of(project))); + panel = tester.startComponentInPage( + new MileStoneCounterPanel( + "panel", + Model.of(COMPLETED), + MilestoneActivityTemplate.Type.PROJECT, + Model.of(project) + ) + ); } static final long TOTAL = 3L; diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneOverviewPanelTest.java index 6468790402..ae4ac72661 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneOverviewPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.milestones.panels; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -13,15 +21,6 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - public class MilestoneOverviewPanelTest extends SciProTest { private MileStoneOverviewPanel panel; @@ -32,14 +31,18 @@ public class MilestoneOverviewPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); DomainObjects.injectId(project, 1L); - MilestoneActivityTemplate projectActivity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT); - MilestoneActivityTemplate studentActivity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.STUDENT); + MilestoneActivityTemplate projectActivity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT + ); + MilestoneActivityTemplate studentActivity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.STUDENT + ); activityList = Arrays.asList(projectActivity, studentActivity); MilestonePhaseTemplate phase = new MilestonePhaseTemplate("This is a title", "This is a description"); phaseList = Collections.singletonList(phase); @@ -48,8 +51,12 @@ public class MilestoneOverviewPanelTest extends SciProTest { DomainObjects.injectId(milestone, 2L); when(mileStonePhaseTemplateService.findAllActive(project.getStartDate())).thenReturn(phaseList); - when(milestoneActivityTemplateService.findActiveByPhase(isA(MilestonePhaseTemplate.class), eq(project))).thenReturn(activityList); - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(milestone); + when( + milestoneActivityTemplateService.findActiveByPhase(isA(MilestonePhaseTemplate.class), eq(project)) + ).thenReturn(activityList); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + milestone + ); startPanel(); } @@ -64,7 +71,11 @@ public class MilestoneOverviewPanelTest extends SciProTest { @Test public void testPanelContainsListOfPhases() { - String listPath = path(panel.getId(), MileStoneOverviewPanel.TABLE_CONTAINER, MileStoneOverviewPanel.PHASE_LIST); + String listPath = path( + panel.getId(), + MileStoneOverviewPanel.TABLE_CONTAINER, + MileStoneOverviewPanel.PHASE_LIST + ); tester.assertComponent(listPath, ListView.class); tester.assertModelValue(listPath, phaseList); } @@ -85,18 +96,33 @@ public class MilestoneOverviewPanelTest extends SciProTest { @Test public void phase_is_hidden_if_no_activities() { - when(milestoneActivityTemplateService.findActiveByPhase(any(MilestonePhaseTemplate.class), any(Project.class))).thenReturn(Collections.emptyList()); + when( + milestoneActivityTemplateService.findActiveByPhase(any(MilestonePhaseTemplate.class), any(Project.class)) + ).thenReturn(Collections.emptyList()); startPanel(); tester.assertInvisible(phasePath()); } private String phasePath(String... paths) { - return path(panel.getId(), MileStoneOverviewPanel.TABLE_CONTAINER, MileStoneOverviewPanel.PHASE_LIST, 0, path((Object[]) paths)); + return path( + panel.getId(), + MileStoneOverviewPanel.TABLE_CONTAINER, + MileStoneOverviewPanel.PHASE_LIST, + 0, + path((Object[]) paths) + ); } private String activityPath(String... paths) { - return path(panel.getId(), MileStoneOverviewPanel.TABLE_CONTAINER, MileStoneOverviewPanel.PHASE_LIST, 0, MileStoneOverviewPanel.MILESTONE_LIST, 0, path((Object[]) paths)); + return path( + panel.getId(), + MileStoneOverviewPanel.TABLE_CONTAINER, + MileStoneOverviewPanel.PHASE_LIST, + 0, + MileStoneOverviewPanel.MILESTONE_LIST, + 0, + path((Object[]) paths) + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneProgressPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneProgressPanelTest.java index af83a2fc8b..05f0a88456 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneProgressPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneProgressPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.milestones.panels; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,13 +15,6 @@ import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class MilestoneProgressPanelTest extends SciProTest { MileStoneProgressPanel panel; @@ -26,7 +25,13 @@ public class MilestoneProgressPanelTest extends SciProTest { project = new Project(); project.setStartDate(LocalDate.now().minusDays(1)); project.setProjectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")); - when(milestoneActivityTemplateService.getActivities(isA(MilestoneActivityTemplate.Type.class), eq(project.getProjectType()), eq(project.getStartDate()))).thenReturn(activityList(5)); + when( + milestoneActivityTemplateService.getActivities( + isA(MilestoneActivityTemplate.Type.class), + eq(project.getProjectType()), + eq(project.getStartDate()) + ) + ).thenReturn(activityList(5)); startPanel(); } @@ -44,6 +49,8 @@ public class MilestoneProgressPanelTest extends SciProTest { } private void startPanel() { - panel = tester.startComponentInPage(new MileStoneProgressPanel("panel", Model.of(3L), MilestoneActivityTemplate.Type.PROJECT, Model.of(project))); + panel = tester.startComponentInPage( + new MileStoneProgressPanel("panel", Model.of(3L), MilestoneActivityTemplate.Type.PROJECT, Model.of(project)) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneStatusPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneStatusPanelTest.java index 015ebe75b8..176b162c91 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneStatusPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneStatusPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.milestones.panels; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -13,13 +19,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class MilestoneStatusPanelTest extends SciProTest { MileStoneStatusPanel panel; @@ -28,23 +27,27 @@ public class MilestoneStatusPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); DomainObjects.injectId(project, 1L); } @Test public void testRenders() throws Exception { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(true)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(true) + ); startPanel(Model.of(new MilestoneActivityTemplate())); assert panel != null; } @Test public void testCheckIconIsVisibleWithConfirmedMileStone() { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(true)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(true) + ); startPanel(Model.of(new MilestoneActivityTemplate())); boolean isVisible = panel.get(MileStoneStatusPanel.CHECK_ICON).isVisibleInHierarchy(); @@ -53,7 +56,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testCheckIconIsInvisibleWithUnconfirmedMileStone() { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(false)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(false) + ); startPanel(Model.of(new MilestoneActivityTemplate())); boolean isVisible = panel.get(MileStoneStatusPanel.CHECK_ICON).isVisibleInHierarchy(); @@ -62,7 +67,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testCheckIconIsVisibleForStudentMilestones() { - when(mileStoneService.getMileStone(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(true)); + when( + mileStoneService.getMileStone(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class)) + ).thenReturn(getMileStone(true)); startPanel(Model.of(new MilestoneActivityTemplate()), Model.of(new User())); boolean isVisible = panel.get(MileStoneStatusPanel.CHECK_ICON).isVisibleInHierarchy(); @@ -71,7 +78,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testCheckIconIsInvisibleForStudentMilestonesNotConfirmed() { - when(mileStoneService.getMileStone(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(false)); + when( + mileStoneService.getMileStone(isA(Project.class), isA(User.class), isA(MilestoneActivityTemplate.class)) + ).thenReturn(getMileStone(false)); startPanel(Model.of(new MilestoneActivityTemplate()), Model.of(new User())); boolean isVisible = panel.get(MileStoneStatusPanel.CHECK_ICON).isVisibleInHierarchy(); @@ -80,7 +89,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testNotCheckedContainerIsVisibleIfMileStoneIsCorrectTypeAndUnconfirmed() { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(false)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(false) + ); startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT))); boolean isVisible = panel.get(MileStoneStatusPanel.NOT_CHECKED).isVisibleInHierarchy(); @@ -89,7 +100,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testNotCheckedContainerIsNotVisibleIfMilestoneIsConfirmed() { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(true)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(true) + ); startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT))); boolean isVisible = panel.get(MileStoneStatusPanel.NOT_CHECKED).isVisibleInHierarchy(); @@ -98,7 +111,9 @@ public class MilestoneStatusPanelTest extends SciProTest { @Test public void testNotCheckedContainerIsNotVisibleIfMilestoneIsWrongType() { - when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn(getMileStone(false)); + when(mileStoneService.getMileStone(isA(Project.class), isA(MilestoneActivityTemplate.class))).thenReturn( + getMileStone(false) + ); startPanel(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.STUDENT))); boolean isVisible = panel.get(MileStoneStatusPanel.NOT_CHECKED).isVisibleInHierarchy(); @@ -112,10 +127,20 @@ public class MilestoneStatusPanelTest extends SciProTest { } private void startPanel(final IModel activityModel) { - panel = tester.startComponentInPage(new MileStoneStatusPanel("panel", Model.of(project), activityModel, MilestoneActivityTemplate.Type.PROJECT)); + panel = tester.startComponentInPage( + new MileStoneStatusPanel("panel", Model.of(project), activityModel, MilestoneActivityTemplate.Type.PROJECT) + ); } private void startPanel(final IModel activityModel, final IModel studentModel) { - panel = tester.startComponentInPage(new MileStoneStatusPanel("panel", Model.of(project), activityModel, studentModel, MilestoneActivityTemplate.Type.STUDENT)); + panel = tester.startComponentInPage( + new MileStoneStatusPanel( + "panel", + Model.of(project), + activityModel, + studentModel, + MilestoneActivityTemplate.Type.STUDENT + ) + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanelTest.java b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanelTest.java index 5ae2632b05..db164dcdae 100644 --- a/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/milestones/panels/MilestoneSummaryPanelTest.java @@ -1,5 +1,15 @@ package se.su.dsv.scipro.milestones.panels; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.TreeSet; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.Model; @@ -14,17 +24,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.TreeSet; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class MilestoneSummaryPanelTest extends SciProTest { MilestoneSummaryPanel panel; @@ -34,21 +33,22 @@ public class MilestoneSummaryPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - supervisorUser = new UserBuilder().setFirstName("super").setLastName("visor").create(); studentUser = new UserBuilder().setFirstName("author").setLastName("1").create(); TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(studentUser)); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .projectParticipants(projectParticipants) - .headSupervisor(supervisorUser) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .projectParticipants(projectParticipants) + .headSupervisor(supervisorUser) + .build(); DomainObjects.injectId(project, 1L); - when(milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate())).thenReturn(1L); + when( + milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate()) + ).thenReturn(1L); MilestoneActivityTemplate notEditableByStudent = new MilestoneActivityTemplate(); notEditableByStudent.setEditableByStudents(false); @@ -56,7 +56,9 @@ public class MilestoneSummaryPanelTest extends SciProTest { MilestoneActivityTemplate editableByStudent = new MilestoneActivityTemplate(); editableByStudent.setEditableByStudents(true); - when(milestoneActivityTemplateService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, project)).thenReturn(Arrays.asList(notEditableByStudent, editableByStudent)); + when( + milestoneActivityTemplateService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, project) + ).thenReturn(Arrays.asList(notEditableByStudent, editableByStudent)); startPanel(); } @@ -81,7 +83,10 @@ public class MilestoneSummaryPanelTest extends SciProTest { @Test public void testStudentContainsNameLabel() { tester.assertComponent(studentPath(MilestoneSummaryPanel.STUDENT_NAME), Label.class); - tester.assertLabel(studentPath(MilestoneSummaryPanel.STUDENT_NAME), project.getProjectParticipants().first().getFullName()); + tester.assertLabel( + studentPath(MilestoneSummaryPanel.STUDENT_NAME), + project.getProjectParticipants().first().getFullName() + ); } @Test @@ -95,7 +100,9 @@ public class MilestoneSummaryPanelTest extends SciProTest { DomainObjects.injectId(activity1, 1L); MilestoneActivityTemplate activity2 = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT); DomainObjects.injectId(activity2, 2L); - when(milestoneActivityTemplateService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, project)).thenReturn(Arrays.asList(activity1, activity2)); + when( + milestoneActivityTemplateService.getActivitiesInOrder(MilestoneActivityTemplate.Type.PROJECT, project) + ).thenReturn(Arrays.asList(activity1, activity2)); when(mileStoneService.isConfirmed(isA(Project.class), eq(activity1))).thenReturn(true); when(mileStoneService.isConfirmed(isA(Project.class), eq(activity2))).thenReturn(false); @@ -106,7 +113,9 @@ public class MilestoneSummaryPanelTest extends SciProTest { @Test public void invisibleWhenNoActiveActivities() { - when(milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate())).thenReturn(0L); + when( + milestoneActivityTemplateService.countActivities(project.getProjectType(), project.getStartDate()) + ).thenReturn(0L); startPanel(); assertFalse(panel.isVisibilityAllowed()); } diff --git a/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanelTest.java b/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanelTest.java index 80fcd31795..2c0f352d58 100644 --- a/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysCRUDPanelTest.java @@ -1,15 +1,14 @@ package se.su.dsv.scipro.nonworkdays; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.time.LocalDate; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.Model; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.nonworkperiod.NonWorkDayPeriod; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class NonWorkDaysCRUDPanelTest extends SciProTest { NonWorkDaysCRUDPanel panel; @@ -23,15 +22,15 @@ public class NonWorkDaysCRUDPanelTest extends SciProTest { nwdp.setStartDate(LocalDate.now()); nwdp.setEndDate(LocalDate.now()); return nwdp; - } private void start_panel(final NonWorkDayPeriod nwdp) { - panel = tester.startComponentInPage(new NonWorkDaysCRUDPanel("panel", Model.of(nwdp)) { - @Override - public void handleSave(AjaxRequestTarget target) { + panel = tester.startComponentInPage( + new NonWorkDaysCRUDPanel("panel", Model.of(nwdp)) { + @Override + public void handleSave(AjaxRequestTarget target) {} } - }); + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPageTest.java b/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPageTest.java index 0c0eaca7fa..07b306c9e3 100644 --- a/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/nonworkdays/NonWorkDaysPageTest.java @@ -36,4 +36,4 @@ public class NonWorkDaysPageTest extends PageTest { tester.assertComponent(NonWorkDaysPage.FEEDBACK, FeedbackPanel.class); tester.assertComponent(NonWorkDaysPage.DATA_PANEL, ExportableDataPanel.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/notes/NotesPageTest.java b/view/src/test/java/se/su/dsv/scipro/notes/NotesPageTest.java index 73a71038e1..98d2574cca 100644 --- a/view/src/test/java/se/su/dsv/scipro/notes/NotesPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notes/NotesPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.notes; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -7,11 +12,6 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class NotesPageTest extends SciProTest { @BeforeEach @@ -41,5 +41,4 @@ public class NotesPageTest extends SciProTest { assertFalse(tester.getMessages(FeedbackMessage.SUCCESS).isEmpty()); verify(noteService).save(isA(Note.class)); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/pages/NotificationsPageTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/pages/NotificationsPageTest.java index 29adede700..adb8c10df1 100755 --- a/view/src/test/java/se/su/dsv/scipro/notifications/pages/NotificationsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/pages/NotificationsPageTest.java @@ -3,7 +3,6 @@ package se.su.dsv.scipro.notifications.pages; import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; - public class NotificationsPageTest extends PageTest { @Override diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPageTest.java index 0438adc582..a421da9fc1 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/pages/SupervisorNotificationSettingsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notifications.pages; +import static org.mockito.Mockito.when; + import org.apache.wicket.Page; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,16 +15,16 @@ import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import static org.mockito.Mockito.when; - - public class SupervisorNotificationSettingsPageTest extends PageTest { - @Mock ReceiverConfigurationService receiverConfiguration; - @Mock DeliveryConfigurationService deliveryConfiguration; + @Mock + ReceiverConfigurationService receiverConfiguration; + + @Mock + DeliveryConfigurationService deliveryConfiguration; + + SupervisorNotificationSettingsPage page; - SupervisorNotificationSettingsPage page; - @BeforeEach public void setUp() { setRoles(Roles.SUPERVISOR); @@ -30,7 +32,7 @@ public class SupervisorNotificationSettingsPageTest extends PageTest { User user = new UserBuilder().create(); setLoggedInAs(user); when(userProfileService.findByUser(user)).thenReturn(new UserProfile()); - page = tester.startPage(SupervisorNotificationSettingsPage.class); + page = tester.startPage(SupervisorNotificationSettingsPage.class); } @Override @@ -40,6 +42,6 @@ public class SupervisorNotificationSettingsPageTest extends PageTest { @Test public void testPageContainsSettingsPanel() { - tester.assertComponent(SupervisorNotificationSettingsPage.SETTINGS_PANEL, NotificationSettingsPanel.class); + tester.assertComponent(SupervisorNotificationSettingsPage.SETTINGS_PANEL, NotificationSettingsPanel.class); } } diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanelTest.java index df03f0a9fe..d1d7c6bcca 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationDataPanelTest.java @@ -1,26 +1,25 @@ package se.su.dsv.scipro.notifications.panels; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.data.dataobjects.Member; -import se.su.dsv.scipro.notifications.NotificationService; -import se.su.dsv.scipro.notifications.dataobject.Notification; -import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.test.UserBuilder; - -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.data.dataobjects.Member; +import se.su.dsv.scipro.notifications.NotificationService; +import se.su.dsv.scipro.notifications.dataobject.Notification; +import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.test.UserBuilder; + public class NotificationDataPanelTest extends SciProTest { NotificationDataPanel panel; @@ -62,7 +61,9 @@ public class NotificationDataPanelTest extends SciProTest { } private void startPanel(Project project, User causedBy) { - when(notificationService.findAll(any(NotificationService.Filter.class), any(Pageable.class))).thenReturn(Collections.singletonList(createNotification(project, causedBy))); + when(notificationService.findAll(any(NotificationService.Filter.class), any(Pageable.class))).thenReturn( + Collections.singletonList(createNotification(project, causedBy)) + ); when(notificationService.count(any(NotificationService.Filter.class))).thenReturn(1L); lenient().when(projectService.getMemberType(project, causedBy)).thenReturn(Member.Type.SUPERVISOR); panel = tester.startComponentInPage(NotificationDataPanel.class); @@ -78,5 +79,4 @@ public class NotificationDataPanelTest extends SciProTest { notification.setNotificationEvent(notificationEvent); return notification; } - } diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanelTest.java index 93d156599c..eeb2c6275d 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/panels/NotificationSettingsPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.notifications.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.markup.html.form.RadioGroup; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -9,12 +15,6 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class NotificationSettingsPanelTest extends SciProTest { NotificationSettingsPanel panel; @@ -42,7 +42,11 @@ public class NotificationSettingsPanelTest extends SciProTest { // when start_panel(); - String componentPath = path(panel.getId(), NotificationSettingsPanel.FORM, NotificationSettingsPanel.MAIL_COMPILATION); + String componentPath = path( + panel.getId(), + NotificationSettingsPanel.FORM, + NotificationSettingsPanel.MAIL_COMPILATION + ); tester.assertComponent(componentPath, RadioGroup.class); RadioGroup radioGroup = (RadioGroup) tester.getComponentFromLastRenderedPage(componentPath); diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPageTest.java index 3fe53abdf5..36f45bd319 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/settings/pages/AdminNotificationSettingsPageTest.java @@ -8,8 +8,11 @@ import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationServ public class AdminNotificationSettingsPageTest extends PageTest { - @Mock ReceiverConfigurationService receiverConfiguration; - @Mock DeliveryConfigurationService deliveryConfiguration; + @Mock + ReceiverConfigurationService receiverConfiguration; + + @Mock + DeliveryConfigurationService deliveryConfiguration; @Override protected Class getPage() { diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanelTest.java index 67ff93bd3e..d996eb6014 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/AbstractReceiverConfigurationPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.notifications.settings.panels; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.list.ListView; import org.junit.jupiter.api.BeforeEach; @@ -11,21 +20,12 @@ import se.su.dsv.scipro.notifications.dataobject.Notification; import se.su.dsv.scipro.notifications.dataobject.PeerEvent; import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationService; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - //import se.su.dsv.scipro.notifications.settings.service.EventConfigurationService; public class AbstractReceiverConfigurationPanelTest extends SciProTest { - @Mock ReceiverConfigurationService receiverConfiguration; + @Mock + ReceiverConfigurationService receiverConfiguration; static Notification.Type TYPE; static List MEMBERS; @@ -63,26 +63,53 @@ public class AbstractReceiverConfigurationPanelTest extends SciProTest { @Test public void testEventRowContainsMemberList() { - tester.assertComponent(path(panel.getId(), AbstractReceiverConfigurationPanel.EVENT_LIST, 0, AbstractReceiverConfigurationPanel.CONFIGURATIONS), ListView.class); + tester.assertComponent( + path( + panel.getId(), + AbstractReceiverConfigurationPanel.EVENT_LIST, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATIONS + ), + ListView.class + ); } @Test public void testCheckboxEveryEventAndMember() { - tester.assertComponent(path(panel.getId(), - AbstractReceiverConfigurationPanel.EVENT_LIST, 0, - AbstractReceiverConfigurationPanel.CONFIGURATIONS, 0, - AbstractReceiverConfigurationPanel.CONFIGURATION), CheckBox.class); + tester.assertComponent( + path( + panel.getId(), + AbstractReceiverConfigurationPanel.EVENT_LIST, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATIONS, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATION + ), + CheckBox.class + ); } @Test public void testClickingCheckboxCallsService() { - tester.executeAjaxEvent(panel.get(path( - AbstractReceiverConfigurationPanel.EVENT_LIST, 0, - AbstractReceiverConfigurationPanel.CONFIGURATIONS, 0, - AbstractReceiverConfigurationPanel.CONFIGURATION)), - "click"); + tester.executeAjaxEvent( + panel.get( + path( + AbstractReceiverConfigurationPanel.EVENT_LIST, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATIONS, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATION + ) + ), + "click" + ); - verify(receiverConfiguration).setReceiving(eq(TYPE), isA(Enum.class), isA(Member.Type.class), isA(Boolean.class)); + verify(receiverConfiguration).setReceiving( + eq(TYPE), + isA(Enum.class), + isA(Member.Type.class), + isA(Boolean.class) + ); } @Test @@ -91,18 +118,34 @@ public class AbstractReceiverConfigurationPanelTest extends SciProTest { boolean setting = true; // when - when(receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class))).thenReturn(setting, !setting); + when( + receiverConfiguration.isReceiving(isA(Notification.Type.class), isA(Enum.class), isA(Member.Type.class)) + ).thenReturn(setting, !setting); setUp(); // Re-render the panel // then - tester.assertModelValue(path(panel.getId(), - AbstractReceiverConfigurationPanel.EVENT_LIST, 0, - AbstractReceiverConfigurationPanel.CONFIGURATIONS, 0, - AbstractReceiverConfigurationPanel.CONFIGURATION), setting); // First checkbox should be checked - tester.assertModelValue(path(panel.getId(), - AbstractReceiverConfigurationPanel.EVENT_LIST, 0, - AbstractReceiverConfigurationPanel.CONFIGURATIONS, 1, - AbstractReceiverConfigurationPanel.CONFIGURATION), !setting); // All after should not be checked + tester.assertModelValue( + path( + panel.getId(), + AbstractReceiverConfigurationPanel.EVENT_LIST, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATIONS, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATION + ), + setting + ); // First checkbox should be checked + tester.assertModelValue( + path( + panel.getId(), + AbstractReceiverConfigurationPanel.EVENT_LIST, + 0, + AbstractReceiverConfigurationPanel.CONFIGURATIONS, + 1, + AbstractReceiverConfigurationPanel.CONFIGURATION + ), + !setting + ); // All after should not be checked } } @@ -116,4 +159,4 @@ class TestPanel extends AbstractReceiverConfigurationPanel { protected List getMemberTypes() { return AbstractReceiverConfigurationPanelTest.MEMBERS; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanelTest.java index f03ce44d0f..ee010dbd19 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/DeliveryConfigurationPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notifications.settings.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.markup.html.panel.Panel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,12 +10,13 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.notifications.settings.service.DeliveryConfigurationService; import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationService; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class DeliveryConfigurationPanelTest extends SciProTest { - @Mock DeliveryConfigurationService deliveryConfigurationService; - @Mock ReceiverConfigurationService receiverConfigurationService; + @Mock + DeliveryConfigurationService deliveryConfigurationService; + + @Mock + ReceiverConfigurationService receiverConfigurationService; private Panel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanelTest.java index c88d447bfd..be2f33f3b9 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/MemberDeliveryConfigurationPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.notifications.settings.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.markup.html.panel.Panel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,12 +11,13 @@ import se.su.dsv.scipro.data.dataobjects.Member; import se.su.dsv.scipro.notifications.settings.service.DeliveryConfigurationService; import se.su.dsv.scipro.notifications.settings.service.ReceiverConfigurationService; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class MemberDeliveryConfigurationPanelTest extends SciProTest { - @Mock DeliveryConfigurationService deliveryConfigurationService; - @Mock ReceiverConfigurationService receiverConfigurationService; + @Mock + DeliveryConfigurationService deliveryConfigurationService; + + @Mock + ReceiverConfigurationService receiverConfigurationService; private Panel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanelTest.java b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanelTest.java index 14402a696b..1224116381 100644 --- a/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/notifications/settings/panels/TypeDeliveryConfigurationPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.notifications.settings.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + +import java.util.Arrays; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -9,12 +14,6 @@ import se.su.dsv.scipro.notifications.dataobject.ProjectEvent; import se.su.dsv.scipro.notifications.settings.entities.DeliveryMethod; import se.su.dsv.scipro.notifications.settings.service.DeliveryConfigurationService; -import java.util.Arrays; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.*; - public class TypeDeliveryConfigurationPanelTest extends SciProTest { @Mock @@ -24,7 +23,9 @@ public class TypeDeliveryConfigurationPanelTest extends SciProTest { @BeforeEach public void setUp() throws Exception { - panel = tester.startComponentInPage(new TypeDeliveryConfigurationPanel("panel", Notification.Type.PROJECT, ProjectEvent.Event.values())); + panel = tester.startComponentInPage( + new TypeDeliveryConfigurationPanel("panel", Notification.Type.PROJECT, ProjectEvent.Event.values()) + ); } @Test @@ -34,27 +35,49 @@ public class TypeDeliveryConfigurationPanelTest extends SciProTest { @Test public void testContainsListOfDeliveryMethods() { - tester.assertModelValue(path(panel, TypeDeliveryConfigurationPanel.METHODS), Arrays.asList(DeliveryMethod.values())); + tester.assertModelValue( + path(panel, TypeDeliveryConfigurationPanel.METHODS), + Arrays.asList(DeliveryMethod.values()) + ); } @Test public void testContainsRowForEvents() { - tester.assertModelValue(path(panel, TypeDeliveryConfigurationPanel.EVENTS), Arrays.asList(ProjectEvent.Event.values())); + tester.assertModelValue( + path(panel, TypeDeliveryConfigurationPanel.EVENTS), + Arrays.asList(ProjectEvent.Event.values()) + ); } @Test public void testEventRowContainsListOfDeliveryMethods() { - tester.assertModelValue(path(panel, TypeDeliveryConfigurationPanel.EVENTS, 0, TypeDeliveryConfigurationPanel.METHODS), Arrays.asList(DeliveryMethod.values())); + tester.assertModelValue( + path(panel, TypeDeliveryConfigurationPanel.EVENTS, 0, TypeDeliveryConfigurationPanel.METHODS), + Arrays.asList(DeliveryMethod.values()) + ); } @Test public void testClickingCheckboxUpdatesMethod() { - tester.executeAjaxEvent(path(panel.getId(), - TypeDeliveryConfigurationPanel.EVENTS, "0", - TypeDeliveryConfigurationPanel.METHODS, "0", - TypeDeliveryConfigurationPanel.METHOD), "click"); + tester.executeAjaxEvent( + path( + panel.getId(), + TypeDeliveryConfigurationPanel.EVENTS, + "0", + TypeDeliveryConfigurationPanel.METHODS, + "0", + TypeDeliveryConfigurationPanel.METHOD + ), + "click" + ); - verify(configuration, times(1)).setDelivery(isA(Notification.Type.class), isA(Enum.class), isA(DeliveryMethod.class), isA(Boolean.class), any(Optional.class)); + verify(configuration, times(1)).setDelivery( + isA(Notification.Type.class), + isA(Enum.class), + isA(DeliveryMethod.class), + isA(Boolean.class), + any(Optional.class) + ); } @Test @@ -63,18 +86,38 @@ public class TypeDeliveryConfigurationPanelTest extends SciProTest { boolean setting = true; // when - when(configuration.isDelivery(isA(Notification.Type.class), isA(Enum.class), isA(DeliveryMethod.class), eq(Optional.empty()))).thenReturn(setting, !setting); + when( + configuration.isDelivery( + isA(Notification.Type.class), + isA(Enum.class), + isA(DeliveryMethod.class), + eq(Optional.empty()) + ) + ).thenReturn(setting, !setting); setUp(); // Re-render the panel // then - tester.assertModelValue(path(panel.getId(), - TypeDeliveryConfigurationPanel.EVENTS, "0", - TypeDeliveryConfigurationPanel.METHODS, "0", - TypeDeliveryConfigurationPanel.METHOD), setting); // First checkbox should be checked - tester.assertModelValue(path(panel.getId(), - TypeDeliveryConfigurationPanel.EVENTS, "0", - TypeDeliveryConfigurationPanel.METHODS, "1", - TypeDeliveryConfigurationPanel.METHOD), !setting); // All after should not be checked - + tester.assertModelValue( + path( + panel.getId(), + TypeDeliveryConfigurationPanel.EVENTS, + "0", + TypeDeliveryConfigurationPanel.METHODS, + "0", + TypeDeliveryConfigurationPanel.METHOD + ), + setting + ); // First checkbox should be checked + tester.assertModelValue( + path( + panel.getId(), + TypeDeliveryConfigurationPanel.EVENTS, + "0", + TypeDeliveryConfigurationPanel.METHODS, + "1", + TypeDeliveryConfigurationPanel.METHOD + ), + !setting + ); // All after should not be checked } } diff --git a/view/src/test/java/se/su/dsv/scipro/panels/CommentThreadPanelTest.java b/view/src/test/java/se/su/dsv/scipro/panels/CommentThreadPanelTest.java index 7272eba0f1..44568bdb9c 100644 --- a/view/src/test/java/se/su/dsv/scipro/panels/CommentThreadPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/panels/CommentThreadPanelTest.java @@ -1,123 +1,124 @@ -package se.su.dsv.scipro.panels; - -import org.apache.wicket.model.Model; -import org.apache.wicket.util.tester.FormTester; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.peer.Comment; -import se.su.dsv.scipro.peer.CommentThread; -import se.su.dsv.scipro.peer.PeerReview; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.Dates; -import se.su.dsv.scipro.test.UserBuilder; - -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.*; -import static se.su.dsv.scipro.panels.CommentThreadPanel.*; - -public class CommentThreadPanelTest extends SciProTest { - - private CommentThreadPanel panel; - private PeerReview review; - private List commentList; - private User creatorUser; - - @BeforeEach - public void setUp() throws Exception { - Project project = Project.builder().title("someP").projectType(new ProjectType(DegreeType.BACHELOR, "x", "s")).startDate(LocalDate.now()).build(); - review = new PeerReview(); - review.setProject(project); - review.setComment("a;".repeat(PeerReview.MINIMUM_COMMENT_LENGTH_IF_NO_ANSWERS)); - review.setDeadline(Dates.tomorrow()); - review.submit(); - creatorUser = new UserBuilder().create(); - commentList = setUpList(); - } - - @Test - public void testRenders() throws Exception { - startPanel(); - assertNotNull(panel); - } - - @Test - public void testStartWithACommentThreadDoesNotCreateANewOne() { - when(commentThreadService.getCommentThread(review)).thenReturn(new CommentThread(new PeerReview())); - startPanel(); - verify(commentThreadService, never()).save(any(CommentThread.class)); - - } - - @Test - public void testSubmitEmptyFormRendersErrorFeedback() { - startPanel(); - FormTester formTester = tester.newFormTester(path(panel.getId(), COMMENT_FORM)); - formTester.submit(); - tester.assertErrorMessages(panel.getString("commentTextArea.Required")); - } - - @Test - public void testSubmitFormWithCorrectInput() { - startPanel(); - FormTester formTester = tester.newFormTester(path(panel.getId(), COMMENT_FORM)); - formTester.setValue(COMMENT_TEXT_AREA, "comment"); - formTester.submit(); - tester.assertNoErrorMessage(); - verify(commentService).save((Comment) formTester.getForm().getModelObject()); - } - - @Test - public void testCommentListView() { - startPanel(); - tester.assertModelValue(path(panel.getId(), COMMENTS), commentList); - } - - @Test - public void testDeleteLinkIsVisibleForCreator() { - setLoggedInAs(creatorUser); - startPanel(); - - boolean isVisible = panel.get(path(COMMENTS, 0, DELETE_LINK)).isVisibleInHierarchy(); - assertTrue(isVisible); - } - - - @Test - public void testDeleteLinkIsInvisibleForNonCreators() { - setLoggedInAs(new UserBuilder().create()); - startPanel(); - - tester.assertInvisible(path(panel, COMMENTS, 0, DELETE_LINK)); - } - - @Test - public void testClickDelete() { - setLoggedInAs(creatorUser); - startPanel(); - tester.clickLink(path(panel.getId(), COMMENTS, 0, DELETE_LINK)); - verify(commentService).delete(any(Comment.class)); - } - - private List setUpList() { - Comment comment = new Comment(creatorUser, null); - comment.setCreator(creatorUser); - comment.setComment("comment"); - List commentList = Collections.singletonList(comment); - when(commentThreadService.getCommentThread(review)).thenReturn(new CommentThread(new PeerReview())); - when(commentService.findByCommentThread(isA(CommentThread.class))).thenReturn(commentList); - return commentList; - } - - private void startPanel() { - panel = tester.startComponentInPage(new CommentThreadPanel("panel", Model.of(review))); - } -} +package se.su.dsv.scipro.panels; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; +import static se.su.dsv.scipro.panels.CommentThreadPanel.*; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; +import org.apache.wicket.model.Model; +import org.apache.wicket.util.tester.FormTester; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.peer.Comment; +import se.su.dsv.scipro.peer.CommentThread; +import se.su.dsv.scipro.peer.PeerReview; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.Dates; +import se.su.dsv.scipro.test.UserBuilder; + +public class CommentThreadPanelTest extends SciProTest { + + private CommentThreadPanel panel; + private PeerReview review; + private List commentList; + private User creatorUser; + + @BeforeEach + public void setUp() throws Exception { + Project project = Project.builder() + .title("someP") + .projectType(new ProjectType(DegreeType.BACHELOR, "x", "s")) + .startDate(LocalDate.now()) + .build(); + review = new PeerReview(); + review.setProject(project); + review.setComment("a;".repeat(PeerReview.MINIMUM_COMMENT_LENGTH_IF_NO_ANSWERS)); + review.setDeadline(Dates.tomorrow()); + review.submit(); + creatorUser = new UserBuilder().create(); + commentList = setUpList(); + } + + @Test + public void testRenders() throws Exception { + startPanel(); + assertNotNull(panel); + } + + @Test + public void testStartWithACommentThreadDoesNotCreateANewOne() { + when(commentThreadService.getCommentThread(review)).thenReturn(new CommentThread(new PeerReview())); + startPanel(); + verify(commentThreadService, never()).save(any(CommentThread.class)); + } + + @Test + public void testSubmitEmptyFormRendersErrorFeedback() { + startPanel(); + FormTester formTester = tester.newFormTester(path(panel.getId(), COMMENT_FORM)); + formTester.submit(); + tester.assertErrorMessages(panel.getString("commentTextArea.Required")); + } + + @Test + public void testSubmitFormWithCorrectInput() { + startPanel(); + FormTester formTester = tester.newFormTester(path(panel.getId(), COMMENT_FORM)); + formTester.setValue(COMMENT_TEXT_AREA, "comment"); + formTester.submit(); + tester.assertNoErrorMessage(); + verify(commentService).save((Comment) formTester.getForm().getModelObject()); + } + + @Test + public void testCommentListView() { + startPanel(); + tester.assertModelValue(path(panel.getId(), COMMENTS), commentList); + } + + @Test + public void testDeleteLinkIsVisibleForCreator() { + setLoggedInAs(creatorUser); + startPanel(); + + boolean isVisible = panel.get(path(COMMENTS, 0, DELETE_LINK)).isVisibleInHierarchy(); + assertTrue(isVisible); + } + + @Test + public void testDeleteLinkIsInvisibleForNonCreators() { + setLoggedInAs(new UserBuilder().create()); + startPanel(); + + tester.assertInvisible(path(panel, COMMENTS, 0, DELETE_LINK)); + } + + @Test + public void testClickDelete() { + setLoggedInAs(creatorUser); + startPanel(); + tester.clickLink(path(panel.getId(), COMMENTS, 0, DELETE_LINK)); + verify(commentService).delete(any(Comment.class)); + } + + private List setUpList() { + Comment comment = new Comment(creatorUser, null); + comment.setCreator(creatorUser); + comment.setComment("comment"); + List commentList = Collections.singletonList(comment); + when(commentThreadService.getCommentThread(review)).thenReturn(new CommentThread(new PeerReview())); + when(commentService.findByCommentThread(isA(CommentThread.class))).thenReturn(commentList); + return commentList; + } + + private void startPanel() { + panel = tester.startComponentInPage(new CommentThreadPanel("panel", Model.of(review))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerReviewPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerReviewPageTest.java index 151132ffc3..c656d54e48 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerReviewPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerReviewPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Date; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,12 +18,6 @@ import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Date; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public class AdminPeerReviewPageTest extends SciProTest { @BeforeEach @@ -51,7 +50,9 @@ public class AdminPeerReviewPageTest extends SciProTest { peerReview.setPeerRequest(peerRequest); peerReview.setDateCreated(new Date()); peerReview.setReviewer(reviewerUser); - peerReview.setProject(Project.builder().title("some reviewer project").projectType(projectType).startDate(LocalDate.now()).build()); + peerReview.setProject( + Project.builder().title("some reviewer project").projectType(projectType).startDate(LocalDate.now()).build() + ); when(peerReviewService.findOne(anyLong())).thenReturn(peerReview); } diff --git a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerSettingsPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerSettingsPageTest.java index 59fef00b1f..7568862b69 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerSettingsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeerSettingsPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminPeerSettingsPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminPeerSettingsPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeersPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeersPageTest.java index f90bb2eaec..ccd5a35bd9 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/AdminPeersPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/AdminPeersPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminPeersPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminPeersPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/DisplayQuestionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/DisplayQuestionPanelTest.java index fbb66e7b45..320f9e4e7a 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/DisplayQuestionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/DisplayQuestionPanelTest.java @@ -1,69 +1,69 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.checklist.ChecklistAnswerEnum; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class DisplayQuestionPanelTest extends SciProTest { - - private int index = 1; - - @Test - public void renders_with_green_answer() { - startPanel(ChecklistAnswerEnum.GREEN, "motivation"); - } - - @Test - public void renders_with_red_answer() { - startPanel(ChecklistAnswerEnum.RED, "motivation"); - } - - @Test - public void renders_with_yellow_answer() { - startPanel(ChecklistAnswerEnum.YELLOW, "motivation"); - } - - @Test - public void renders_with_not_applicable_answer() { - startPanel(ChecklistAnswerEnum.NOT_APPLICABLE, "motivation"); - } - - @Test - public void throws_exception_with_unknown_answer() { - assertThrows(IllegalStateException.class, () -> - startPanel(ChecklistAnswerEnum.NO_ANSWER, "motivation")); - } - - @Test - public void question_number_is_index_plus_one() { - startPanel(ChecklistAnswerEnum.GREEN, "motivation"); - tester.assertLabel(path("id", "questionNumber"), String.valueOf(index + 1)); - } - - @Test - public void no_motivation_label_invisible_if_motivation_exists() { - startPanel(ChecklistAnswerEnum.GREEN, "motivation"); - tester.assertInvisible(path("id", "noMotivation")); - } - - @Test - public void no_motivation_label_visible_if_motivation_is_missing() { - startPanel(ChecklistAnswerEnum.GREEN, null); - tester.assertVisible(path("id", "noMotivation")); - } - - private DisplayQuestionPanel startPanel(ChecklistAnswerEnum answer, String motivation) { - return tester.startComponentInPage(new DisplayQuestionPanel("id", Model.of(getAnswer(answer, motivation)), index)); - } - - private Answer getAnswer(ChecklistAnswerEnum cqa, String motivation) { - Answer answer = new Answer(); - answer.setAnswer(cqa); - answer.setMotivation(motivation); - return answer; - } - -} +package se.su.dsv.scipro.peer; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.checklist.ChecklistAnswerEnum; + +public class DisplayQuestionPanelTest extends SciProTest { + + private int index = 1; + + @Test + public void renders_with_green_answer() { + startPanel(ChecklistAnswerEnum.GREEN, "motivation"); + } + + @Test + public void renders_with_red_answer() { + startPanel(ChecklistAnswerEnum.RED, "motivation"); + } + + @Test + public void renders_with_yellow_answer() { + startPanel(ChecklistAnswerEnum.YELLOW, "motivation"); + } + + @Test + public void renders_with_not_applicable_answer() { + startPanel(ChecklistAnswerEnum.NOT_APPLICABLE, "motivation"); + } + + @Test + public void throws_exception_with_unknown_answer() { + assertThrows(IllegalStateException.class, () -> startPanel(ChecklistAnswerEnum.NO_ANSWER, "motivation")); + } + + @Test + public void question_number_is_index_plus_one() { + startPanel(ChecklistAnswerEnum.GREEN, "motivation"); + tester.assertLabel(path("id", "questionNumber"), String.valueOf(index + 1)); + } + + @Test + public void no_motivation_label_invisible_if_motivation_exists() { + startPanel(ChecklistAnswerEnum.GREEN, "motivation"); + tester.assertInvisible(path("id", "noMotivation")); + } + + @Test + public void no_motivation_label_visible_if_motivation_is_missing() { + startPanel(ChecklistAnswerEnum.GREEN, null); + tester.assertVisible(path("id", "noMotivation")); + } + + private DisplayQuestionPanel startPanel(ChecklistAnswerEnum answer, String motivation) { + return tester.startComponentInPage( + new DisplayQuestionPanel("id", Model.of(getAnswer(answer, motivation)), index) + ); + } + + private Answer getAnswer(ChecklistAnswerEnum cqa, String motivation) { + Answer answer = new Answer(); + answer.setAnswer(cqa); + answer.setMotivation(motivation); + return answer; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/ExpiredRequestWorkerTest.java b/view/src/test/java/se/su/dsv/scipro/peer/ExpiredRequestWorkerTest.java index 3c9ba94de2..e2ccb20de5 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/ExpiredRequestWorkerTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/ExpiredRequestWorkerTest.java @@ -1,6 +1,13 @@ package se.su.dsv.scipro.peer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import com.google.common.eventbus.EventBus; +import java.time.ZonedDateTime; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,21 +21,15 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.ProjectTypeSettings; import se.su.dsv.scipro.test.DomainObjects; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) public class ExpiredRequestWorkerTest { @Mock PeerRequestService peerRequestService; + @Mock EventBus eventBus; + @Mock GeneralSystemSettingsService settingsService; @@ -79,7 +80,9 @@ public class ExpiredRequestWorkerTest { currentRequest.setProject(project); currentRequest.setDateCreated(new Date()); - doReturn(Arrays.asList(currentRequest, expiredRequest)).when(peerRequestService).findByStatus(RequestStatus.WAITING); + doReturn(Arrays.asList(currentRequest, expiredRequest)) + .when(peerRequestService) + .findByStatus(RequestStatus.WAITING); // when worker.doWork(); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/LatestReviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/LatestReviewPanelTest.java index 8fb5f53ca5..3ad29817cc 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/LatestReviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/LatestReviewPanelTest.java @@ -1,89 +1,90 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.peer.LatestReviewPanel.*; - -public class LatestReviewPanelTest extends SciProTest { - - public static final String PANEL = "id"; - public static final boolean DISPLAY_REVIEWS = true; - public static final boolean NOT_DISPLAY_REVIEWS = false; - public static final boolean NOT_PUBLIC = false; - public static final boolean PUBLIC_REVIEWS = true; - - @Test - public void panel_visible_if_display_is_active_in_settings() { - startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); - tester.assertVisible(PANEL); - } - - @Test - public void not_visible_if_display_is_inactivated_in_settings() { - startPanel(NOT_DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); - tester.assertInvisible(PANEL); - } - - @Test - public void displays_reviews() { - startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); - tester.assertModelValue(path(PANEL, LIST_VIEW), getReviewList()); - } - - @Test - public void no_reviewers_label_visible_if_no_reviews_are_available() { - startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, new ArrayList()); - tester.assertVisible(path(PANEL, NO_REVIEWERS)); - } - - @Test - public void no_reviewers_label_invisible_if_reviews_are_available() { - startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); - tester.assertInvisible(path(PANEL, NO_REVIEWERS)); - } - - @Test - public void link_to_review_from_list() { - startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); - PageParameters parameters = new PageParameters(); - parameters.add(PageParameterKeys.MAP.get(PeerReview.class), getReviewList().get(0).getId()); - tester.assertBookmarkablePageLink(path(PANEL, LIST_VIEW, 0, REVIEW_LINK), ViewPeerReviewPage.class, parameters); - } - - @Test - public void link_to_review_disabled_if_not_activated_in_settings() { - startPanel(DISPLAY_REVIEWS, NOT_PUBLIC, getReviewList()); - tester.assertDisabled(path(PANEL, LIST_VIEW, 0, REVIEW_LINK)); - } - - private void startPanel(boolean displayReviews, boolean reviewsActivated, List reviewList) { - lenient().when(peerReviewService.findAllCompleted(any(Pageable.class))).thenReturn(reviewList); - when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(createSettings(displayReviews, reviewsActivated)); - tester.startComponentInPage(new LatestReviewPanel(PANEL)); - } - - private GeneralSystemSettings createSettings(boolean displayLatestReviews, boolean reviewsActivated) { - GeneralSystemSettings settings = new GeneralSystemSettings(); - settings.setPeerDisplayLatestReviews(displayLatestReviews); - settings.setPublicReviewsActivated(reviewsActivated); - return settings; - } - - private List getReviewList() { - PeerReview peerReview = new PeerReview(); - peerReview.setId(5L); - return Collections.singletonList(peerReview); - } -} +package se.su.dsv.scipro.peer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.peer.LatestReviewPanel.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class LatestReviewPanelTest extends SciProTest { + + public static final String PANEL = "id"; + public static final boolean DISPLAY_REVIEWS = true; + public static final boolean NOT_DISPLAY_REVIEWS = false; + public static final boolean NOT_PUBLIC = false; + public static final boolean PUBLIC_REVIEWS = true; + + @Test + public void panel_visible_if_display_is_active_in_settings() { + startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); + tester.assertVisible(PANEL); + } + + @Test + public void not_visible_if_display_is_inactivated_in_settings() { + startPanel(NOT_DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); + tester.assertInvisible(PANEL); + } + + @Test + public void displays_reviews() { + startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); + tester.assertModelValue(path(PANEL, LIST_VIEW), getReviewList()); + } + + @Test + public void no_reviewers_label_visible_if_no_reviews_are_available() { + startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, new ArrayList()); + tester.assertVisible(path(PANEL, NO_REVIEWERS)); + } + + @Test + public void no_reviewers_label_invisible_if_reviews_are_available() { + startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); + tester.assertInvisible(path(PANEL, NO_REVIEWERS)); + } + + @Test + public void link_to_review_from_list() { + startPanel(DISPLAY_REVIEWS, PUBLIC_REVIEWS, getReviewList()); + PageParameters parameters = new PageParameters(); + parameters.add(PageParameterKeys.MAP.get(PeerReview.class), getReviewList().get(0).getId()); + tester.assertBookmarkablePageLink(path(PANEL, LIST_VIEW, 0, REVIEW_LINK), ViewPeerReviewPage.class, parameters); + } + + @Test + public void link_to_review_disabled_if_not_activated_in_settings() { + startPanel(DISPLAY_REVIEWS, NOT_PUBLIC, getReviewList()); + tester.assertDisabled(path(PANEL, LIST_VIEW, 0, REVIEW_LINK)); + } + + private void startPanel(boolean displayReviews, boolean reviewsActivated, List reviewList) { + lenient().when(peerReviewService.findAllCompleted(any(Pageable.class))).thenReturn(reviewList); + when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn( + createSettings(displayReviews, reviewsActivated) + ); + tester.startComponentInPage(new LatestReviewPanel(PANEL)); + } + + private GeneralSystemSettings createSettings(boolean displayLatestReviews, boolean reviewsActivated) { + GeneralSystemSettings settings = new GeneralSystemSettings(); + settings.setPeerDisplayLatestReviews(displayLatestReviews); + settings.setPublicReviewsActivated(reviewsActivated); + return settings; + } + + private List getReviewList() { + PeerReview peerReview = new PeerReview(); + peerReview.setId(5L); + return Collections.singletonList(peerReview); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/MyPeerPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/MyPeerPanelTest.java index 39a5170500..fca11efd12 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/MyPeerPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/MyPeerPanelTest.java @@ -1,177 +1,201 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.feedback.FeedbackMessage; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.peer.MyPeerPanel.*; -import static se.su.dsv.scipro.test.ObjectMother.SOME_PROJECT; - -public class MyPeerPanelTest extends SciProTest { - - public static final String PANEL = "id"; - public static final String SOME_PROJECT_TITLE = "someProjectTitle"; - public static final long REVIEW_ID = 5L; - private Date requestDate; - private Date reviewDate; - private MyPeerPanel panel; - - @BeforeEach - public void setUp() throws Exception { - requestDate = new Date(); - reviewDate = Date.from(ZonedDateTime.now().plusDays(3).toInstant()); - mockExistingPeers(getRequests(RequestStatus.WAITING), getReviews()); - startPanel(); - } - - @Test - public void lists_my_requests() { - tester.assertModelValue(path(PANEL, REQUEST_LIST), getRequests(RequestStatus.WAITING)); - } - - @Test - public void lists_my_reviews() { - tester.assertModelValue(path(PANEL, REVIEW_LIST), getReviews()); - } - - @Test - public void requests_lists_date_created() { - tester.assertModelValue(path(PANEL, REQUEST_LIST, 0, REQUEST_DATE), requestDate); - } - - @Test - public void reviews_lists_date_created() { - tester.assertModelValue(path(PANEL, REVIEW_LIST, 0, REVIEW_DATE), reviewDate); - } - - @Test - public void review_list_shows_title_of_request_project() { - tester.assertLabel(path(PANEL, REVIEW_LIST, 0, REVIEW_LINK, PROJECT_TITLE), SOME_PROJECT_TITLE); - } - - @Test - public void click_on_review_title_takes_reviewer_to_the_review() { - PageParameters parameters = new PageParameters(); - parameters.add(PageParameterKeys.MAP.get(PeerReview.class), REVIEW_ID); - tester.assertBookmarkablePageLink(path(PANEL, REVIEW_LIST, 0, REVIEW_LINK), PeerPortalPage.class, parameters); - tester.assertBookmarkablePageLink(path(PANEL, REVIEW_LIST, 1, REVIEW_LINK), ViewPeerReviewPage.class, parameters); - } - - @Test - public void request_list_shows_request_status() { - tester.assertModelValue(path(PANEL, REQUEST_LIST, 0, REQUEST_LINK, REQUEST_STATUS), getPeerRequest().getStatus()); - } - - @Test - public void review_list_shows_review_status() { - tester.assertModelValue(path(PANEL, REVIEW_LIST, 0, REVIEW_STATUS), getReviews().get(0).getStatus()); - } - - @Test - public void cancel_request_calls_service() { - tester.clickLink(path(PANEL, REQUEST_LIST, 0, CANCEL)); - verify(peerRequestService).deleteRequest(eq(getPeerRequest())); - } - - @Test - public void cancel_generates_feedback() { - tester.clickLink(path(PANEL, REQUEST_LIST, 0, CANCEL)); - List messages = tester.getMessages(FeedbackMessage.SUCCESS); - assertThat(messages, hasItem(panel.getString("deleted"))); - } - - @Test - public void cancel_link_is_only_visible_for_awaiting_requests() { - mockExistingPeers(getRequests(RequestStatus.TAKEN), getReviews()); - startPanel(); - tester.assertInvisible(path(PANEL, REQUEST_LIST, 0, CANCEL)); - } - - @Test - public void no_requests_label_visible_if_no_requests_exist() { - mockExistingPeers(new ArrayList(), getReviews()); - startPanel(); - tester.assertVisible(path(PANEL, NO_REQUESTS)); - } - - @Test - public void no_reviews_label_visible_if_no_reviews_exist() { - mockExistingPeers(new ArrayList(), new ArrayList()); - startPanel(); - tester.assertVisible(path(PANEL, NO_REVIEWS)); - } - - @Test - public void request_is_clickable_if_review_is_completed() { - mockExistingPeers(getRequests(RequestStatus.FINISHED), getReviews()); - startPanel(); - tester.assertEnabled(path(PANEL, REQUEST_LIST, 0, REQUEST_LINK)); - } - - @Test - public void request_is_not_clickable_if_review_is_completed() { - tester.assertDisabled(path(PANEL, REQUEST_LIST, 0, REQUEST_LINK)); - } - - private PeerRequest getPeerRequest() { - return getRequests(RequestStatus.WAITING).get(0); - } - - private void mockExistingPeers(List requests, List reviews) { - User me = SciProSession.get().getUser(); - when(peerRequestService.findByRequesterAndProject(me, SOME_PROJECT)).thenReturn(requests); - when(peerReviewService.findNonExpiredReviewsByProjectAuthor(me, SOME_PROJECT)).thenReturn(reviews); - } - - private List getReviews() { - PeerReview inProgress = createReview(); - inProgress.setPeerRequest(createRequest(Project.builder().title(SOME_PROJECT_TITLE).projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(), RequestStatus.WAITING)); - PeerReview complete = createReview(); - complete.setStatus(PeerReview.ReviewStatus.COMPLETED); - complete.setPeerRequest(createRequest(Project.builder().title(SOME_PROJECT_TITLE).projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(), RequestStatus.WAITING)); - return Arrays.asList(inProgress, complete); - } - - private List getRequests(RequestStatus status) { - PeerRequest peerRequest = createRequest(SOME_PROJECT, status); - peerRequest.setPeerReviews(Collections.singletonList(createReview())); - return Collections.singletonList(peerRequest); - } - - private PeerReview createReview() { - PeerReview peerReview = new PeerReview(); - peerReview.setId(REVIEW_ID); - peerReview.setDateCreated(reviewDate); - return peerReview; - } - - private PeerRequest createRequest(Project project, RequestStatus status) { - PeerRequest peerRequest = new PeerRequest(); - peerRequest.setProject(project); - peerRequest.setDateCreated(requestDate); - peerRequest.setStatus(status); - return peerRequest; - } - - private void startPanel() { - panel = tester.startComponentInPage(new MyPeerPanel(PANEL, Model.of(SOME_PROJECT))); - } -} +package se.su.dsv.scipro.peer; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.peer.MyPeerPanel.*; +import static se.su.dsv.scipro.test.ObjectMother.SOME_PROJECT; + +import java.io.Serializable; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; +import org.apache.wicket.feedback.FeedbackMessage; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class MyPeerPanelTest extends SciProTest { + + public static final String PANEL = "id"; + public static final String SOME_PROJECT_TITLE = "someProjectTitle"; + public static final long REVIEW_ID = 5L; + private Date requestDate; + private Date reviewDate; + private MyPeerPanel panel; + + @BeforeEach + public void setUp() throws Exception { + requestDate = new Date(); + reviewDate = Date.from(ZonedDateTime.now().plusDays(3).toInstant()); + mockExistingPeers(getRequests(RequestStatus.WAITING), getReviews()); + startPanel(); + } + + @Test + public void lists_my_requests() { + tester.assertModelValue(path(PANEL, REQUEST_LIST), getRequests(RequestStatus.WAITING)); + } + + @Test + public void lists_my_reviews() { + tester.assertModelValue(path(PANEL, REVIEW_LIST), getReviews()); + } + + @Test + public void requests_lists_date_created() { + tester.assertModelValue(path(PANEL, REQUEST_LIST, 0, REQUEST_DATE), requestDate); + } + + @Test + public void reviews_lists_date_created() { + tester.assertModelValue(path(PANEL, REVIEW_LIST, 0, REVIEW_DATE), reviewDate); + } + + @Test + public void review_list_shows_title_of_request_project() { + tester.assertLabel(path(PANEL, REVIEW_LIST, 0, REVIEW_LINK, PROJECT_TITLE), SOME_PROJECT_TITLE); + } + + @Test + public void click_on_review_title_takes_reviewer_to_the_review() { + PageParameters parameters = new PageParameters(); + parameters.add(PageParameterKeys.MAP.get(PeerReview.class), REVIEW_ID); + tester.assertBookmarkablePageLink(path(PANEL, REVIEW_LIST, 0, REVIEW_LINK), PeerPortalPage.class, parameters); + tester.assertBookmarkablePageLink( + path(PANEL, REVIEW_LIST, 1, REVIEW_LINK), + ViewPeerReviewPage.class, + parameters + ); + } + + @Test + public void request_list_shows_request_status() { + tester.assertModelValue( + path(PANEL, REQUEST_LIST, 0, REQUEST_LINK, REQUEST_STATUS), + getPeerRequest().getStatus() + ); + } + + @Test + public void review_list_shows_review_status() { + tester.assertModelValue(path(PANEL, REVIEW_LIST, 0, REVIEW_STATUS), getReviews().get(0).getStatus()); + } + + @Test + public void cancel_request_calls_service() { + tester.clickLink(path(PANEL, REQUEST_LIST, 0, CANCEL)); + verify(peerRequestService).deleteRequest(eq(getPeerRequest())); + } + + @Test + public void cancel_generates_feedback() { + tester.clickLink(path(PANEL, REQUEST_LIST, 0, CANCEL)); + List messages = tester.getMessages(FeedbackMessage.SUCCESS); + assertThat(messages, hasItem(panel.getString("deleted"))); + } + + @Test + public void cancel_link_is_only_visible_for_awaiting_requests() { + mockExistingPeers(getRequests(RequestStatus.TAKEN), getReviews()); + startPanel(); + tester.assertInvisible(path(PANEL, REQUEST_LIST, 0, CANCEL)); + } + + @Test + public void no_requests_label_visible_if_no_requests_exist() { + mockExistingPeers(new ArrayList(), getReviews()); + startPanel(); + tester.assertVisible(path(PANEL, NO_REQUESTS)); + } + + @Test + public void no_reviews_label_visible_if_no_reviews_exist() { + mockExistingPeers(new ArrayList(), new ArrayList()); + startPanel(); + tester.assertVisible(path(PANEL, NO_REVIEWS)); + } + + @Test + public void request_is_clickable_if_review_is_completed() { + mockExistingPeers(getRequests(RequestStatus.FINISHED), getReviews()); + startPanel(); + tester.assertEnabled(path(PANEL, REQUEST_LIST, 0, REQUEST_LINK)); + } + + @Test + public void request_is_not_clickable_if_review_is_completed() { + tester.assertDisabled(path(PANEL, REQUEST_LIST, 0, REQUEST_LINK)); + } + + private PeerRequest getPeerRequest() { + return getRequests(RequestStatus.WAITING).get(0); + } + + private void mockExistingPeers(List requests, List reviews) { + User me = SciProSession.get().getUser(); + when(peerRequestService.findByRequesterAndProject(me, SOME_PROJECT)).thenReturn(requests); + when(peerReviewService.findNonExpiredReviewsByProjectAuthor(me, SOME_PROJECT)).thenReturn(reviews); + } + + private List getReviews() { + PeerReview inProgress = createReview(); + inProgress.setPeerRequest( + createRequest( + Project.builder() + .title(SOME_PROJECT_TITLE) + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(), + RequestStatus.WAITING + ) + ); + PeerReview complete = createReview(); + complete.setStatus(PeerReview.ReviewStatus.COMPLETED); + complete.setPeerRequest( + createRequest( + Project.builder() + .title(SOME_PROJECT_TITLE) + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(), + RequestStatus.WAITING + ) + ); + return Arrays.asList(inProgress, complete); + } + + private List getRequests(RequestStatus status) { + PeerRequest peerRequest = createRequest(SOME_PROJECT, status); + peerRequest.setPeerReviews(Collections.singletonList(createReview())); + return Collections.singletonList(peerRequest); + } + + private PeerReview createReview() { + PeerReview peerReview = new PeerReview(); + peerReview.setId(REVIEW_ID); + peerReview.setDateCreated(reviewDate); + return peerReview; + } + + private PeerRequest createRequest(Project project, RequestStatus status) { + PeerRequest peerRequest = new PeerRequest(); + peerRequest.setProject(project); + peerRequest.setDateCreated(requestDate); + peerRequest.setStatus(status); + return peerRequest; + } + + private void startPanel() { + panel = tester.startComponentInPage(new MyPeerPanel(PANEL, Model.of(SOME_PROJECT))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalHeaderTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalHeaderTest.java index 71c8fe0e39..5d99208291 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalHeaderTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalHeaderTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,20 +16,18 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class PeerPortalHeaderTest extends SciProTest { + private Project project; private PeerPortalHeader panel; @BeforeEach public void setUp() throws Exception { - project = Project.builder().title("Title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); + project = Project.builder() + .title("Title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); DomainObjects.injectId(project, 234L); } @@ -51,7 +55,11 @@ public class PeerPortalHeaderTest extends SciProTest { public void has_link_to_perform_review_if_user_has_more_requests_than_reviews() { mockMoreRequestsThanReviews(); startPanel(); - tester.assertBookmarkablePageLink(path(panel, "review", "perform"), PeerPortalPage.class, PeerPortalPage.getPageParameters(project)); + tester.assertBookmarkablePageLink( + path(panel, "review", "perform"), + PeerPortalPage.class, + PeerPortalPage.getPageParameters(project) + ); } @Test @@ -112,11 +120,15 @@ public class PeerPortalHeaderTest extends SciProTest { } private void mockReviewInProgress() { - when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), project)).thenReturn(Collections.singletonList(new PeerReview())); + when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), project)).thenReturn( + Collections.singletonList(new PeerReview()) + ); } private void mockNoReviewInProgress() { - when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), project)).thenReturn(new ArrayList()); + when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), project)).thenReturn( + new ArrayList() + ); } private void startPanel() { diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalPageTest.java index fbda3467c2..4339ac17b4 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerPortalPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -14,29 +19,25 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - public class PeerPortalPageTest extends PageTest { @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().setFirstName("author").setLastName("1").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); setLoggedInAs(user); when(projectService.findOne(anyLong())).thenReturn(project); when(projectService.isPartOfProject(project, user)).thenReturn(true); - when(peerRequestService.findByRequesterAndProject(SciProSession.get().getUser(), project)).thenReturn(Collections.singletonList(new PeerRequest())); + when(peerRequestService.findByRequesterAndProject(SciProSession.get().getUser(), project)).thenReturn( + Collections.singletonList(new PeerRequest()) + ); when(performReviewService.getInProgressReview(any(User.class), eq(project))).thenReturn(null); } diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestListPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestListPanelTest.java index 93645e7009..509fc532f3 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestListPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestListPanelTest.java @@ -1,12 +1,12 @@ -package se.su.dsv.scipro.peer; - -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; - -public class PeerRequestListPanelTest extends SciProTest { - - @Test - public void renders() throws Exception { - tester.startComponentInPage(new PeerRequestListPanel("id")); - } -} +package se.su.dsv.scipro.peer; + +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; + +public class PeerRequestListPanelTest extends SciProTest { + + @Test + public void renders() throws Exception { + tester.startComponentInPage(new PeerRequestListPanel("id")); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanelTest.java index 913b5552a1..7eb6e57162 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSelectionPanelTest.java @@ -1,111 +1,132 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.notifications.dataobject.NotificationSource; -import se.su.dsv.scipro.notifications.dataobject.PeerEvent; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.session.SciProSession; -import se.su.dsv.scipro.system.User; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.peer.PeerRequestSelectionPanel.*; -import static se.su.dsv.scipro.test.ObjectMother.BACHELOR; -import static se.su.dsv.scipro.test.ObjectMother.SOME_PROJECT; - -public class PeerRequestSelectionPanelTest extends SciProTest { - - public static final String PANEL = "id"; - private Project requestProject; - private PeerRequestSelectionPanel panel; - - @BeforeEach - public void setUp() throws Exception { - requestProject = Project.builder().title("Project").projectType(BACHELOR).startDate(LocalDate.now()).build(); - startPanel(2L, 1L, new ArrayList()); - } - - @Test - public void panel_is_visible_if_user_is_allowed_to_select_request() { - tester.assertVisible(PANEL); - } - - @Test - public void panel_is_not_visible_if_user_is_disallowed() { - startPanel(0L, 0L, new ArrayList()); - tester.assertInvisible(PANEL); - } - - @Test - public void panel_is_not_visible_if_reviews_in_progress_exists() { - startPanel(2L, 1L, Collections.singletonList(new PeerReview())); - tester.assertInvisible(PANEL); - } - - @Test - public void request_list_shows_request_project_title() { - tester.assertLabel(path(PANEL, AVAILABLE_REQUESTS, 1, TITLE), requestProject.getTitle()); - } - - @Test - public void trying_to_accept_review_with_own_projects_request() throws Exception { - expectErrorMessage(new PartOfProjectException(), "partOfProjectException"); - } - - @Test - public void trying_to_accept_recently_reviewed_projects_request() throws Exception { - expectErrorMessage(new RecentlyReviewedException(), "recentlyReviewedException"); - } - - @Test - public void trying_to_accept_already_taken_request() throws Exception { - expectErrorMessage(new RequestTakenException(), "requestTakenException"); - } - - @Test - public void trying_to_accept_with_unknown_error() throws Exception { - expectErrorMessage(new RuntimeException(), "unknownError"); - } - - @Test - public void accept_review_notifies() { - tester.clickLink(path(PANEL, AVAILABLE_REQUESTS, 1, ACCEPT)); - verify(notificationController).notifyPeer(ArgumentMatchers.any(), eq(PeerEvent.Event.REVIEW_ACCEPTED), any(NotificationSource.class)); - } - - private void expectErrorMessage(RuntimeException exception, String expected) { - when(peerPortal.acceptReview(any(PeerRequest.class), any(User.class), any(Project.class))).thenThrow(exception); - startPanel(2L, 1L, new ArrayList()); - tester.clickLink(path(PANEL, AVAILABLE_REQUESTS, 1, ACCEPT)); - tester.assertErrorMessages(panel.getString(expected)); - } - - private void startPanel(long requests, long reviews, List existingReviews) { - lenient().when(peerRequestService.findAvailableRequests(eq(SciProSession.get().getUser()), eq(RequestStatus.WAITING), eq(BACHELOR), any(Pageable.class))).thenReturn(Collections.singletonList(createRequest())); - lenient().when(peerRequestService.countAvailableRequests(SciProSession.get().getUser(), RequestStatus.WAITING, BACHELOR)).thenReturn(1L); - lenient().when(peerRequestService.count(any(PeerRequestService.Filter.class))).thenReturn(requests); - lenient().when(peerReviewService.count(any(PeerReviewService.Filter.class))).thenReturn(reviews); - when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), SOME_PROJECT)).thenReturn(existingReviews); - panel = tester.startComponentInPage(new PeerRequestSelectionPanel(PANEL, Model.of(SOME_PROJECT))); - } - - private PeerRequest createRequest() { - PeerRequest peerRequest = new PeerRequest(); - peerRequest.setProject(requestProject); - return peerRequest; - } - -} +package se.su.dsv.scipro.peer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.peer.PeerRequestSelectionPanel.*; +import static se.su.dsv.scipro.test.ObjectMother.BACHELOR; +import static se.su.dsv.scipro.test.ObjectMother.SOME_PROJECT; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.notifications.dataobject.NotificationSource; +import se.su.dsv.scipro.notifications.dataobject.PeerEvent; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.session.SciProSession; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.User; + +public class PeerRequestSelectionPanelTest extends SciProTest { + + public static final String PANEL = "id"; + private Project requestProject; + private PeerRequestSelectionPanel panel; + + @BeforeEach + public void setUp() throws Exception { + requestProject = Project.builder().title("Project").projectType(BACHELOR).startDate(LocalDate.now()).build(); + startPanel(2L, 1L, new ArrayList()); + } + + @Test + public void panel_is_visible_if_user_is_allowed_to_select_request() { + tester.assertVisible(PANEL); + } + + @Test + public void panel_is_not_visible_if_user_is_disallowed() { + startPanel(0L, 0L, new ArrayList()); + tester.assertInvisible(PANEL); + } + + @Test + public void panel_is_not_visible_if_reviews_in_progress_exists() { + startPanel(2L, 1L, Collections.singletonList(new PeerReview())); + tester.assertInvisible(PANEL); + } + + @Test + public void request_list_shows_request_project_title() { + tester.assertLabel(path(PANEL, AVAILABLE_REQUESTS, 1, TITLE), requestProject.getTitle()); + } + + @Test + public void trying_to_accept_review_with_own_projects_request() throws Exception { + expectErrorMessage(new PartOfProjectException(), "partOfProjectException"); + } + + @Test + public void trying_to_accept_recently_reviewed_projects_request() throws Exception { + expectErrorMessage(new RecentlyReviewedException(), "recentlyReviewedException"); + } + + @Test + public void trying_to_accept_already_taken_request() throws Exception { + expectErrorMessage(new RequestTakenException(), "requestTakenException"); + } + + @Test + public void trying_to_accept_with_unknown_error() throws Exception { + expectErrorMessage(new RuntimeException(), "unknownError"); + } + + @Test + public void accept_review_notifies() { + tester.clickLink(path(PANEL, AVAILABLE_REQUESTS, 1, ACCEPT)); + verify(notificationController).notifyPeer( + ArgumentMatchers.any(), + eq(PeerEvent.Event.REVIEW_ACCEPTED), + any(NotificationSource.class) + ); + } + + private void expectErrorMessage(RuntimeException exception, String expected) { + when(peerPortal.acceptReview(any(PeerRequest.class), any(User.class), any(Project.class))).thenThrow(exception); + startPanel(2L, 1L, new ArrayList()); + tester.clickLink(path(PANEL, AVAILABLE_REQUESTS, 1, ACCEPT)); + tester.assertErrorMessages(panel.getString(expected)); + } + + private void startPanel(long requests, long reviews, List existingReviews) { + lenient() + .when( + peerRequestService.findAvailableRequests( + eq(SciProSession.get().getUser()), + eq(RequestStatus.WAITING), + eq(BACHELOR), + any(Pageable.class) + ) + ) + .thenReturn(Collections.singletonList(createRequest())); + lenient() + .when( + peerRequestService.countAvailableRequests( + SciProSession.get().getUser(), + RequestStatus.WAITING, + BACHELOR + ) + ) + .thenReturn(1L); + lenient().when(peerRequestService.count(any(PeerRequestService.Filter.class))).thenReturn(requests); + lenient().when(peerReviewService.count(any(PeerReviewService.Filter.class))).thenReturn(reviews); + when(peerReviewService.findInProgressReviews(SciProSession.get().getUser(), SOME_PROJECT)).thenReturn( + existingReviews + ); + panel = tester.startComponentInPage(new PeerRequestSelectionPanel(PANEL, Model.of(SOME_PROJECT))); + } + + private PeerRequest createRequest() { + PeerRequest peerRequest = new PeerRequest(); + peerRequest.setProject(requestProject); + return peerRequest; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanelTest.java index 81bd8bcf66..9dca9b50fb 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerRequestSubmissionPanelTest.java @@ -1,103 +1,113 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.Model; -import org.apache.wicket.util.file.File; -import org.apache.wicket.util.tester.FormTester; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.checklist.ChecklistTemplate; -import se.su.dsv.scipro.file.FileUpload; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.ProjectStatus; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.DomainObjects; -import se.su.dsv.scipro.test.UserBuilder; - -import java.net.URL; -import java.time.LocalDate; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class PeerRequestSubmissionPanelTest extends SciProTest { - - private Project project = Project.builder().title("project").projectType(new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor")).startDate(LocalDate.now()).projectStatus(ProjectStatus.ACTIVE).build(); - private PeerRequestSubmissionPanel panel; - private User user; - private ChecklistTemplate background; - - @BeforeEach - public void setUp() throws Exception { - user = new UserBuilder().create(); - setLoggedInAs(user); - project.addProjectParticipant(user); - DomainObjects.injectId(project, 2134L); - background = new ChecklistTemplate("Background", user); - } - - @Test - public void renders_with_correct_user() { - when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn(Collections.singletonList(background)); - startPanel(); - tester.assertVisible(path(panel)); - } - - @Test - public void panel_is_not_visible_if_project_is_not_active() { - project.setProjectStatus(ProjectStatus.COMPLETED); - startPanel(); - tester.assertInvisible(path(panel)); - } - - @Test - public void submit_form_without_upload() { - when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn(Collections.singletonList(background)); - startPanel(); - FormTester formTester = tester.newFormTester(path(panel, "requestForm")); - formTester.select("language", 0 ); - formTester.submit(); - tester.assertErrorMessages(panel.getString(("fileUpload.Required"))); - } - - @Test - public void submit_new_peer_request() throws Exception { - when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn(Collections.singletonList(background)); - String comment = "my comment"; - - startPanel(); - FormTester formTester = tester.newFormTester(path(panel, "requestForm")); - formTester.setValue("comment", comment); - formTester.select(path("listContainer", "radioGroup"), 1); - formTester.setFile("fileUpload", getTestFile(), "text/plain"); - formTester.select("language", 0 ); - formTester.submit(); - - tester.assertNoErrorMessage(); - - ArgumentCaptor captor = ArgumentCaptor.forClass(PeerRequest.class); - verify(peerPortal).storePeerRequest(isA(FileUpload.class), captor.capture()); - - PeerRequest peerRequest = captor.getValue(); - assertEquals(user, peerRequest.getRequester()); - assertEquals(comment, peerRequest.getComment()); - assertEquals(background, peerRequest.getChecklistTemplate()); - assertEquals(project, peerRequest.getProject()); - } - - private static File getTestFile() throws Exception { - URL resource = Thread.currentThread().getContextClassLoader().getResource("peer_request.txt"); - assert resource != null; - return new File(resource.toURI()); - } - - private void startPanel() { - panel = tester.startComponentInPage(new PeerRequestSubmissionPanel("id", Model.of(project))); - } -} +package se.su.dsv.scipro.peer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URL; +import java.time.LocalDate; +import java.util.Collections; +import org.apache.wicket.model.Model; +import org.apache.wicket.util.file.File; +import org.apache.wicket.util.tester.FormTester; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.checklist.ChecklistTemplate; +import se.su.dsv.scipro.file.FileUpload; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.ProjectStatus; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.DomainObjects; +import se.su.dsv.scipro.test.UserBuilder; + +public class PeerRequestSubmissionPanelTest extends SciProTest { + + private Project project = Project.builder() + .title("project") + .projectType(new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor")) + .startDate(LocalDate.now()) + .projectStatus(ProjectStatus.ACTIVE) + .build(); + private PeerRequestSubmissionPanel panel; + private User user; + private ChecklistTemplate background; + + @BeforeEach + public void setUp() throws Exception { + user = new UserBuilder().create(); + setLoggedInAs(user); + project.addProjectParticipant(user); + DomainObjects.injectId(project, 2134L); + background = new ChecklistTemplate("Background", user); + } + + @Test + public void renders_with_correct_user() { + when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn( + Collections.singletonList(background) + ); + startPanel(); + tester.assertVisible(path(panel)); + } + + @Test + public void panel_is_not_visible_if_project_is_not_active() { + project.setProjectStatus(ProjectStatus.COMPLETED); + startPanel(); + tester.assertInvisible(path(panel)); + } + + @Test + public void submit_form_without_upload() { + when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn( + Collections.singletonList(background) + ); + startPanel(); + FormTester formTester = tester.newFormTester(path(panel, "requestForm")); + formTester.select("language", 0); + formTester.submit(); + tester.assertErrorMessages(panel.getString(("fileUpload.Required"))); + } + + @Test + public void submit_new_peer_request() throws Exception { + when(checklistTemplateService.findPeerRequestChecklists(project)).thenReturn( + Collections.singletonList(background) + ); + String comment = "my comment"; + + startPanel(); + FormTester formTester = tester.newFormTester(path(panel, "requestForm")); + formTester.setValue("comment", comment); + formTester.select(path("listContainer", "radioGroup"), 1); + formTester.setFile("fileUpload", getTestFile(), "text/plain"); + formTester.select("language", 0); + formTester.submit(); + + tester.assertNoErrorMessage(); + + ArgumentCaptor captor = ArgumentCaptor.forClass(PeerRequest.class); + verify(peerPortal).storePeerRequest(isA(FileUpload.class), captor.capture()); + + PeerRequest peerRequest = captor.getValue(); + assertEquals(user, peerRequest.getRequester()); + assertEquals(comment, peerRequest.getComment()); + assertEquals(background, peerRequest.getChecklistTemplate()); + assertEquals(project, peerRequest.getProject()); + } + + private static File getTestFile() throws Exception { + URL resource = Thread.currentThread().getContextClassLoader().getResource("peer_request.txt"); + assert resource != null; + return new File(resource.toURI()); + } + + private void startPanel() { + panel = tester.startComponentInPage(new PeerRequestSubmissionPanel("id", Model.of(project))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PeerSummaryPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PeerSummaryPanelTest.java index b7e38149fc..da5a05102c 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PeerSummaryPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PeerSummaryPanelTest.java @@ -1,118 +1,134 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.markup.html.WebPage; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.time.LocalDate; -import java.time.ZonedDateTime; -import java.util.*; - -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.peer.PeerSummaryPanel.*; - -public class PeerSummaryPanelTest extends SciProTest { - - public static final String PANEL = "id"; - - private PeerReview reviewReceived; - private PeerReview reviewPerformed; - private Project project; - - @BeforeEach - public void setUp() throws Exception { - User author = User.builder().firstName("author").lastName("author").emailAddress("author@author.com").build(); - author.setId(4L); - Date reviewReceivedDate = Date.from(ZonedDateTime.now().plusDays(1).toInstant()); - reviewReceived = createReview(1L, reviewReceivedDate, User.builder().firstName("reviewer").lastName("1").emailAddress("reviewer@example.com").build()); - Date reviewPerformedDate = Date.from(ZonedDateTime.now().plusDays(3).toInstant()); - reviewPerformed = createReview(2L, reviewPerformedDate, User.builder().firstName("reviewer").lastName("2").emailAddress("reviewer@example.com").build()); - project = Project.builder().title("title").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); - project.addProjectParticipant(author); - setLoggedInAs(author); - startPanel(performedReviews(), receivedReviews()); - } - - @Test - public void lists_reviews_for_completed_requests() { - tester.assertModelValue(path(PANEL, RECEIVED_REVIEWS), receivedReviews()); - } - - @Test - public void lists_completed_reviews_by_project_authors() { - tester.assertModelValue(path(PANEL, PERFORMED_REVIEWS), performedReviews()); - } - - @Test - public void lists_have_links_to_reviews() { - assertReviewPageLink(ViewPeerReviewPage.class); - } - - @Test - public void links_to_supervisor_page_if_not_project_participant() { - setLoggedInAs(ObjectMother.SOME_USER); - startPanel(performedReviews(), receivedReviews()); - assertReviewPageLink(SupervisorViewPeerReviewPage.class); - } - - @Test - public void lists_show_date_created() { - tester.assertModelValue(path(PANEL, RECEIVED_REVIEWS, 0, REVIEW_LINK, DATE_CREATED), reviewReceived.getDateCreated()); - tester.assertModelValue(path(PANEL, PERFORMED_REVIEWS, 0, REVIEW_LINK, DATE_CREATED), reviewPerformed.getDateCreated()); - } - - @Test - public void lists_show_reviewer_name() { - tester.assertLabel(path(PANEL, RECEIVED_REVIEWS, 0, REVIEWER), reviewReceived.getReviewer().getFullName()); - tester.assertLabel(path(PANEL, PERFORMED_REVIEWS, 0, REVIEWER), reviewPerformed.getReviewer().getFullName()); - } - - @Test - public void no_reviews_label_not_visible_if_reviews_exist() { - tester.assertInvisible(path(PANEL, NO_PERFORMED)); - tester.assertInvisible(path(PANEL, NO_RECEIVED)); - } - - @Test - public void no_reviews_label_visible_if_empty() { - startPanel(new ArrayList(), new ArrayList()); - tester.assertVisible(path(PANEL, NO_PERFORMED)); - tester.assertVisible(path(PANEL, NO_RECEIVED)); - } - - private List performedReviews() { - return Collections.singletonList(reviewPerformed); - } - - private void assertReviewPageLink(Class pageClass) { - PageParameters parameters = new PageParameters(); - parameters.add(PageParameterKeys.MAP.get(PeerReview.class), reviewReceived.getId()); - tester.assertBookmarkablePageLink(path(PANEL, RECEIVED_REVIEWS, 0, REVIEW_LINK), pageClass, parameters); - } - - private List receivedReviews() { - return Collections.singletonList(reviewReceived); - } - - private PeerReview createReview(long id, Date dateCreated, User reviewer) { - PeerReview peerReview = new PeerReview(); - peerReview.setDateCreated(dateCreated); - peerReview.setId(id); - peerReview.setReviewer(reviewer); - return peerReview; - } - - private void startPanel(List performed, List received) { - when(peerReviewService.findCompletedReviews(project)).thenReturn(performed); - when(peerReviewService.findReceivedCompletedReviews(project)).thenReturn(received); - tester.startComponentInPage(new PeerSummaryPanel(PANEL, Model.of(project))); - } - -} +package se.su.dsv.scipro.peer; + +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.peer.PeerSummaryPanel.*; + +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.util.*; +import org.apache.wicket.markup.html.WebPage; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class PeerSummaryPanelTest extends SciProTest { + + public static final String PANEL = "id"; + + private PeerReview reviewReceived; + private PeerReview reviewPerformed; + private Project project; + + @BeforeEach + public void setUp() throws Exception { + User author = User.builder().firstName("author").lastName("author").emailAddress("author@author.com").build(); + author.setId(4L); + Date reviewReceivedDate = Date.from(ZonedDateTime.now().plusDays(1).toInstant()); + reviewReceived = createReview( + 1L, + reviewReceivedDate, + User.builder().firstName("reviewer").lastName("1").emailAddress("reviewer@example.com").build() + ); + Date reviewPerformedDate = Date.from(ZonedDateTime.now().plusDays(3).toInstant()); + reviewPerformed = createReview( + 2L, + reviewPerformedDate, + User.builder().firstName("reviewer").lastName("2").emailAddress("reviewer@example.com").build() + ); + project = Project.builder() + .title("title") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .build(); + project.addProjectParticipant(author); + setLoggedInAs(author); + startPanel(performedReviews(), receivedReviews()); + } + + @Test + public void lists_reviews_for_completed_requests() { + tester.assertModelValue(path(PANEL, RECEIVED_REVIEWS), receivedReviews()); + } + + @Test + public void lists_completed_reviews_by_project_authors() { + tester.assertModelValue(path(PANEL, PERFORMED_REVIEWS), performedReviews()); + } + + @Test + public void lists_have_links_to_reviews() { + assertReviewPageLink(ViewPeerReviewPage.class); + } + + @Test + public void links_to_supervisor_page_if_not_project_participant() { + setLoggedInAs(ObjectMother.SOME_USER); + startPanel(performedReviews(), receivedReviews()); + assertReviewPageLink(SupervisorViewPeerReviewPage.class); + } + + @Test + public void lists_show_date_created() { + tester.assertModelValue( + path(PANEL, RECEIVED_REVIEWS, 0, REVIEW_LINK, DATE_CREATED), + reviewReceived.getDateCreated() + ); + tester.assertModelValue( + path(PANEL, PERFORMED_REVIEWS, 0, REVIEW_LINK, DATE_CREATED), + reviewPerformed.getDateCreated() + ); + } + + @Test + public void lists_show_reviewer_name() { + tester.assertLabel(path(PANEL, RECEIVED_REVIEWS, 0, REVIEWER), reviewReceived.getReviewer().getFullName()); + tester.assertLabel(path(PANEL, PERFORMED_REVIEWS, 0, REVIEWER), reviewPerformed.getReviewer().getFullName()); + } + + @Test + public void no_reviews_label_not_visible_if_reviews_exist() { + tester.assertInvisible(path(PANEL, NO_PERFORMED)); + tester.assertInvisible(path(PANEL, NO_RECEIVED)); + } + + @Test + public void no_reviews_label_visible_if_empty() { + startPanel(new ArrayList(), new ArrayList()); + tester.assertVisible(path(PANEL, NO_PERFORMED)); + tester.assertVisible(path(PANEL, NO_RECEIVED)); + } + + private List performedReviews() { + return Collections.singletonList(reviewPerformed); + } + + private void assertReviewPageLink(Class pageClass) { + PageParameters parameters = new PageParameters(); + parameters.add(PageParameterKeys.MAP.get(PeerReview.class), reviewReceived.getId()); + tester.assertBookmarkablePageLink(path(PANEL, RECEIVED_REVIEWS, 0, REVIEW_LINK), pageClass, parameters); + } + + private List receivedReviews() { + return Collections.singletonList(reviewReceived); + } + + private PeerReview createReview(long id, Date dateCreated, User reviewer) { + PeerReview peerReview = new PeerReview(); + peerReview.setDateCreated(dateCreated); + peerReview.setId(id); + peerReview.setReviewer(reviewer); + return peerReview; + } + + private void startPanel(List performed, List received) { + when(peerReviewService.findCompletedReviews(project)).thenReturn(performed); + when(peerReviewService.findReceivedCompletedReviews(project)).thenReturn(received); + tester.startComponentInPage(new PeerSummaryPanel(PANEL, Model.of(project))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/PerformReviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/PerformReviewPanelTest.java index 36770c4901..38173ec867 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/PerformReviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/PerformReviewPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.peer; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static se.su.dsv.scipro.peer.PerformReviewPanel.*; + +import java.net.URL; +import java.time.LocalDate; +import java.util.Optional; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.Model; @@ -18,16 +27,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.net.URL; -import java.time.LocalDate; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static se.su.dsv.scipro.peer.PerformReviewPanel.*; - public class PerformReviewPanelTest extends SciProTest { private PeerReview peerReview; @@ -65,7 +64,10 @@ public class PerformReviewPanelTest extends SciProTest { public void lists_every_question_text() { int answer = 0; startPanel(); - tester.assertLabel(path(panel, REVIEW_FORM, ANSWERS, answer, QUESTION), peerReview.getAnswers().get(answer).getQuestion()); + tester.assertLabel( + path(panel, REVIEW_FORM, ANSWERS, answer, QUESTION), + peerReview.getAnswers().get(answer).getQuestion() + ); } @Test diff --git a/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerPortalPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerPortalPageTest.java index 293ae84418..d2eaa02802 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerPortalPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerPortalPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -12,22 +16,17 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - public class ProjectPeerPortalPageTest extends PageTest { @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().setFirstName("author").setLastName("1").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); setLoggedInAs(user); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerStatsPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerStatsPageTest.java index 62b15e0a39..ae6468f375 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerStatsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/ProjectPeerStatsPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.TreeSet; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -12,13 +18,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; -import java.util.TreeSet; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - public class ProjectPeerStatsPageTest extends PageTest { @BeforeEach @@ -30,11 +29,11 @@ public class ProjectPeerStatsPageTest extends PageTest { TreeSet projectParticipants = new TreeSet<>(new User.ByNameComparator()); projectParticipants.addAll(Collections.singletonList(user)); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(anyLong())).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/RequestDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/RequestDetailsPanelTest.java index 4f99192d71..757f0c3ea2 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/RequestDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/RequestDetailsPanelTest.java @@ -1,39 +1,40 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.checklist.ChecklistTemplate; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; - -import java.time.LocalDate; - -public class RequestDetailsPanelTest extends SciProTest { - - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); - private RequestDetailsPanel panel; - - @Test - public void renders() throws Exception { - startPanel(); - } - - @Test - public void open_checklist_template_dialog() { - startPanel(); - - tester.clickLink(path(panel, RequestDetailsPanel.TEMPLATE_LINK)); - tester.assertComponentOnAjaxResponse(path(panel, RequestDetailsPanel.DIALOG)); - } - - private void startPanel() { - PeerRequest peerRequest = new PeerRequest(); - peerRequest.setProject(Project.builder().title("title").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).build()); - ChecklistTemplate checklistTemplate = new ChecklistTemplate(); - checklistTemplate.addQuestion("question"); - peerRequest.setChecklistTemplate(checklistTemplate); - panel = tester.startComponentInPage(new RequestDetailsPanel("id", Model.of(peerRequest))); - } -} +package se.su.dsv.scipro.peer; + +import java.time.LocalDate; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.checklist.ChecklistTemplate; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; + +public class RequestDetailsPanelTest extends SciProTest { + + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); + private RequestDetailsPanel panel; + + @Test + public void renders() throws Exception { + startPanel(); + } + + @Test + public void open_checklist_template_dialog() { + startPanel(); + + tester.clickLink(path(panel, RequestDetailsPanel.TEMPLATE_LINK)); + tester.assertComponentOnAjaxResponse(path(panel, RequestDetailsPanel.DIALOG)); + } + + private void startPanel() { + PeerRequest peerRequest = new PeerRequest(); + peerRequest.setProject( + Project.builder().title("title").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).build() + ); + ChecklistTemplate checklistTemplate = new ChecklistTemplate(); + checklistTemplate.addQuestion("question"); + peerRequest.setChecklistTemplate(checklistTemplate); + panel = tester.startComponentInPage(new RequestDetailsPanel("id", Model.of(peerRequest))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanelTest.java index d627566fd4..ff785bd393 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/ReviewPageRequestDetailsPanelTest.java @@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class ReviewPageRequestDetailsPanelTest extends SciProTest { + private PeerRequest peerRequest; @BeforeEach diff --git a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorPeersPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorPeersPageTest.java index f6552eaeb8..c0188fe0f0 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorPeersPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorPeersPageTest.java @@ -4,6 +4,7 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class SupervisorPeersPageTest extends PageTest { + @Override protected Class getPage() { return SupervisorPeersPage.class; diff --git a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPageTest.java index 58e0e077d3..198c62102e 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewAllPeersPageTest.java @@ -1,32 +1,32 @@ -package se.su.dsv.scipro.peer; - -import org.apache.wicket.Page; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.BeforeEach; -import se.su.dsv.scipro.PageTest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.util.PageParameterKeys; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - -public class SupervisorViewPeerReviewAllPeersPageTest extends PageTest { - - @BeforeEach - public void setUp() throws Exception { - when(peerReviewService.findOne(anyLong())).thenReturn(new PeerReview()); - } - - @Override - protected Class getPage() { - return SupervisorViewPeerReviewAllPeersPage.class; - } - - @Override - protected PageParameters getPageParameters() { - PageParameters pageParameters = new PageParameters(); - pageParameters.set(PageParameterKeys.MAP.get(PeerReview.class), 1L); - pageParameters.set(PageParameterKeys.MAP.get(Project.class), 2L); - return pageParameters; - } -} +package se.su.dsv.scipro.peer; + +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import org.apache.wicket.Page; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.BeforeEach; +import se.su.dsv.scipro.PageTest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class SupervisorViewPeerReviewAllPeersPageTest extends PageTest { + + @BeforeEach + public void setUp() throws Exception { + when(peerReviewService.findOne(anyLong())).thenReturn(new PeerReview()); + } + + @Override + protected Class getPage() { + return SupervisorViewPeerReviewAllPeersPage.class; + } + + @Override + protected PageParameters getPageParameters() { + PageParameters pageParameters = new PageParameters(); + pageParameters.set(PageParameterKeys.MAP.get(PeerReview.class), 1L); + pageParameters.set(PageParameterKeys.MAP.get(Project.class), 2L); + return pageParameters; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPageTest.java index 34168a4052..fd1bdd4b39 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/SupervisorViewPeerReviewPageTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -8,12 +11,8 @@ import se.su.dsv.scipro.supervisor.pages.SupervisorPageTest; import se.su.dsv.scipro.test.ObjectMother; import se.su.dsv.scipro.util.PageParameterKeys; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public class SupervisorViewPeerReviewPageTest extends SupervisorPageTest { - @BeforeEach public void setUp() throws Exception { when(peerReviewService.findOne(anyLong())).thenReturn(new PeerReview()); diff --git a/view/src/test/java/se/su/dsv/scipro/peer/ViewPeerReviewPageTest.java b/view/src/test/java/se/su/dsv/scipro/peer/ViewPeerReviewPageTest.java index 4dcee8df3e..65728c156f 100644 --- a/view/src/test/java/se/su/dsv/scipro/peer/ViewPeerReviewPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/peer/ViewPeerReviewPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.peer; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -15,12 +20,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.when; - public class ViewPeerReviewPageTest extends PageTest { private PeerReview peerReview; @@ -47,7 +46,7 @@ public class ViewPeerReviewPageTest extends PageTest { lenient().when(peerReviewService.findOne(anyLong())).thenReturn(peerReview); when(projectService.findOne(anyLong())).thenReturn(project); when(projectService.isPartOfProject(eq(project), any(User.class))).thenReturn(true); - generalSystemSettings = new GeneralSystemSettings(); + generalSystemSettings = new GeneralSystemSettings(); when(generalSystemSettingsService.getGeneralSystemSettingsInstance()).thenReturn(generalSystemSettings); setLoggedInAs(reviewer); } diff --git a/view/src/test/java/se/su/dsv/scipro/profile/DisplayUserProfilePanelTest.java b/view/src/test/java/se/su/dsv/scipro/profile/DisplayUserProfilePanelTest.java index d5c1480c3d..f628e0d5ff 100644 --- a/view/src/test/java/se/su/dsv/scipro/profile/DisplayUserProfilePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/profile/DisplayUserProfilePanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.profile; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; import org.apache.wicket.extensions.markup.html.basic.SmartLinkMultiLineLabel; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; @@ -16,13 +22,6 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import java.util.ArrayList; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class DisplayUserProfilePanelTest extends SciProTest { @@ -75,22 +74,31 @@ public class DisplayUserProfilePanelTest extends SciProTest { @Test public void testEmployee() { - tester.assertContains("["+path(DisplayUserProfilePanel.EMPLOYEE)+"]"); + tester.assertContains("[" + path(DisplayUserProfilePanel.EMPLOYEE) + "]"); } @Test public void testUnit() { - tester.assertLabel(path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.UNIT), user.getUnit().getTitle()); + tester.assertLabel( + path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.UNIT), + user.getUnit().getTitle() + ); } @Test public void testAreas() { - tester.assertModelValue(path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.AREAS), new ArrayList<>(user.getActiveResearchAreas())); + tester.assertModelValue( + path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.AREAS), + new ArrayList<>(user.getActiveResearchAreas()) + ); } @Test public void testLanguages() { - tester.assertModelValue(path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.LANGUAGES), new ArrayList<>(user.getLanguages())); + tester.assertModelValue( + path(DisplayUserProfilePanel.EMPLOYEE, DisplayUserProfilePanel.LANGUAGES), + new ArrayList<>(user.getLanguages()) + ); } @Override diff --git a/view/src/test/java/se/su/dsv/scipro/profile/StudentProfileProgramPanelTest.java b/view/src/test/java/se/su/dsv/scipro/profile/StudentProfileProgramPanelTest.java index 4ee9bc5ca9..ef50e9bf85 100644 --- a/view/src/test/java/se/su/dsv/scipro/profile/StudentProfileProgramPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/profile/StudentProfileProgramPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.profile; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,12 +14,12 @@ import se.su.dsv.scipro.system.Program; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import static org.junit.jupiter.api.Assertions.assertNotNull; - @ExtendWith(MockitoExtension.class) public class StudentProfileProgramPanelTest extends SciProTest { + StudentProfileProgramPanel panel; IdeaParticipation nip; + @BeforeEach public void setUp() throws Exception { final User user = new UserBuilder().create(); diff --git a/view/src/test/java/se/su/dsv/scipro/profile/UserLinkPanelTest.java b/view/src/test/java/se/su/dsv/scipro/profile/UserLinkPanelTest.java index de56b52de3..fa19b9fe5d 100644 --- a/view/src/test/java/se/su/dsv/scipro/profile/UserLinkPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/profile/UserLinkPanelTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.profile; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.profile.UserLinkPanel.*; + import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -11,11 +16,6 @@ import se.su.dsv.scipro.components.ModalWindowPlus; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.profile.UserLinkPanel.*; - @ExtendWith(MockitoExtension.class) public class UserLinkPanelTest extends SciProTest { diff --git a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectDetailsPageTest.java index de0a3dada9..f8dbdeb0aa 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectDetailsPageTest.java @@ -1,136 +1,143 @@ -package se.su.dsv.scipro.project.pages; - -import org.apache.wicket.Page; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.PageTest; -import se.su.dsv.scipro.group.AuthorGroupPage; -import se.su.dsv.scipro.group.Group; -import se.su.dsv.scipro.group.GroupService; -import se.su.dsv.scipro.project.ExternalOrganization; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectModule; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.DomainObjects; -import se.su.dsv.scipro.test.UserBuilder; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.when; - -public class ProjectDetailsPageTest extends PageTest { - - private static final Long PROJECT_PP = 1L; - - private static final User SOME_USER = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); - private static final User SOME_SUPERVISOR = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); - private Project someBachelorProject; - private static final Project SOME_MASTER_PROJECT = Project.builder() - .title("master") - .projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")) - .startDate(LocalDate.now()) - .headSupervisor(SOME_SUPERVISOR) - .build(); - private Project ICT4D_PROJECT = Project.builder().title("ICT4D") - .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) - .startDate(LocalDate.now()) - .headSupervisor(SOME_SUPERVISOR) - .build(); - - @BeforeEach - public void setUp() throws Exception { - setLoggedInAs(SOME_USER); - someBachelorProject = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(SOME_SUPERVISOR) - .build(); - DomainObjects.injectId(someBachelorProject, 1L); - DomainObjects.injectId(ICT4D_PROJECT, 2L); - DomainObjects.injectId(SOME_MASTER_PROJECT, 3L); - mockProject(someBachelorProject); - } - - @Test - public void shows_final_seminar_panel_for_bachelor_project() { - startPage(); - tester.assertVisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); - } - - @Test - public void shows_final_seminar_panel_for_master_project() { - mockProject(SOME_MASTER_PROJECT); - startPage(); - tester.assertVisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); - } - - @Test - public void hides_final_seminar_panel_for_ICT4D_project() { - setModules(ProjectModule.CHECKLIST); - mockProject(ICT4D_PROJECT); - startPage(); - tester.assertInvisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); - } - - @Test - public void shows_external_organization() { - ExternalOrganization externalOrganization = new ExternalOrganization(); - externalOrganization.setName("Some external organization"); - someBachelorProject.setExternalOrganization(externalOrganization); - mockProject(someBachelorProject); - startPage(); - tester.assertModelValue(ProjectDetailsPage.EXTERNAL_ORGANIZATION, someBachelorProject.getExternalOrganization().getName()); - } - - @Test - public void hides_external_organization_if_project_has_none() { - mockProject(someBachelorProject); - startPage(); - tester.assertInvisible(ProjectDetailsPage.EXTERNAL_ORGANIZATION); - } - - @Test - public void group_overview_link_to_author_group_page() { - long id = 55L; - mockGroup(id); - mockProject(someBachelorProject); - startPage(); - PageParameters parameters = new PageParameters(); - parameters.add(PageParameterKeys.MAP.get(Group.class), id); - tester.assertBookmarkablePageLink(path("groups", "groupList", 0, "groupLink"), - AuthorGroupPage.class, parameters); - } - - private void mockGroup(long id) { - Group group = new Group(); - group.setId(id); - when(groupService.findAll(any(GroupService.Filter.class))).thenReturn( - Collections.singletonList(group) - ); - } - - @Override - protected Class getPage() { - return ProjectDetailsPage.class; - } - - @Override - protected PageParameters getPageParameters() { - PageParameters pageParameters = new PageParameters(); - pageParameters.set(PageParameterKeys.MAP.get(Project.class), String.valueOf(PROJECT_PP)); - return pageParameters; - } - - private void mockProject(Project project) { - lenient().when(projectService.findOne(PROJECT_PP)).thenReturn(project); - lenient().when(projectService.isPartOfProject(project, SOME_USER)).thenReturn(true); - } -} +package se.su.dsv.scipro.project.pages; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import org.apache.wicket.Page; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.PageTest; +import se.su.dsv.scipro.group.AuthorGroupPage; +import se.su.dsv.scipro.group.Group; +import se.su.dsv.scipro.group.GroupService; +import se.su.dsv.scipro.project.ExternalOrganization; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectModule; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.DomainObjects; +import se.su.dsv.scipro.test.UserBuilder; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class ProjectDetailsPageTest extends PageTest { + + private static final Long PROJECT_PP = 1L; + + private static final User SOME_USER = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); + private static final User SOME_SUPERVISOR = new UserBuilder() + .setFirstName("head") + .setLastName("supervisor") + .create(); + private Project someBachelorProject; + private static final Project SOME_MASTER_PROJECT = Project.builder() + .title("master") + .projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")) + .startDate(LocalDate.now()) + .headSupervisor(SOME_SUPERVISOR) + .build(); + private Project ICT4D_PROJECT = Project.builder() + .title("ICT4D") + .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) + .startDate(LocalDate.now()) + .headSupervisor(SOME_SUPERVISOR) + .build(); + + @BeforeEach + public void setUp() throws Exception { + setLoggedInAs(SOME_USER); + someBachelorProject = Project.builder() + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(SOME_SUPERVISOR) + .build(); + DomainObjects.injectId(someBachelorProject, 1L); + DomainObjects.injectId(ICT4D_PROJECT, 2L); + DomainObjects.injectId(SOME_MASTER_PROJECT, 3L); + mockProject(someBachelorProject); + } + + @Test + public void shows_final_seminar_panel_for_bachelor_project() { + startPage(); + tester.assertVisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); + } + + @Test + public void shows_final_seminar_panel_for_master_project() { + mockProject(SOME_MASTER_PROJECT); + startPage(); + tester.assertVisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); + } + + @Test + public void hides_final_seminar_panel_for_ICT4D_project() { + setModules(ProjectModule.CHECKLIST); + mockProject(ICT4D_PROJECT); + startPage(); + tester.assertInvisible(ProjectDetailsPage.FINAL_SEMINAR_NEW); + } + + @Test + public void shows_external_organization() { + ExternalOrganization externalOrganization = new ExternalOrganization(); + externalOrganization.setName("Some external organization"); + someBachelorProject.setExternalOrganization(externalOrganization); + mockProject(someBachelorProject); + startPage(); + tester.assertModelValue( + ProjectDetailsPage.EXTERNAL_ORGANIZATION, + someBachelorProject.getExternalOrganization().getName() + ); + } + + @Test + public void hides_external_organization_if_project_has_none() { + mockProject(someBachelorProject); + startPage(); + tester.assertInvisible(ProjectDetailsPage.EXTERNAL_ORGANIZATION); + } + + @Test + public void group_overview_link_to_author_group_page() { + long id = 55L; + mockGroup(id); + mockProject(someBachelorProject); + startPage(); + PageParameters parameters = new PageParameters(); + parameters.add(PageParameterKeys.MAP.get(Group.class), id); + tester.assertBookmarkablePageLink( + path("groups", "groupList", 0, "groupLink"), + AuthorGroupPage.class, + parameters + ); + } + + private void mockGroup(long id) { + Group group = new Group(); + group.setId(id); + when(groupService.findAll(any(GroupService.Filter.class))).thenReturn(Collections.singletonList(group)); + } + + @Override + protected Class getPage() { + return ProjectDetailsPage.class; + } + + @Override + protected PageParameters getPageParameters() { + PageParameters pageParameters = new PageParameters(); + pageParameters.set(PageParameterKeys.MAP.get(Project.class), String.valueOf(PROJECT_PP)); + return pageParameters; + } + + private void mockProject(Project project) { + lenient().when(projectService.findOne(PROJECT_PP)).thenReturn(project); + lenient().when(projectService.isPartOfProject(project, SOME_USER)).thenReturn(true); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectFilePageTest.java b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectFilePageTest.java index d06367772f..08492dc5df 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectFilePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectFilePageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.project.pages; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -12,11 +16,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public class ProjectFilePageTest extends PageTest { private Project project; @@ -28,11 +27,11 @@ public class ProjectFilePageTest extends PageTest { User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.findOne(anyLong())).thenReturn(project); diff --git a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectStartPageTest.java b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectStartPageTest.java index 545b1df4f5..0b6a0c72d5 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectStartPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/pages/ProjectStartPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.project.pages; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; @@ -11,14 +17,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class ProjectStartPageTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { User user = new UserBuilder().setFirstName("Rolf").setLastName("Rolfsson").create(); @@ -26,11 +26,11 @@ public class ProjectStartPageTest extends SciProTest { User supervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(supervisor) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); DomainObjects.injectId(project, 1L); when(projectService.getProjectsByUser(user)).thenReturn(Collections.singletonList(project)); diff --git a/view/src/test/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPageTest.java b/view/src/test/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPageTest.java index 6d27aad2b3..ef4dd649a6 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/pages/SupervisorEditProjectPageTest.java @@ -6,22 +6,22 @@ import se.su.dsv.scipro.supervisor.pages.SupervisorPageTest; import se.su.dsv.scipro.system.User; public class SupervisorEditProjectPageTest extends SupervisorPageTest { - @Override - protected Class getPage() { - return SupervisorEditProjectPage.class; - } - @Test - public void only_head_supervisor_can_edit_project() { - startPage(); - tester.assertRenderedPage(getPage()); - } + @Override + protected Class getPage() { + return SupervisorEditProjectPage.class; + } - @Test - public void not_head_supervisor_can_not_edit_project() { - setLoggedInAs(User.builder().firstName("any").lastName("any").emailAddress("any@test.com").build()); - startPage(); - tester.assertRenderedPage(getHomePage()); + @Test + public void only_head_supervisor_can_edit_project() { + startPage(); + tester.assertRenderedPage(getPage()); + } - } + @Test + public void not_head_supervisor_can_not_edit_project() { + setLoggedInAs(User.builder().firstName("any").lastName("any").emailAddress("any@test.com").build()); + startPage(); + tester.assertRenderedPage(getHomePage()); + } } diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanelTest.java index f2d3937a0b..5224c74b55 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/ExternalResourcesPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.project.panels; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.Collections; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -9,12 +13,8 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ExternalResource; import se.su.dsv.scipro.system.ProjectType; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class ExternalResourcesPanelTest extends SciProTest { + private ProjectType bachelor; @BeforeEach @@ -48,4 +48,4 @@ public class ExternalResourcesPanelTest extends SciProTest { externalResource.setUrl("https://scipro.dsv.su.se"); return externalResource; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanelTest.java index 7af8ddc35a..8b3a5564c8 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectHeaderPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.project.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static se.su.dsv.scipro.project.panels.ProjectHeaderPanel.CREDITS; + +import java.time.LocalDate; +import java.time.Month; +import java.util.*; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.Model; @@ -14,13 +20,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.time.Month; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static se.su.dsv.scipro.project.panels.ProjectHeaderPanel.CREDITS; - public class ProjectHeaderPanelTest extends SciProTest { ProjectHeaderPanel panel; @@ -128,14 +127,14 @@ public class ProjectHeaderPanelTest extends SciProTest { tester.assertInvisible(panel(CREDITS)); } - @Test - public void only_head_supervisor_can_see_edit_link() { - User user = new UserBuilder().setId(2L).setFirstName("any").setLastName("any").create(); - setLoggedInAs(user); - tester.assertInvisible(panel(ProjectHeaderPanel.EDIT_LINK)); - } + @Test + public void only_head_supervisor_can_see_edit_link() { + User user = new UserBuilder().setId(2L).setFirstName("any").setLastName("any").create(); + setLoggedInAs(user); + tester.assertInvisible(panel(ProjectHeaderPanel.EDIT_LINK)); + } - private void startPanel() { + private void startPanel() { startPanel(project); } @@ -146,11 +145,11 @@ public class ProjectHeaderPanelTest extends SciProTest { private Project createProject() { User user = new UserBuilder().setId(1L).setFirstName("author").setLastName("1").create(); Project project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); return project; diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanelTest.java index 25463914ed..99572307f7 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectSubTabMenuPanelTest.java @@ -1,5 +1,12 @@ package se.su.dsv.scipro.project.panels; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,20 +19,28 @@ import se.su.dsv.scipro.system.ProjectModule; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; - -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - public class ProjectSubTabMenuPanelTest extends SciProTest { - private static final Project SOME_BACHELOR_PROJECT = Project.builder().title("some title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); - private static final Project SOME_MASTER_PROJECT = Project.builder().title("master").projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")).startDate(LocalDate.now()).build(); - private static final Project ICT4D_PROJECT = Project.builder().title("some title").projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")).startDate(LocalDate.now()).build(); - private static final Project SOME_PHD_PROJECT = Project.builder().title("phd").projectType(new ProjectType(DegreeType.NONE, "PHD", "PHD")).startDate(LocalDate.now()).build(); + private static final Project SOME_BACHELOR_PROJECT = Project.builder() + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); + private static final Project SOME_MASTER_PROJECT = Project.builder() + .title("master") + .projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")) + .startDate(LocalDate.now()) + .build(); + private static final Project ICT4D_PROJECT = Project.builder() + .title("some title") + .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) + .startDate(LocalDate.now()) + .build(); + private static final Project SOME_PHD_PROJECT = Project.builder() + .title("phd") + .projectType(new ProjectType(DegreeType.NONE, "PHD", "PHD")) + .startDate(LocalDate.now()) + .build(); @BeforeEach public void setUp() throws Exception { @@ -78,7 +93,8 @@ public class ProjectSubTabMenuPanelTest extends SciProTest { } private ProjectSubTabMenuPanel startPanel(Project project) { - return tester.startComponentInPage(new ProjectSubTabMenuPanel("id", AbstractProjectDetailsPage.class, new PageParameters(), () -> project)); + return tester.startComponentInPage( + new ProjectSubTabMenuPanel("id", AbstractProjectDetailsPage.class, new PageParameters(), () -> project) + ); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanelTest.java index e05d0cce34..7113730938 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectTabMenuPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.project.panels; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; @@ -10,28 +18,19 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Collections; - -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - public class ProjectTabMenuPanelTest extends SciProTest { private static final User LOGGED_IN_USER = new UserBuilder().create(); public static final Project SOME_PROJECT = Project.builder() - .title("some project") - .projectType(new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor")) - .startDate(LocalDate.now()) - .build(); + .title("some project") + .projectType(new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor")) + .startDate(LocalDate.now()) + .build(); private static final Project ICT4D_PROJECT = Project.builder() - .title("ICT4D") - .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) - .startDate(LocalDate.now()) - .build(); + .title("ICT4D") + .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) + .startDate(LocalDate.now()) + .build(); @Test public void renders() throws Exception { diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanelTest.java index fbedcc9a7c..40d4b99fec 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/ProjectsOverviewPanelTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.project.panels; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -13,13 +19,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - public class ProjectsOverviewPanelTest extends SciProTest { public static final ProjectType BACHELOR = new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"); @@ -56,7 +55,9 @@ public class ProjectsOverviewPanelTest extends SciProTest { @Test public void shows_empty_label_if_there_are_no_projects_matching_filter() { when(projectService.findAll(anyFilter())).thenReturn(Collections.emptyList()); - when(projectService.findByUserAndStatus(author, ProjectStatus.COMPLETED)).thenReturn(Collections.singletonList(ObjectMother.SOME_PROJECT)); + when(projectService.findByUserAndStatus(author, ProjectStatus.COMPLETED)).thenReturn( + Collections.singletonList(ObjectMother.SOME_PROJECT) + ); when(projectService.findByUserAndStatus(author, ProjectStatus.ACTIVE)).thenReturn(Collections.emptyList()); tester.startComponentInPage(ProjectsOverviewPanel.class); tester.assertVisible(path("tableContainer", "emptyLabel")); @@ -73,8 +74,14 @@ public class ProjectsOverviewPanelTest extends SciProTest { } private Project buildProject() { - Project project = Project.builder().title("My project").projectType(BACHELOR).startDate(LocalDate.now()).build(); - project.setHeadSupervisor(User.builder().firstName("Susan").lastName("Supervisor").emailAddress("susan@dsv.su.se").build()); + Project project = Project.builder() + .title("My project") + .projectType(BACHELOR) + .startDate(LocalDate.now()) + .build(); + project.setHeadSupervisor( + User.builder().firstName("Susan").lastName("Supervisor").emailAddress("susan@dsv.su.se").build() + ); DomainObjects.injectId(project, 1L); return project; } diff --git a/view/src/test/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanelTest.java b/view/src/test/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanelTest.java index 7f35b4e531..e1c7e33209 100644 --- a/view/src/test/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/project/panels/SupervisorEditProjectPanelTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.project.panels; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.CO_SUPERVISORS; +import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.FEEDBACK; +import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.FORM; +import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.TITLE; + +import java.time.LocalDate; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -12,71 +21,61 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.verify; -import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.CO_SUPERVISORS; -import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.FEEDBACK; -import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.FORM; -import static se.su.dsv.scipro.project.panels.SupervisorEditProjectPanel.TITLE; - public class SupervisorEditProjectPanelTest extends SciProTest { - private Project project; + private Project project; private SupervisorEditProjectPanel panel; @BeforeEach public void setUp() throws Exception { project = Project.builder().title("any").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build(); - DomainObjects.injectId(project, 1L); - lenient().when(projectService.save(project)).thenReturn(project); - } + DomainObjects.injectId(project, 1L); + lenient().when(projectService.save(project)).thenReturn(project); + } - @Test - public void render() { - startPanel(); - } + @Test + public void render() { + startPanel(); + } - @Test - public void change_project_title() { - startPanel(); + @Test + public void change_project_title() { + startPanel(); - String newTitle = "new title"; - submitForm(newTitle); + String newTitle = "new title"; + submitForm(newTitle); - Project updatedProject = captureSavedProject(); - assertEquals(newTitle, updatedProject.getTitle()); - } + Project updatedProject = captureSavedProject(); + assertEquals(newTitle, updatedProject.getTitle()); + } - private Project captureSavedProject() { - ArgumentCaptor projectArgumentCaptor = ArgumentCaptor.forClass(Project.class); - verify(projectService).save(projectArgumentCaptor.capture()); - return projectArgumentCaptor.getValue(); - } + private Project captureSavedProject() { + ArgumentCaptor projectArgumentCaptor = ArgumentCaptor.forClass(Project.class); + verify(projectService).save(projectArgumentCaptor.capture()); + return projectArgumentCaptor.getValue(); + } - @Test - public void feedback_message_after_save() { - startPanel(); - submitForm("any"); - tester.assertComponent(path("id", FORM, FEEDBACK), FeedbackPanel.class); - } + @Test + public void feedback_message_after_save() { + startPanel(); + submitForm("any"); + tester.assertComponent(path("id", FORM, FEEDBACK), FeedbackPanel.class); + } - @Test - public void co_supervisor_deleted() { - User user = User.builder().firstName("").lastName("").emailAddress("A@A.S").build(); - DomainObjects.injectId(user, 1L); + @Test + public void co_supervisor_deleted() { + User user = User.builder().firstName("").lastName("").emailAddress("A@A.S").build(); + DomainObjects.injectId(user, 1L); project.addCoSupervisor(user); - startPanel(); + startPanel(); - tester.executeAjaxEvent(path("id", FORM, CO_SUPERVISORS, "wmc", "users", 0, "remove"), "click"); + tester.executeAjaxEvent(path("id", FORM, CO_SUPERVISORS, "wmc", "users", 0, "remove"), "click"); - submitForm("any"); - Project updatedProject = captureSavedProject(); - assertEquals(0, updatedProject.getCoSupervisors().size()); - } + submitForm("any"); + Project updatedProject = captureSavedProject(); + assertEquals(0, updatedProject.getCoSupervisors().size()); + } private void startPanel() { panel = tester.startComponentInPage(new SupervisorEditProjectPanel("id", Model.of(project))); @@ -84,7 +83,7 @@ public class SupervisorEditProjectPanelTest extends SciProTest { private void submitForm(String newTitle) { FormTester formTester = tester.newFormTester(path("id", FORM)); - formTester.setValue(TITLE, newTitle); - formTester.submit(); - } + formTester.setValue(TITLE, newTitle); + formTester.submit(); + } } diff --git a/view/src/test/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPageTest.java b/view/src/test/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPageTest.java index 6e11a78872..afec00e0e8 100644 --- a/view/src/test/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/projectpartner/AdminProjectPartnerPageTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.projectpartner; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,11 +13,8 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.data.facade.MailFacade; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminProjectPartnerPageTest extends SciProTest { + @Mock private MailFacade mailFacade; diff --git a/view/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPageTest.java b/view/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPageTest.java index 42b6763e8d..5f49d31c5a 100644 --- a/view/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/projectpartner/ProjectPartnerPageTest.java @@ -1,25 +1,24 @@ package se.su.dsv.scipro.projectpartner; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.generalsystemsettings.GeneralSystemSettings; import se.su.dsv.scipro.match.ApplicationPeriod; import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.test.ObjectMother; -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - public class ProjectPartnerPageTest extends SciProTest { private ApplicationPeriod applicationPeriod; @@ -52,9 +51,25 @@ public class ProjectPartnerPageTest extends SciProTest { @Test public void submit_new_ad() { when(applicationPeriodService.findOne(anyLong())).thenReturn(applicationPeriod); - when(projectPartnerService.getProjectPartnerInSpan(eq(daysToLive), eq(applicationPeriod), ArgumentMatchers.any(ProjectType.class), ArgumentMatchers.any(Pageable.class))).thenReturn(Collections.singletonList(new ProjectPartner(ObjectMother.SOME_USER))); - when(projectPartnerService.countProjectPartnerInSpan(eq(daysToLive), eq(applicationPeriod), ArgumentMatchers.any(ProjectType.class))).thenReturn(1L); - tester.getRequest().getPostParameters().setParameterValue("applicationPeriod", Long.toString(applicationPeriod.getId())); + when( + projectPartnerService.getProjectPartnerInSpan( + eq(daysToLive), + eq(applicationPeriod), + ArgumentMatchers.any(ProjectType.class), + ArgumentMatchers.any(Pageable.class) + ) + ).thenReturn(Collections.singletonList(new ProjectPartner(ObjectMother.SOME_USER))); + when( + projectPartnerService.countProjectPartnerInSpan( + eq(daysToLive), + eq(applicationPeriod), + ArgumentMatchers.any(ProjectType.class) + ) + ).thenReturn(1L); + tester + .getRequest() + .getPostParameters() + .setParameterValue("applicationPeriod", Long.toString(applicationPeriod.getId())); tester.executeAjaxEvent("applicationPeriod", "change"); FormTester formTester = tester.newFormTester(path("panels", "projectPartnerForm")); formTester.setValue("infotext", "help!"); diff --git a/view/src/test/java/se/su/dsv/scipro/projectpartner/SinglesPanelTest.java b/view/src/test/java/se/su/dsv/scipro/projectpartner/SinglesPanelTest.java index f9a3e64452..95a7cda25d 100644 --- a/view/src/test/java/se/su/dsv/scipro/projectpartner/SinglesPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/projectpartner/SinglesPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.projectpartner; +import static org.mockito.Mockito.when; + +import java.util.Arrays; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,11 +12,8 @@ import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; -import java.util.Arrays; - -import static org.mockito.Mockito.when; - public class SinglesPanelTest extends SciProTest { + private final ProjectType bachelor = new ProjectType(DegreeType.BACHELOR, "Bachelor", "bachelor"); private final ProjectType master = new ProjectType(DegreeType.MASTER, "Master", "master"); private final ApplicationPeriod applicationPeriod = new ApplicationPeriod("Some period"); @@ -34,12 +34,13 @@ public class SinglesPanelTest extends SciProTest { final ProjectPartner stevesPartner = new ProjectPartner(steve); stevesPartner.setProjectType(master); - when(projectPartnerService.getPartnersWithoutIdea(applicationPeriod)) - .thenReturn(Arrays.asList(billsAd, stevesPartner)); + when(projectPartnerService.getPartnersWithoutIdea(applicationPeriod)).thenReturn( + Arrays.asList(billsAd, stevesPartner) + ); } @Test public void renders() throws Exception { tester.startComponentInPage(new SinglesPanel("id", Model.of(applicationPeriod))); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/projectstate/ProjectStatePanelTest.java b/view/src/test/java/se/su/dsv/scipro/projectstate/ProjectStatePanelTest.java index ea861f657b..080cdfe7b0 100644 --- a/view/src/test/java/se/su/dsv/scipro/projectstate/ProjectStatePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/projectstate/ProjectStatePanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.projectstate; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.time.LocalDate; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.model.Model; @@ -16,10 +19,6 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class ProjectStatePanelTest extends SciProTest { ProjectStatePanel panel; @@ -29,11 +28,11 @@ public class ProjectStatePanelTest extends SciProTest { public void setUp() throws Exception { User user = new UserBuilder().setFirstName("author").setLastName("1").create(); project = Project.builder() - .title("some title") - .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) - .startDate(LocalDate.now()) - .headSupervisor(user) - .build(); + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .headSupervisor(user) + .build(); DomainObjects.injectId(project, 1L); } @@ -117,11 +116,13 @@ public class ProjectStatePanelTest extends SciProTest { private void startPanel(StateOfMind stateOfMind, final boolean isAuthor) { project.setStateOfMind(stateOfMind); - panel = tester.startComponentInPage(new ProjectStatePanel("panel", Model.of(project)) { - @Override - public boolean isAuthorView() { - return isAuthor; + panel = tester.startComponentInPage( + new ProjectStatePanel("panel", Model.of(project)) { + @Override + public boolean isAuthorView() { + return isAuthor; + } } - }); + ); } } diff --git a/view/src/test/java/se/su/dsv/scipro/repository/components/FileDownloadLinkTest.java b/view/src/test/java/se/su/dsv/scipro/repository/components/FileDownloadLinkTest.java index 61da8584d0..07bb3ab23b 100644 --- a/view/src/test/java/se/su/dsv/scipro/repository/components/FileDownloadLinkTest.java +++ b/view/src/test/java/se/su/dsv/scipro/repository/components/FileDownloadLinkTest.java @@ -1,12 +1,12 @@ package se.su.dsv.scipro.repository.components; +import static org.junit.jupiter.api.Assertions.assertFalse; + import org.apache.wicket.model.Model; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.file.FileDescription; -import static org.junit.jupiter.api.Assertions.assertFalse; - public class FileDownloadLinkTest extends SciProTest { public static final String SOME_FILE_NAME = "file.pdf"; diff --git a/view/src/test/java/se/su/dsv/scipro/repository/panels/ProjectFilePanelTest.java b/view/src/test/java/se/su/dsv/scipro/repository/panels/ProjectFilePanelTest.java index 23fe60979f..de353e728d 100644 --- a/view/src/test/java/se/su/dsv/scipro/repository/panels/ProjectFilePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/repository/panels/ProjectFilePanelTest.java @@ -1,27 +1,26 @@ package se.su.dsv.scipro.repository.panels; -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.file.FileDescription; -import se.su.dsv.scipro.file.FileReference; -import se.su.dsv.scipro.file.FileSource; -import se.su.dsv.scipro.file.ProjectFile; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.DomainObjects; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.test.UserBuilder; - -import java.util.Collections; -import java.util.Date; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Collections; +import java.util.Date; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.file.FileDescription; +import se.su.dsv.scipro.file.FileReference; +import se.su.dsv.scipro.file.FileSource; +import se.su.dsv.scipro.file.ProjectFile; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.DomainObjects; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.test.UserBuilder; + public class ProjectFilePanelTest extends SciProTest { public static final String DELETE_LINK_PATH = "id:table:body:rows:1:cells:6:cell:link"; @@ -46,7 +45,9 @@ public class ProjectFilePanelTest extends SciProTest { DomainObjects.injectId(projectFile, 1L); DomainObjects.injectId(fileDescription, 1L); - when(projectFileService.getProjectFiles(eq(ObjectMother.SOME_PROJECT), any(Pageable.class))).thenReturn(Collections.singletonList(projectFile)); + when(projectFileService.getProjectFiles(eq(ObjectMother.SOME_PROJECT), any(Pageable.class))).thenReturn( + Collections.singletonList(projectFile) + ); when(projectFileService.countProjectFiles(ObjectMother.SOME_PROJECT)).thenReturn(1L); when(projectFileService.findOne(projectFile.getId())).thenReturn(projectFile); } diff --git a/view/src/test/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanelTest.java b/view/src/test/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanelTest.java index 816bff0a7c..2c414b56d9 100644 --- a/view/src/test/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/repository/panels/ViewAttachmentPanelTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.repository.panels; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; @@ -9,8 +11,6 @@ import se.su.dsv.scipro.data.enums.DateStyle; import se.su.dsv.scipro.file.FileDescription; import se.su.dsv.scipro.repository.components.FileDownloadLink; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class ViewAttachmentPanelTest extends SciProTest { ViewAttachmentPanel panel; diff --git a/view/src/test/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanelTest.java b/view/src/test/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanelTest.java index 8e8184192f..630f65c0cc 100644 --- a/view/src/test/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/reviewer/ApprovalReviewerPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.reviewer; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; @@ -13,15 +21,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class ApprovalReviewerPanelTest extends SciProTest { private Project project; @@ -32,7 +31,9 @@ public class ApprovalReviewerPanelTest extends SciProTest { RoughDraftApproval approval = createApproval(); when(projectService.findOne(project.getId())).thenReturn(project); when(myReviewService.countDecisions(any(MyReviewService.Filter.class))).thenReturn(1L); - when(myReviewService.findAllDecisions(any(MyReviewService.Filter.class), any())).thenReturn(Collections.singletonList(approval.getCurrentDecision())); + when(myReviewService.findAllDecisions(any(MyReviewService.Filter.class), any())).thenReturn( + Collections.singletonList(approval.getCurrentDecision()) + ); when(myReviewService.findDecision(any())).thenReturn(approval.getCurrentDecision()); when(roughDraftApprovalService.findBy(project)).thenReturn(Optional.of(approval)); setLoggedInAs(project.getReviewer()); @@ -52,14 +53,24 @@ public class ApprovalReviewerPanelTest extends SciProTest { final User jane = User.builder().firstName("Jane").lastName("Doe").emailAddress("jane@example.com").build(); final User john = User.builder().firstName("John").lastName("Doe").emailAddress("john@example.com").build(); john.setId(23523L); - final Project project = Project.builder().title("Title").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(jane).build(); + final Project project = Project.builder() + .title("Title") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(jane) + .build(); project.setId(987912L); project.addReviewer(john); return project; } private RoughDraftApproval createApproval() { - RoughDraftApproval roughDraftApproval = new RoughDraftApproval(project, mock(FileReference.class),"test", new Date()); + RoughDraftApproval roughDraftApproval = new RoughDraftApproval( + project, + mock(FileReference.class), + "test", + new Date() + ); DomainObjects.injectId(roughDraftApproval, 978L); return roughDraftApproval; } diff --git a/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPageTest.java b/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPageTest.java index 7163ec6cb4..8b8607472a 100644 --- a/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerInteractionPageTest.java @@ -1,69 +1,68 @@ -package se.su.dsv.scipro.reviewer; - -import org.apache.wicket.Page; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.admin.pages.AdminStartPage; -import se.su.dsv.scipro.basepages.errorpages.AccessDeniedPage; -import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.test.UserBuilder; -import se.su.dsv.scipro.util.PageParameterKeys; - -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - -public class ReviewerInteractionPageTest extends SciProTest { - - @Test - public void redirects_to_home_page_if_no_value_found() { - tester.startPage(ReviewerInteractionPage.class); - tester.assertRenderedPage(AdminStartPage.class); - } - - @Test - public void access_denied_if_no_project_is_found() { - startWithParametersAndExpect(AccessDeniedPage.class); - } - - @Test - public void access_denied_if_not_reviewer_on_project() { - when(projectService.findOne(anyLong())).thenReturn(ObjectMother.SOME_PROJECT); - startWithParametersAndExpect(AccessDeniedPage.class); - } - - @Test - public void renders_when_reviewer_on_project() { - when(finalSeminarApprovalService.findBy(any(Project.class))).thenReturn(Optional.empty()); - when(roughDraftApprovalService.findBy(any(Project.class))).thenReturn(Optional.empty()); - mockProjectWithReviewerAndThread(); - startWithParametersAndExpect(ReviewerInteractionPage.class); - } - - private void startWithParametersAndExpect(Class pageClass) { - tester.startPage(ReviewerInteractionPage.class, getPageParameters()); - tester.assertRenderedPage(pageClass); - } - - private void mockProjectWithReviewerAndThread() { - User reviewer = new UserBuilder().create(); - setLoggedInAs(reviewer); - ObjectMother.SOME_PROJECT.addReviewer(reviewer); - when(projectService.findOne(anyLong())).thenReturn(ObjectMother.SOME_PROJECT); - ReviewerThread reviewerThread = new ReviewerThread(); - reviewerThread.setProject(ObjectMother.SOME_PROJECT); - when(reviewerInteractionService.getReviewerThread(ObjectMother.SOME_PROJECT)).thenReturn(reviewerThread); - } - - private PageParameters getPageParameters() { - PageParameters pageParameters = new PageParameters(); - pageParameters.add(PageParameterKeys.MAP.get(Project.class), 5L); - return pageParameters; - } -} +package se.su.dsv.scipro.reviewer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import org.apache.wicket.Page; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.admin.pages.AdminStartPage; +import se.su.dsv.scipro.basepages.errorpages.AccessDeniedPage; +import se.su.dsv.scipro.forum.dataobjects.ReviewerThread; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.test.UserBuilder; +import se.su.dsv.scipro.util.PageParameterKeys; + +public class ReviewerInteractionPageTest extends SciProTest { + + @Test + public void redirects_to_home_page_if_no_value_found() { + tester.startPage(ReviewerInteractionPage.class); + tester.assertRenderedPage(AdminStartPage.class); + } + + @Test + public void access_denied_if_no_project_is_found() { + startWithParametersAndExpect(AccessDeniedPage.class); + } + + @Test + public void access_denied_if_not_reviewer_on_project() { + when(projectService.findOne(anyLong())).thenReturn(ObjectMother.SOME_PROJECT); + startWithParametersAndExpect(AccessDeniedPage.class); + } + + @Test + public void renders_when_reviewer_on_project() { + when(finalSeminarApprovalService.findBy(any(Project.class))).thenReturn(Optional.empty()); + when(roughDraftApprovalService.findBy(any(Project.class))).thenReturn(Optional.empty()); + mockProjectWithReviewerAndThread(); + startWithParametersAndExpect(ReviewerInteractionPage.class); + } + + private void startWithParametersAndExpect(Class pageClass) { + tester.startPage(ReviewerInteractionPage.class, getPageParameters()); + tester.assertRenderedPage(pageClass); + } + + private void mockProjectWithReviewerAndThread() { + User reviewer = new UserBuilder().create(); + setLoggedInAs(reviewer); + ObjectMother.SOME_PROJECT.addReviewer(reviewer); + when(projectService.findOne(anyLong())).thenReturn(ObjectMother.SOME_PROJECT); + ReviewerThread reviewerThread = new ReviewerThread(); + reviewerThread.setProject(ObjectMother.SOME_PROJECT); + when(reviewerInteractionService.getReviewerThread(ObjectMother.SOME_PROJECT)).thenReturn(reviewerThread); + } + + private PageParameters getPageParameters() { + PageParameters pageParameters = new PageParameters(); + pageParameters.add(PageParameterKeys.MAP.get(Project.class), 5L); + return pageParameters; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerStartPageTest.java b/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerStartPageTest.java index 5da1a6d1c0..91c0947265 100644 --- a/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerStartPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/reviewer/ReviewerStartPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.reviewer; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.wicket.Page; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.PageTest; @@ -9,24 +15,17 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.security.auth.roles.Roles; import se.su.dsv.scipro.system.User; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - public class ReviewerStartPageTest extends PageTest { - @Override - protected Class getPage() { - return ReviewerStartPage.class; - } + @Override + protected Class getPage() { + return ReviewerStartPage.class; + } @Override public Roles[] getRoles() { - return new Roles[]{Roles.REVIEWER}; - } + return new Roles[] { Roles.REVIEWER }; + } @Test public void shows_undecided_approvals_on_the_tab() { @@ -46,7 +45,13 @@ public class ReviewerStartPageTest extends PageTest { when(projectService.findAll(any(ProjectService.Filter.class))).thenReturn(projects); when(reviewerInteractionService.getPosts(project)).thenReturn(posts); - when(basicForumService.isRead(any(User.class), any(ForumPost.class))).thenReturn(true, false, true, false, true); + when(basicForumService.isRead(any(User.class), any(ForumPost.class))).thenReturn( + true, + false, + true, + false, + true + ); startPage(); tester.assertModelValue("unreadSupervisorsPosts", 1); } diff --git a/view/src/test/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPageTest.java b/view/src/test/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPageTest.java index bbd1f56315..0ca0b83f68 100644 --- a/view/src/test/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/reviewer/RoughDraftApprovalDecisionPageTest.java @@ -1,5 +1,23 @@ package se.su.dsv.scipro.reviewer; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.math.BigDecimal; +import java.net.URISyntaxException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.file.File; import org.apache.wicket.util.tester.FormTester; @@ -22,26 +40,8 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.util.Either; -import java.math.BigDecimal; -import java.net.URISyntaxException; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class RoughDraftApprovalDecisionPageTest extends SciProTest { + private Project project; private RoughDraftApproval roughDraftApproval; @@ -49,19 +49,28 @@ public class RoughDraftApprovalDecisionPageTest extends SciProTest { public void setUp() throws Exception { project = createProject(); setLoggedInAs(project.getReviewer()); - roughDraftApproval = new RoughDraftApproval(project, mock(FileReference.class),"test", new Date()); + roughDraftApproval = new RoughDraftApproval(project, mock(FileReference.class), "test", new Date()); DomainObjects.injectId(roughDraftApproval, 123L); when(projectService.findOne(project.getId())).thenReturn(project); when(roughDraftApprovalService.findBy(project)).thenReturn(Optional.of(roughDraftApproval)); tester.getSession().setMetaData(OAuth.TOKEN, "abc"); tester.getSession().setMetaData(OAuth.EXPIRATION, Instant.now().plus(Duration.ofHours(1))); - Examination problemAndMethod = new Examination(614, new Name("Problem", "Problem"), "KX1P", BigDecimal.valueOf(6), List.of(new Grade(Grade.Type.PASSING, "P"))); - lenient().when(gradingService.getExaminations(anyString(), anyLong(), anyLong())) - .thenReturn(List.of(problemAndMethod)); - lenient().when(gradingService.reportGrade(any(), anyLong(), anyLong(), anyInt(), any(), any())) - .thenReturn(Either.right(null)); - when(gradingService.getResult(any(), anyLong(), anyLong(), anyLong())) - .thenReturn(Either.right(Optional.empty())); + Examination problemAndMethod = new Examination( + 614, + new Name("Problem", "Problem"), + "KX1P", + BigDecimal.valueOf(6), + List.of(new Grade(Grade.Type.PASSING, "P")) + ); + lenient() + .when(gradingService.getExaminations(anyString(), anyLong(), anyLong())) + .thenReturn(List.of(problemAndMethod)); + lenient() + .when(gradingService.reportGrade(any(), anyLong(), anyLong(), anyInt(), any(), any())) + .thenReturn(Either.right(null)); + when(gradingService.getResult(any(), anyLong(), anyLong(), anyLong())).thenReturn( + Either.right(Optional.empty()) + ); startPage(); } @@ -94,8 +103,9 @@ public class RoughDraftApprovalDecisionPageTest extends SciProTest { String feedback = "This is good enough"; File attachment = testFile(); - when(gradingService.getResult(anyString(), anyLong(), anyLong(), anyLong())) - .thenReturn(Either.right(Optional.empty())); + when(gradingService.getResult(anyString(), anyLong(), anyLong(), anyLong())).thenReturn( + Either.right(Optional.empty()) + ); tester.executeAjaxEvent(path("decision", "approve"), "click"); FormTester formTester = tester.newFormTester("decision"); @@ -141,7 +151,12 @@ public class RoughDraftApprovalDecisionPageTest extends SciProTest { stina.setId(987L); stina.setIdentifier(523); reviewer.setId(34L); - Project build = Project.builder().title("My project").projectType(bachelor).startDate(LocalDate.now()).headSupervisor(supervisor).build(); + Project build = Project.builder() + .title("My project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); build.addReviewer(reviewer); build.setId(87L); build.setIdentifier(8798); @@ -150,11 +165,13 @@ public class RoughDraftApprovalDecisionPageTest extends SciProTest { } private void startPage() { - PageParameters pageParameters = RoughDraftApprovalDecisionPage.pageParametersFor(roughDraftApproval.getProject()); + PageParameters pageParameters = RoughDraftApprovalDecisionPage.pageParametersFor( + roughDraftApproval.getProject() + ); tester.startPage(RoughDraftApprovalDecisionPage.class, pageParameters); } private static File testFile() throws URISyntaxException { return new File(RoughDraftApprovalDecisionPageTest.class.getResource("thesis.pdf").toURI()); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanelTest.java b/view/src/test/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanelTest.java index c7aa5ba6b3..35195f9f0c 100644 --- a/view/src/test/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/reviewer/timeline/TimelinePanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.reviewer.timeline; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.*; import org.apache.wicket.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,11 +17,6 @@ import se.su.dsv.scipro.reviewing.RoughDraftApproval; import se.su.dsv.scipro.system.DegreeType; import se.su.dsv.scipro.system.ProjectType; -import java.time.LocalDate; -import java.util.*; - -import static org.mockito.Mockito.when; - public class TimelinePanelTest extends SciProTest { private Project project; @@ -30,7 +29,12 @@ public class TimelinePanelTest extends SciProTest { final ForumPost forumPost = new ForumPost(); when(reviewerInteractionService.getPosts(project)).thenReturn(Collections.singletonList(forumPost)); - final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval(project, createFile(), "comment", new Date()); + final FinalSeminarApproval finalSeminarApproval = new FinalSeminarApproval( + project, + createFile(), + "comment", + new Date() + ); when(finalSeminarApprovalService.findBy(project)).thenReturn(Optional.of(finalSeminarApproval)); final RoughDraftApproval draftApproval = new RoughDraftApproval(project, createFile(), "comment", new Date()); @@ -52,4 +56,4 @@ public class TimelinePanelTest extends SciProTest { fileReference.setFileDescription(fileDescription); return fileReference; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/security/auth/ProjectProjectModuleBasedAuthorizationStrategyTest.java b/view/src/test/java/se/su/dsv/scipro/security/auth/ProjectProjectModuleBasedAuthorizationStrategyTest.java index 4f7cca6cd0..6ded2491b0 100644 --- a/view/src/test/java/se/su/dsv/scipro/security/auth/ProjectProjectModuleBasedAuthorizationStrategyTest.java +++ b/view/src/test/java/se/su/dsv/scipro/security/auth/ProjectProjectModuleBasedAuthorizationStrategyTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.security.auth; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + import org.apache.wicket.Component; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -7,14 +11,11 @@ import org.mockito.Mock; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.ProjectModule; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - public class ProjectProjectModuleBasedAuthorizationStrategyTest extends SciProTest { @Mock private ProjectModuleComponent authorization; + @Mock private Component component; diff --git a/view/src/test/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategyTest.java b/view/src/test/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategyTest.java index baf6537e71..c25d6ad43f 100644 --- a/view/src/test/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategyTest.java +++ b/view/src/test/java/se/su/dsv/scipro/security/auth/RoleBasedAuthorizationStrategyTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.security.auth; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + import org.apache.wicket.Component; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -9,15 +13,12 @@ import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.security.auth.roles.Roles; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class RoleBasedAuthorizationStrategyTest extends SciProTest { @Mock private Authorization authorization; + @Mock private Component component; @@ -38,7 +39,7 @@ public class RoleBasedAuthorizationStrategyTest extends SciProTest { setRoles(Roles.SYSADMIN, Roles.SUPERVISOR); when(authorization.requiresLoggedInUser()).thenReturn(true); - when(authorization.authorizedRoles()).thenReturn(new Roles[]{Roles.SYSADMIN}); + when(authorization.authorizedRoles()).thenReturn(new Roles[] { Roles.SYSADMIN }); assertRenderAllowed(); } diff --git a/view/src/test/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategyTest.java b/view/src/test/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategyTest.java index 91b5bd6fd0..552b00bd6c 100644 --- a/view/src/test/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategyTest.java +++ b/view/src/test/java/se/su/dsv/scipro/security/auth/SystemModuleBasedAuthorizationStrategyTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.security.auth; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + import org.apache.wicket.Component; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -7,14 +11,11 @@ import org.mockito.Mock; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.SystemModule; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - public class SystemModuleBasedAuthorizationStrategyTest extends SciProTest { @Mock private SystemModuleComponent authorization; + @Mock private Component component; @@ -54,5 +55,4 @@ public class SystemModuleBasedAuthorizationStrategyTest extends SciProTest { when(authorization.value()).thenReturn(SystemModule.GROUP); assertFalse(authorizationStrategy.isActionAuthorized(component, Component.RENDER)); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/settings/pages/BasicProfilePageTest.java b/view/src/test/java/se/su/dsv/scipro/settings/pages/BasicProfilePageTest.java index 937627df9f..f678afc869 100644 --- a/view/src/test/java/se/su/dsv/scipro/settings/pages/BasicProfilePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/settings/pages/BasicProfilePageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.settings.pages; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.settings.pages.BasicProfilePage.*; + import org.apache.wicket.Page; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -11,13 +16,9 @@ import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.system.User; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.settings.pages.BasicProfilePage.*; - @ExtendWith(MockitoExtension.class) public class BasicProfilePageTest extends PageTest { + @BeforeEach public void setUp() throws Exception { User user = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); @@ -35,7 +36,7 @@ public class BasicProfilePageTest extends PageTest { @Test public void shows_feedback_after_submitting_form() { - tester.newFormTester(FORM).submit(); + tester.newFormTester(FORM).submit(); tester.assertFeedback(FEEDBACK, tester.getLastRenderedPage().getString("profile.saved")); } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPageTest.java index 45633e2b63..5e20f84e0b 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminAuthorsStatisticsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import static se.su.dsv.scipro.statistics.AdminAuthorsStatisticsPage.*; + import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.junit.jupiter.api.Test; @@ -7,9 +9,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.components.AjaxCheckBoxMultipleChoice; import se.su.dsv.scipro.date.DeactivatableDatePickerPanel; -import static se.su.dsv.scipro.statistics.AdminAuthorsStatisticsPage.*; - -public class AdminAuthorsStatisticsPageTest extends SciProTest { +public class AdminAuthorsStatisticsPageTest extends SciProTest { @Test public void renders() throws Exception { @@ -52,5 +52,4 @@ public class AdminAuthorsStatisticsPageTest extends SciProTest { tester.clickLink(path(CONTAINER, DETAILS_LINK)); tester.assertRenderedPage(AdminMultipleAuthorsStatisticsPage.class); } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPageTest.java index c7947eeeb9..686a338998 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminFinalSeminarStatisticsPageTest.java @@ -4,8 +4,9 @@ import org.apache.wicket.Page; import se.su.dsv.scipro.PageTest; public class AdminFinalSeminarStatisticsPageTest extends PageTest { + @Override protected Class getPage() { return AdminFinalSeminarStatisticsPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPageTest.java index e897315a34..77bc5f21c1 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminIndividualMilestoneDetailsPageTest.java @@ -10,8 +10,12 @@ public class AdminIndividualMilestoneDetailsPageTest extends SciProTest { @Test public void renders() throws Exception { - tester.startPage(new AdminIndividualMilestoneDetailsPage(Model.of(new MilestoneActivityTemplate()), new MileStoneService.Filter())); + tester.startPage( + new AdminIndividualMilestoneDetailsPage( + Model.of(new MilestoneActivityTemplate()), + new MileStoneService.Filter() + ) + ); tester.assertRenderedPage(AdminIndividualMilestoneDetailsPage.class); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePageTest.java index a0a73c5d49..30ab33eee2 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMedianMilestonePageTest.java @@ -9,4 +9,4 @@ public class AdminMedianMilestonePageTest extends PageTest { protected Class getPage() { return AdminMedianMilestonePage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPageTest.java index 201663c086..abecdd2c29 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMilestoneStatisticsPageTest.java @@ -1,21 +1,25 @@ package se.su.dsv.scipro.statistics; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; - -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.when; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; + public class AdminMilestoneStatisticsPageTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { - when(milestoneActivityTemplateService.getAllActivities(any(MilestoneActivityTemplate.Type.class), anyCollection())) - .thenReturn(Collections.singletonList(new MilestoneActivityTemplate())); + when( + milestoneActivityTemplateService.getAllActivities( + any(MilestoneActivityTemplate.Type.class), + anyCollection() + ) + ).thenReturn(Collections.singletonList(new MilestoneActivityTemplate())); tester.startPage(AdminMilestoneStatisticsPage.class); } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPageTest.java index dcbad4025d..2aefd61c0c 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminMultipleAuthorsStatisticsPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.statistics; +import static se.su.dsv.scipro.statistics.AdminMultipleAuthorsStatisticsPage.AUTHOR_LIST; +import static se.su.dsv.scipro.statistics.AdminMultipleAuthorsStatisticsPage.PROJECTS; +import static se.su.dsv.scipro.test.ObjectMother.SOME_USER; + +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; @@ -10,13 +16,6 @@ import se.su.dsv.scipro.project.ProjectService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.util.Collections; -import java.util.List; - -import static se.su.dsv.scipro.statistics.AdminMultipleAuthorsStatisticsPage.AUTHOR_LIST; -import static se.su.dsv.scipro.statistics.AdminMultipleAuthorsStatisticsPage.PROJECTS; -import static se.su.dsv.scipro.test.ObjectMother.SOME_USER; - public class AdminMultipleAuthorsStatisticsPageTest extends SciProTest { private ProjectService.Filter filter; @@ -25,7 +24,9 @@ public class AdminMultipleAuthorsStatisticsPageTest extends SciProTest { public void setUp() throws Exception { filter = new ProjectService.Filter(); Mockito.when(getMultipleAuthors()).thenReturn(Collections.singletonList(SOME_USER)); - Mockito.when(projectService.findAll(ArgumentMatchers.any(ProjectService.Filter.class))).thenReturn(Collections.singletonList(ObjectMother.SOME_PROJECT)); + Mockito.when(projectService.findAll(ArgumentMatchers.any(ProjectService.Filter.class))).thenReturn( + Collections.singletonList(ObjectMother.SOME_PROJECT) + ); tester.startPage(new AdminMultipleAuthorsStatisticsPage(filter)); } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPageTest.java index fbd8f1369f..e5de86edf3 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminPeopleStatisticsPageTest.java @@ -9,4 +9,4 @@ public class AdminPeopleStatisticsPageTest extends PageTest { protected Class getPage() { return AdminPeopleStatisticsPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPageTest.java index a0739293a1..0347e8a6e7 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminProjectMilestoneDetailsPageTest.java @@ -6,13 +6,16 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.service.MileStoneService; - public class AdminProjectMilestoneDetailsPageTest extends SciProTest { - @Test public void renders() throws Exception { - tester.startPage(new AdminProjectMilestoneDetailsPage(Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), new MileStoneService.Filter())); + tester.startPage( + new AdminProjectMilestoneDetailsPage( + Model.of(new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT)), + new MileStoneService.Filter() + ) + ); tester.assertRenderedPage(AdminProjectMilestoneDetailsPage.class); } } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPageTest.java index fbf1038271..b78b71a2c5 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminReviewerDeadlinesPageTest.java @@ -1,5 +1,14 @@ package se.su.dsv.scipro.statistics; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; import org.apache.wicket.Page; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,16 +17,6 @@ import se.su.dsv.scipro.reviewing.Decision; import se.su.dsv.scipro.reviewing.ReviewerApproval; import se.su.dsv.scipro.util.Pair; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class AdminReviewerDeadlinesPageTest extends PageTest { @BeforeEach @@ -30,23 +29,40 @@ public class AdminReviewerDeadlinesPageTest extends PageTest { }; Decision decision = mock(Decision.class); - List> lateReviewerApprovals = Collections.singletonList(new Pair<>(reviewerApproval, decision)); + List> lateReviewerApprovals = Collections.singletonList( + new Pair<>(reviewerApproval, decision) + ); List> list = new ArrayList<>(); - for (Pair ra: lateReviewerApprovals) { + for (Pair ra : lateReviewerApprovals) { list.add(0, ra); } - when(reviewerDeadlineFollowupService.getLateReviewerApprovals(eq(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), any(Date.class), any(Date.class), any(Date.class))).thenReturn(list); + when( + reviewerDeadlineFollowupService.getLateReviewerApprovals( + eq(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL), + any(Date.class), + any(Date.class), + any(Date.class) + ) + ).thenReturn(list); startPage(); } @Test public void lists_all_rough_draft_deadlines_that_are_missed() { - tester.assertModelValue(path("container", "reviewerApprovals"), reviewerDeadlineFollowupService.getLateReviewerApprovals(ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL, new Date(), new Date(), new Date())); + tester.assertModelValue( + path("container", "reviewerApprovals"), + reviewerDeadlineFollowupService.getLateReviewerApprovals( + ReviewerApproval.Step.ROUGH_DRAFT_APPROVAL, + new Date(), + new Date(), + new Date() + ) + ); } @Override protected Class getPage() { return AdminReviewerDeadlinesPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminStatisticsPageTest.java index 06cd459d15..7b0fc213ff 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminStatisticsPageTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; public class AdminStatisticsPageTest extends SciProTest { + @Test public void renders() throws Exception { tester.startPage(AdminStatisticsPage.class); diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPageTest.java index ff4ced4682..b61b1afd97 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnfinishedFinalSeminarsPageTest.java @@ -1,52 +1,55 @@ -package se.su.dsv.scipro.statistics; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.finalseminar.FinalSeminar; -import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.test.ObjectMother; - -import java.time.LocalDate; -import java.util.Collections; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -public class AdminUnfinishedFinalSeminarsPageTest extends SciProTest { - - public static final String EXPORT_LINK_PATH = "table:bottomToolbars:toolbars:4:td:linkContainer:1:exportLink"; - - @BeforeEach - public void setUp() throws Exception { - when(finalSeminarService.findUnfinishedSeminars(any(Date.class),any(Date.class), any(Pageable.class))).thenReturn(Collections.singletonList(getFinalSeminar())); - when(finalSeminarService.countUnfinishedSeminars(any(Date.class), any(Date.class))).thenReturn(1L); - } - - @Test - public void renders() throws Exception { - tester.startPage(new AdminUnfinishedFinalSeminarsPage()); - tester.assertRenderedPage(AdminUnfinishedFinalSeminarsPage.class); - } - - @Test - public void excel_exports_render() { - tester.startPage(new AdminUnfinishedFinalSeminarsPage()); - tester.clickLink(EXPORT_LINK_PATH); - assertEquals("application/vnd.openxmlformats", tester.getContentTypeFromResponseHeader()); - } - - private FinalSeminar getFinalSeminar() { - FinalSeminar seminar = new FinalSeminar(); - seminar.setProject(ObjectMother.SOME_PROJECT); - FinalSeminarOpposition opposition = new FinalSeminarOpposition(); - opposition.setProject(Project.builder().title("hej").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build()); - opposition.setUser(ObjectMother.SOME_USER); - seminar.addOpposition(opposition); - return seminar; - } -} +package se.su.dsv.scipro.statistics; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.Date; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.finalseminar.FinalSeminar; +import se.su.dsv.scipro.finalseminar.FinalSeminarOpposition; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.test.ObjectMother; + +public class AdminUnfinishedFinalSeminarsPageTest extends SciProTest { + + public static final String EXPORT_LINK_PATH = "table:bottomToolbars:toolbars:4:td:linkContainer:1:exportLink"; + + @BeforeEach + public void setUp() throws Exception { + when( + finalSeminarService.findUnfinishedSeminars(any(Date.class), any(Date.class), any(Pageable.class)) + ).thenReturn(Collections.singletonList(getFinalSeminar())); + when(finalSeminarService.countUnfinishedSeminars(any(Date.class), any(Date.class))).thenReturn(1L); + } + + @Test + public void renders() throws Exception { + tester.startPage(new AdminUnfinishedFinalSeminarsPage()); + tester.assertRenderedPage(AdminUnfinishedFinalSeminarsPage.class); + } + + @Test + public void excel_exports_render() { + tester.startPage(new AdminUnfinishedFinalSeminarsPage()); + tester.clickLink(EXPORT_LINK_PATH); + assertEquals("application/vnd.openxmlformats", tester.getContentTypeFromResponseHeader()); + } + + private FinalSeminar getFinalSeminar() { + FinalSeminar seminar = new FinalSeminar(); + seminar.setProject(ObjectMother.SOME_PROJECT); + FinalSeminarOpposition opposition = new FinalSeminarOpposition(); + opposition.setProject( + Project.builder().title("hej").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).build() + ); + opposition.setUser(ObjectMother.SOME_USER); + seminar.addOpposition(opposition); + return seminar; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanelTest.java index 76fc10b6fa..4d1c496657 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/AdminUnitStatisticsPanelTest.java @@ -25,5 +25,4 @@ public class AdminUnitStatisticsPanelTest extends SciProTest { public void testPanelContainsDataPanel() { tester.assertComponent(path(panel.getId(), AdminUnitStatisticsPanel.TABLE), ExportableDataPanel.class); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanelTest.java index 388b15d23b..1f63ff0447 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/IndividualMilestoneDetailsPanelTest.java @@ -1,28 +1,33 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; - -public class IndividualMilestoneDetailsPanelTest extends SciProTest { - - private MilestoneActivityTemplate activity; - - @BeforeEach - public void setUp() throws Exception { - createActivity(); - } - - @Test - public void renders() throws Exception { - tester.startComponentInPage(new IndividualMilestoneDetailsPanel("id", Model.of(activity), new MileStoneService.Filter())); - } - - private void createActivity() { - activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, "project plan approved", "description"); - } -} - +package se.su.dsv.scipro.statistics; + +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; + +public class IndividualMilestoneDetailsPanelTest extends SciProTest { + + private MilestoneActivityTemplate activity; + + @BeforeEach + public void setUp() throws Exception { + createActivity(); + } + + @Test + public void renders() throws Exception { + tester.startComponentInPage( + new IndividualMilestoneDetailsPanel("id", Model.of(activity), new MileStoneService.Filter()) + ); + } + + private void createActivity() { + activity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + "project plan approved", + "description" + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanelTest.java index c60d812796..2119265d69 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneFilterDetailsPanelTest.java @@ -1,60 +1,60 @@ -package se.su.dsv.scipro.statistics; - -import org.hamcrest.MatcherAssert; -import org.hamcrest.core.StringContains; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.data.enums.DateStyle; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; - -import java.util.Arrays; -import java.util.Date; - -public class MilestoneFilterDetailsPanelTest extends SciProTest { - - private MilestoneFilterDetailsPanel panel; - - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); - public static final ProjectType SOME_OTHER_PROJECT_TYPE = new ProjectType(DegreeType.MASTER, "master", "master"); - - @Test - public void filtering_without_project_started_between_includes_not_available_string() { - startPanel(new MileStoneService.Filter()); - assertThatPageContains(panel.getString("notAvailable")); - } - - @Test - public void filter_with_project_started_between() { - String dateString = "xxxx-xx-xx"; - Mockito.when(dateService.format(ArgumentMatchers.any(Date.class), ArgumentMatchers.eq(DateStyle.DATE))).thenReturn(dateString); - MileStoneService.Filter filter = new MileStoneService.Filter(); - filter.setProjectStartedAfter(new Date()); - filter.setProjectStartedBefore(new Date()); - startPanel(filter); - assertThatPageContains(dateString + " and " + dateString); - } - - @Test - public void filter_with_project_types() { - MileStoneService.Filter filter = new MileStoneService.Filter(); - filter.setProjectTypes(Arrays.asList(SOME_PROJECT_TYPE, SOME_OTHER_PROJECT_TYPE)); - startPanel(filter); - for (ProjectType projectType : filter.getProjectTypes()) { - assertThatPageContains(projectType.getName()); - } - } - - private void startPanel(MileStoneService.Filter filter) { - panel = tester.startComponentInPage(new MilestoneFilterDetailsPanel("id", filter)); - } - - private void assertThatPageContains(String string) { - String lastResponseAsString = tester.getLastResponseAsString(); - MatcherAssert.assertThat(lastResponseAsString, StringContains.containsString(string)); - } - -} +package se.su.dsv.scipro.statistics; + +import java.util.Arrays; +import java.util.Date; +import org.hamcrest.MatcherAssert; +import org.hamcrest.core.StringContains; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.data.enums.DateStyle; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; + +public class MilestoneFilterDetailsPanelTest extends SciProTest { + + private MilestoneFilterDetailsPanel panel; + + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); + public static final ProjectType SOME_OTHER_PROJECT_TYPE = new ProjectType(DegreeType.MASTER, "master", "master"); + + @Test + public void filtering_without_project_started_between_includes_not_available_string() { + startPanel(new MileStoneService.Filter()); + assertThatPageContains(panel.getString("notAvailable")); + } + + @Test + public void filter_with_project_started_between() { + String dateString = "xxxx-xx-xx"; + Mockito.when( + dateService.format(ArgumentMatchers.any(Date.class), ArgumentMatchers.eq(DateStyle.DATE)) + ).thenReturn(dateString); + MileStoneService.Filter filter = new MileStoneService.Filter(); + filter.setProjectStartedAfter(new Date()); + filter.setProjectStartedBefore(new Date()); + startPanel(filter); + assertThatPageContains(dateString + " and " + dateString); + } + + @Test + public void filter_with_project_types() { + MileStoneService.Filter filter = new MileStoneService.Filter(); + filter.setProjectTypes(Arrays.asList(SOME_PROJECT_TYPE, SOME_OTHER_PROJECT_TYPE)); + startPanel(filter); + for (ProjectType projectType : filter.getProjectTypes()) { + assertThatPageContains(projectType.getName()); + } + } + + private void startPanel(MileStoneService.Filter filter) { + panel = tester.startComponentInPage(new MilestoneFilterDetailsPanel("id", filter)); + } + + private void assertThatPageContains(String string) { + String lastResponseAsString = tester.getLastResponseAsString(); + MatcherAssert.assertThat(lastResponseAsString, StringContains.containsString(string)); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanelTest.java index c70607df9f..6a57da5cd0 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsPanelTest.java @@ -1,184 +1,230 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.Page; -import org.apache.wicket.markup.html.form.FormComponent; -import org.apache.wicket.model.IModel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.date.DatePickerPanel; -import se.su.dsv.scipro.date.DeactivatableDatePickerPanel; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; - -import java.util.*; - -import static java.util.Arrays.asList; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static se.su.dsv.scipro.statistics.MilestoneStatisticsPanel.*; - -public class MilestoneStatisticsPanelTest extends SciProTest { - - private List projectActivities; - private List individualActivities; - private MilestoneActivityTemplate projectActivity; - private MilestoneActivityTemplate individualActivity; - private List projectTypes; - - @BeforeEach - public void setUp() throws Exception { - projectTypes = new ArrayList<>(Collections.singletonList(new ProjectType(DegreeType.BACHELOR, "any", "any"))); - initActivities(); - Mockito.when(projectTypeService.findByDegreeTypes(EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER))).thenReturn(projectTypes); - tester.startComponentInPage(new MilestoneStatisticsPanel("panel", new MilestoneStatisticsPanel.PageSupplier() { - @Override - public Page individualPage(IModel model, MileStoneService.Filter filter) { - return new AdminIndividualMilestoneDetailsPage(model, filter); - } - - @Override - public Page projectPage(IModel model, MileStoneService.Filter filter) { - return new AdminProjectMilestoneDetailsPage(model, filter); - } - })); - } - - @Test - public void contains_list_of_project_milestone_activities() { - tester.assertModelValue(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST), projectActivities); - } - - @Test - public void project_milestones_have_number_of_completed_projects() { - Long completed = 2L; - Mockito.when(mileStoneService.countCompletedMileStones(eq(projectActivity), any(MileStoneService.Filter.class))).thenReturn(completed); - - tester.assertModelValue(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST, 0, COMPLETED_PROJECTS), completed); - } - - @Test - public void contains_list_of_individual_milestone_activities() { - tester.assertModelValue(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST), individualActivities); - } - - @Test - public void individual_milestones_have_number_of_completed_authors() { - Long completed = 2L; - Mockito.when(mileStoneService.countCompletedMileStones(eq(individualActivity), any(MileStoneService.Filter.class))).thenReturn(completed); - - tester.assertModelValue(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST, 0, COMPLETED_AUTHORS), completed); - } - - @Test - public void updating_project_type_filter_renders_container() { - tester.executeAjaxEvent(getProjectTypeCheckGroup(), "change"); - tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); - } - - @Test - public void updating_project_status_filter_renders_container() { - tester.executeAjaxEvent(getProjectStatusCheckGroup(), "change"); - tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); - } - - @Test - public void updating_milestone_date_filter_renders_container() { - tester.executeAjaxEvent(getMileStoneDateField(), "change"); - tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); - } - - @Test - public void updating_project_date_filter_start_date() { - enableDateFilter(); - tester.executeAjaxEvent(getProjectDateField(DatePickerPanel.START_DATE), "change"); - tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); - } - - @Test - public void updating_project_date_filter_end_date() { - enableDateFilter(); - tester.executeAjaxEvent(getProjectDateField(DatePickerPanel.END_DATE), "change"); - tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); - } - - @Test - public void disabling_date_filter_disables_date_picker() { - disableDateFilter(); - tester.assertDisabled(path("panel", DATE_FILTER, DeactivatableDatePickerPanel.DATE_PICKER)); - } - - @Test - public void enabling_date_filter_enables_date_picker() { - disableDateFilter(); - tester.assertDisabled(path("panel", DATE_FILTER, DeactivatableDatePickerPanel.DATE_PICKER)); - } - - @Test - public void activities_have_link_to_project_statistics_page() { - tester.clickLink(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST, 0, DETAILS_LINK)); - tester.assertRenderedPage(AdminProjectMilestoneDetailsPage.class); - } - - @Test - public void go_to_individual_milestone_activity_details() { - tester.clickLink(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST, 0, INDIVIDUAL_ACTIVITY_NAME)); - - tester.assertRenderedPage(AdminIndividualMilestoneDetailsPage.class); - } - - private void initActivities() { - projectActivity = createActivity(MilestoneActivityTemplate.Type.PROJECT, "Project milestone", "This is it..", 0); - projectActivities = asList(projectActivity); - individualActivity = createActivity(MilestoneActivityTemplate.Type.STUDENT, "Student milestone", "Hi?", 0); - individualActivities = asList(individualActivity); - - Mockito.when(milestoneActivityTemplateService.getAllActivities(eq(MilestoneActivityTemplate.Type.PROJECT), eq(projectTypes))).thenReturn(projectActivities); - Mockito.when(milestoneActivityTemplateService.getAllActivities(eq(MilestoneActivityTemplate.Type.STUDENT), eq(projectTypes))).thenReturn(individualActivities); - } - - private String getMileStoneDateField() { - return path("panel", MILESTONE_DATE_FILTER); - } - - private String getProjectTypeCheckGroup() { - return path("panel", PROJECT_TYPE_FILTER); - } - - private String getProjectStatusCheckGroup() { - return path("panel", PROJECT_STATUSES); - } - - private String getProjectDateField(String dateField) { - return path("panel", DATE_FILTER, DeactivatableDatePickerPanel.DATE_PICKER, DatePickerPanel.DATE_FORM, dateField); - } - - private void enableDateFilter() { - setDateFilterEnabled(true); - } - - private void disableDateFilter() { - setDateFilterEnabled(false); - } - - private void setDateFilterEnabled(boolean enabled) { - FormComponent dateFilterToggle = (FormComponent) tester.getComponentFromLastRenderedPage(path("panel", DATE_FILTER, DeactivatableDatePickerPanel.TOGGLE)); - tester.getRequest().getPostParameters().setParameterValue(dateFilterToggle.getInputName(), Boolean.toString(enabled)); - tester.executeAjaxEvent(dateFilterToggle, "click"); - } - - MilestoneActivityTemplate createActivity(MilestoneActivityTemplate.Type type, String title, String description, int order) { - MilestoneActivityTemplate activity = new MilestoneActivityTemplate(); - activity.setType(type); - activity.setTitle(title); - activity.setDescription(description); - activity.setMilestonePhaseTemplate(new MilestonePhaseTemplate("phase test", "this is for test", 0)); - activity.setProjectTypes(new HashSet<>(projectTypes)); - activity.setSortOrder(order); - return activity; - } -} +package se.su.dsv.scipro.statistics; + +import static java.util.Arrays.asList; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static se.su.dsv.scipro.statistics.MilestoneStatisticsPanel.*; + +import java.util.*; +import org.apache.wicket.Page; +import org.apache.wicket.markup.html.form.FormComponent; +import org.apache.wicket.model.IModel; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.date.DatePickerPanel; +import se.su.dsv.scipro.date.DeactivatableDatePickerPanel; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectType; + +public class MilestoneStatisticsPanelTest extends SciProTest { + + private List projectActivities; + private List individualActivities; + private MilestoneActivityTemplate projectActivity; + private MilestoneActivityTemplate individualActivity; + private List projectTypes; + + @BeforeEach + public void setUp() throws Exception { + projectTypes = new ArrayList<>(Collections.singletonList(new ProjectType(DegreeType.BACHELOR, "any", "any"))); + initActivities(); + Mockito.when( + projectTypeService.findByDegreeTypes( + EnumSet.of(DegreeType.BACHELOR, DegreeType.MASTER, DegreeType.MAGISTER) + ) + ).thenReturn(projectTypes); + tester.startComponentInPage( + new MilestoneStatisticsPanel( + "panel", + new MilestoneStatisticsPanel.PageSupplier() { + @Override + public Page individualPage( + IModel model, + MileStoneService.Filter filter + ) { + return new AdminIndividualMilestoneDetailsPage(model, filter); + } + + @Override + public Page projectPage(IModel model, MileStoneService.Filter filter) { + return new AdminProjectMilestoneDetailsPage(model, filter); + } + } + ) + ); + } + + @Test + public void contains_list_of_project_milestone_activities() { + tester.assertModelValue(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST), projectActivities); + } + + @Test + public void project_milestones_have_number_of_completed_projects() { + Long completed = 2L; + Mockito.when( + mileStoneService.countCompletedMileStones(eq(projectActivity), any(MileStoneService.Filter.class)) + ).thenReturn(completed); + + tester.assertModelValue(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST, 0, COMPLETED_PROJECTS), completed); + } + + @Test + public void contains_list_of_individual_milestone_activities() { + tester.assertModelValue(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST), individualActivities); + } + + @Test + public void individual_milestones_have_number_of_completed_authors() { + Long completed = 2L; + Mockito.when( + mileStoneService.countCompletedMileStones(eq(individualActivity), any(MileStoneService.Filter.class)) + ).thenReturn(completed); + + tester.assertModelValue(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST, 0, COMPLETED_AUTHORS), completed); + } + + @Test + public void updating_project_type_filter_renders_container() { + tester.executeAjaxEvent(getProjectTypeCheckGroup(), "change"); + tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); + } + + @Test + public void updating_project_status_filter_renders_container() { + tester.executeAjaxEvent(getProjectStatusCheckGroup(), "change"); + tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); + } + + @Test + public void updating_milestone_date_filter_renders_container() { + tester.executeAjaxEvent(getMileStoneDateField(), "change"); + tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); + } + + @Test + public void updating_project_date_filter_start_date() { + enableDateFilter(); + tester.executeAjaxEvent(getProjectDateField(DatePickerPanel.START_DATE), "change"); + tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); + } + + @Test + public void updating_project_date_filter_end_date() { + enableDateFilter(); + tester.executeAjaxEvent(getProjectDateField(DatePickerPanel.END_DATE), "change"); + tester.assertComponentOnAjaxResponse(path("panel", CONTAINER)); + } + + @Test + public void disabling_date_filter_disables_date_picker() { + disableDateFilter(); + tester.assertDisabled(path("panel", DATE_FILTER, DeactivatableDatePickerPanel.DATE_PICKER)); + } + + @Test + public void enabling_date_filter_enables_date_picker() { + disableDateFilter(); + tester.assertDisabled(path("panel", DATE_FILTER, DeactivatableDatePickerPanel.DATE_PICKER)); + } + + @Test + public void activities_have_link_to_project_statistics_page() { + tester.clickLink(path("panel", CONTAINER, PROJECT_ACTIVITY_LIST, 0, DETAILS_LINK)); + tester.assertRenderedPage(AdminProjectMilestoneDetailsPage.class); + } + + @Test + public void go_to_individual_milestone_activity_details() { + tester.clickLink(path("panel", CONTAINER, INDIVIDUAL_ACTIVITY_LIST, 0, INDIVIDUAL_ACTIVITY_NAME)); + + tester.assertRenderedPage(AdminIndividualMilestoneDetailsPage.class); + } + + private void initActivities() { + projectActivity = createActivity( + MilestoneActivityTemplate.Type.PROJECT, + "Project milestone", + "This is it..", + 0 + ); + projectActivities = asList(projectActivity); + individualActivity = createActivity(MilestoneActivityTemplate.Type.STUDENT, "Student milestone", "Hi?", 0); + individualActivities = asList(individualActivity); + + Mockito.when( + milestoneActivityTemplateService.getAllActivities( + eq(MilestoneActivityTemplate.Type.PROJECT), + eq(projectTypes) + ) + ).thenReturn(projectActivities); + Mockito.when( + milestoneActivityTemplateService.getAllActivities( + eq(MilestoneActivityTemplate.Type.STUDENT), + eq(projectTypes) + ) + ).thenReturn(individualActivities); + } + + private String getMileStoneDateField() { + return path("panel", MILESTONE_DATE_FILTER); + } + + private String getProjectTypeCheckGroup() { + return path("panel", PROJECT_TYPE_FILTER); + } + + private String getProjectStatusCheckGroup() { + return path("panel", PROJECT_STATUSES); + } + + private String getProjectDateField(String dateField) { + return path( + "panel", + DATE_FILTER, + DeactivatableDatePickerPanel.DATE_PICKER, + DatePickerPanel.DATE_FORM, + dateField + ); + } + + private void enableDateFilter() { + setDateFilterEnabled(true); + } + + private void disableDateFilter() { + setDateFilterEnabled(false); + } + + private void setDateFilterEnabled(boolean enabled) { + FormComponent dateFilterToggle = (FormComponent) tester.getComponentFromLastRenderedPage( + path("panel", DATE_FILTER, DeactivatableDatePickerPanel.TOGGLE) + ); + tester + .getRequest() + .getPostParameters() + .setParameterValue(dateFilterToggle.getInputName(), Boolean.toString(enabled)); + tester.executeAjaxEvent(dateFilterToggle, "click"); + } + + MilestoneActivityTemplate createActivity( + MilestoneActivityTemplate.Type type, + String title, + String description, + int order + ) { + MilestoneActivityTemplate activity = new MilestoneActivityTemplate(); + activity.setType(type); + activity.setTitle(title); + activity.setDescription(description); + activity.setMilestonePhaseTemplate(new MilestonePhaseTemplate("phase test", "this is for test", 0)); + activity.setProjectTypes(new HashSet<>(projectTypes)); + activity.setSortOrder(order); + return activity; + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanelTest.java index 93bff5d062..91f1b50ff1 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/MilestoneStatisticsProgressPanelTest.java @@ -1,5 +1,9 @@ package se.su.dsv.scipro.statistics; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,12 +12,8 @@ import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; import se.su.dsv.scipro.milestones.dataobjects.MilestonePhaseTemplate; import se.su.dsv.scipro.test.DomainObjects; -import java.util.Arrays; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class MilestoneStatisticsProgressPanelTest extends SciProTest { + private MilestoneActivityTemplate completed; private MilestoneActivityTemplate notCompleted; @@ -41,4 +41,4 @@ public class MilestoneStatisticsProgressPanelTest extends SciProTest { verify(milestoneStatisticsService).countProgressedProjects(completed, notCompleted); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanelTest.java index 42678ee12d..2896c1e4d9 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/ProjectMilestoneDetailsPanelTest.java @@ -1,64 +1,78 @@ -package se.su.dsv.scipro.statistics; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import se.su.dsv.scipro.system.Pageable; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.Milestone; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.UserBuilder; - -import java.time.LocalDate; -import java.util.Collections; -import java.util.List; - -public class ProjectMilestoneDetailsPanelTest extends SciProTest { - public static final String PROJECT_PLAN_APPROVED = "Project plan approved"; - public static final User HEAD_SUPERVISOR = new UserBuilder().create(); - public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); - public static final Project SOME_PROJECT = Project.builder().title("project").projectType(SOME_PROJECT_TYPE).startDate(LocalDate.now()).headSupervisor(HEAD_SUPERVISOR).build(); - - private MilestoneActivityTemplate activity; - - @BeforeEach - public void setUp() throws Exception { - createActivity(); - } - - @Test - public void shows_milestone_activity_title() { - startPanel(); - tester.assertLabel(path("id", "title"), activity.getTitle()); - } - - private void mockList(MileStoneService.Filter filter) { - Mockito.when(mileStoneService.findCompletedMilestones(ArgumentMatchers.eq(activity), ArgumentMatchers.eq(filter), ArgumentMatchers.any(Pageable.class))).thenReturn(getMileStoneList()); - Mockito.when(mileStoneService.countCompletedMileStones(activity, filter)).thenReturn(1L); - } - - private List getMileStoneList() { - return Collections.singletonList(new Milestone(SOME_PROJECT, activity)); - } - - private void startPanel() { - startPage(new MileStoneService.Filter()); - } - - private void startPage(MileStoneService.Filter filter) { - mockList(filter); - tester.startComponentInPage(new ProjectMilestoneDetailsPanel("id", Model.of(activity), filter)); - } - - private void createActivity() { - activity = new MilestoneActivityTemplate(MilestoneActivityTemplate.Type.PROJECT, PROJECT_PLAN_APPROVED, "description"); - } - -} +package se.su.dsv.scipro.statistics; + +import java.time.LocalDate; +import java.util.Collections; +import java.util.List; +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.Milestone; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.Pageable; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.UserBuilder; + +public class ProjectMilestoneDetailsPanelTest extends SciProTest { + + public static final String PROJECT_PLAN_APPROVED = "Project plan approved"; + public static final User HEAD_SUPERVISOR = new UserBuilder().create(); + public static final ProjectType SOME_PROJECT_TYPE = new ProjectType(DegreeType.BACHELOR, "bachelor", "bachelor"); + public static final Project SOME_PROJECT = Project.builder() + .title("project") + .projectType(SOME_PROJECT_TYPE) + .startDate(LocalDate.now()) + .headSupervisor(HEAD_SUPERVISOR) + .build(); + + private MilestoneActivityTemplate activity; + + @BeforeEach + public void setUp() throws Exception { + createActivity(); + } + + @Test + public void shows_milestone_activity_title() { + startPanel(); + tester.assertLabel(path("id", "title"), activity.getTitle()); + } + + private void mockList(MileStoneService.Filter filter) { + Mockito.when( + mileStoneService.findCompletedMilestones( + ArgumentMatchers.eq(activity), + ArgumentMatchers.eq(filter), + ArgumentMatchers.any(Pageable.class) + ) + ).thenReturn(getMileStoneList()); + Mockito.when(mileStoneService.countCompletedMileStones(activity, filter)).thenReturn(1L); + } + + private List getMileStoneList() { + return Collections.singletonList(new Milestone(SOME_PROJECT, activity)); + } + + private void startPanel() { + startPage(new MileStoneService.Filter()); + } + + private void startPage(MileStoneService.Filter filter) { + mockList(filter); + tester.startComponentInPage(new ProjectMilestoneDetailsPanel("id", Model.of(activity), filter)); + } + + private void createActivity() { + activity = new MilestoneActivityTemplate( + MilestoneActivityTemplate.Type.PROJECT, + PROJECT_PLAN_APPROVED, + "description" + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorIdeaStatisticsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorIdeaStatisticsPanelTest.java index c8b86c0b1f..ca42aac97e 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorIdeaStatisticsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorIdeaStatisticsPanelTest.java @@ -18,6 +18,6 @@ public class SupervisorIdeaStatisticsPanelTest extends SciProTest { @Test public void testRenders() throws Exception { - tester.assertNoErrorMessage(); + tester.assertNoErrorMessage(); } } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanelTest.java index 4ee1c3e34f..cbac3f2b48 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorProjectStatisticsPanelTest.java @@ -18,6 +18,6 @@ public class SupervisorProjectStatisticsPanelTest extends SciProTest { @Test public void testRenders() throws Exception { - tester.assertNoErrorMessage(); + tester.assertNoErrorMessage(); } } diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPageTest.java index 1854ea91a0..8d331865da 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.statistics; +import static se.su.dsv.scipro.statistics.SupervisorStatisticsPage.PANEL; + import org.apache.wicket.Page; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -8,8 +10,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import se.su.dsv.scipro.PageTest; import se.su.dsv.scipro.security.auth.roles.Roles; -import static se.su.dsv.scipro.statistics.SupervisorStatisticsPage.PANEL; - @ExtendWith(MockitoExtension.class) public class SupervisorStatisticsPageTest extends PageTest { diff --git a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanelTest.java b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanelTest.java index 51335a05b2..5c977cde76 100644 --- a/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/statistics/SupervisorStatisticsPanelTest.java @@ -8,7 +8,7 @@ import se.su.dsv.scipro.SciProTest; @ExtendWith(MockitoExtension.class) public class SupervisorStatisticsPanelTest extends SciProTest { - + SupervisorStatisticsPanel panel; @BeforeEach @@ -18,7 +18,6 @@ public class SupervisorStatisticsPanelTest extends SciProTest { @Test public void testRenders() throws Exception { - tester.assertNoErrorMessage(); + tester.assertNoErrorMessage(); } - } diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPageTest.java index a46531bcc3..9f000d51c8 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorEditGroupPageTest.java @@ -6,6 +6,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.group.EditGroupPanel; public class SupervisorEditGroupPageTest extends SciProTest { + @BeforeEach public void setUp() throws Exception { startPage(); diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePageTest.java index d3fbe3f9f3..318f51870c 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorFilePageTest.java @@ -1,14 +1,15 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + import org.apache.wicket.Page; import org.junit.jupiter.api.BeforeEach; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.system.User; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - public class SupervisorFilePageTest extends SupervisorPageTest { + @BeforeEach public void setUp() throws Exception { when(projectService.isPartOfProject(any(Project.class), any(User.class))).thenReturn(true); diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPageTest.java index 2f42556686..f97079577c 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupCreateThreadPageTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -8,9 +11,6 @@ import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorGroupCreateThreadPageTest extends PageTest { Group group; @@ -37,5 +37,4 @@ public class SupervisorGroupCreateThreadPageTest extends PageTest { pageParameters.add(PageParameterKeys.MAP.get(Group.class), 1); return pageParameters; } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPageTest.java index 0d99e818fc..7ae23e7929 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorGroupPageTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -8,9 +11,6 @@ import se.su.dsv.scipro.group.Group; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.util.PageParameterKeys; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorGroupPageTest extends PageTest { Group group; @@ -37,5 +37,4 @@ public class SupervisorGroupPageTest extends PageTest { pageParameters.add(PageParameterKeys.MAP.get(Group.class), 1); return pageParameters; } - -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPageTest.java index 02d233416e..f24a016c18 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorIndividualMilestoneDetailsPageTest.java @@ -1,17 +1,21 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; - -public class SupervisorIndividualMilestoneDetailsPageTest extends SciProTest { - - @Test - public void renders() throws Exception { - tester.startPage(new SupervisorIndividualMilestoneDetailsPage(Model.of(new MilestoneActivityTemplate()), new MileStoneService.Filter())); - tester.assertRenderedPage(SupervisorIndividualMilestoneDetailsPage.class); - - } -} +package se.su.dsv.scipro.supervisor.pages; + +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; + +public class SupervisorIndividualMilestoneDetailsPageTest extends SciProTest { + + @Test + public void renders() throws Exception { + tester.startPage( + new SupervisorIndividualMilestoneDetailsPage( + Model.of(new MilestoneActivityTemplate()), + new MileStoneService.Filter() + ) + ); + tester.assertRenderedPage(SupervisorIndividualMilestoneDetailsPage.class); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPageTest.java index 37141f275e..be3b7d901b 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorInteractWithReviewerPageTest.java @@ -1,11 +1,10 @@ package se.su.dsv.scipro.supervisor.pages; -import org.apache.wicket.Page; -import org.junit.jupiter.api.BeforeEach; +import static org.mockito.Mockito.when; import java.util.Optional; - -import static org.mockito.Mockito.when; +import org.apache.wicket.Page; +import org.junit.jupiter.api.BeforeEach; public class SupervisorInteractWithReviewerPageTest extends SupervisorPageTest { @@ -19,4 +18,4 @@ public class SupervisorInteractWithReviewerPageTest extends SupervisorPageTest { protected Class getPage() { return SupervisorInteractWithReviewerPage.class; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPageTest.java index 14625389da..3c19e39238 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorMilestoneStatisticsPageTest.java @@ -1,38 +1,42 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; - -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyCollection; -import static org.mockito.Mockito.when; - -public class SupervisorMilestoneStatisticsPageTest extends SciProTest { - @BeforeEach - public void setUp() throws Exception { - when(milestoneActivityTemplateService.getAllActivities(any(MilestoneActivityTemplate.Type.class), anyCollection())) - .thenReturn(Collections.singletonList(new MilestoneActivityTemplate())); - tester.startPage(SupervisorMilestoneStatisticsPage.class); - } - - @Test - public void renders() throws Exception { - tester.assertRenderedPage(SupervisorMilestoneStatisticsPage.class); - } - - @Test - public void individual_page_link_links_to_supervisor_individual_page() { - tester.clickLink(path("statistics", "container", "individualActivityList", 0, "individualActivityName")); - tester.assertRenderedPage(SupervisorIndividualMilestoneDetailsPage.class); - } - - @Test - public void project_page_link_links_to_supervisor_project_page() { - tester.clickLink(path("statistics", "container", "projectActivityList", 0, "detailsLink")); - tester.assertRenderedPage(SupervisorProjectMilestoneDetailsPage.class); - } -} +package se.su.dsv.scipro.supervisor.pages; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; + +public class SupervisorMilestoneStatisticsPageTest extends SciProTest { + + @BeforeEach + public void setUp() throws Exception { + when( + milestoneActivityTemplateService.getAllActivities( + any(MilestoneActivityTemplate.Type.class), + anyCollection() + ) + ).thenReturn(Collections.singletonList(new MilestoneActivityTemplate())); + tester.startPage(SupervisorMilestoneStatisticsPage.class); + } + + @Test + public void renders() throws Exception { + tester.assertRenderedPage(SupervisorMilestoneStatisticsPage.class); + } + + @Test + public void individual_page_link_links_to_supervisor_individual_page() { + tester.clickLink(path("statistics", "container", "individualActivityList", 0, "individualActivityName")); + tester.assertRenderedPage(SupervisorIndividualMilestoneDetailsPage.class); + } + + @Test + public void project_page_link_links_to_supervisor_project_page() { + tester.clickLink(path("statistics", "container", "projectActivityList", 0, "detailsLink")); + tester.assertRenderedPage(SupervisorProjectMilestoneDetailsPage.class); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorPageTest.java index 57424e6adb..3223e22718 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorPageTest.java @@ -1,5 +1,10 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; import se.su.dsv.scipro.PageTest; @@ -10,31 +15,29 @@ import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - public abstract class SupervisorPageTest extends PageTest { - protected Project project; + protected Project project; - @BeforeEach + @BeforeEach public void setUpProject() { Project project = createProject(); - setLoggedInAs(project.getHeadSupervisor()); + setLoggedInAs(project.getHeadSupervisor()); when(projectService.findOne(anyLong())).thenReturn(project); when(projectService.hasSupervisingRole(any(Project.class), any(User.class))).thenReturn(true); } protected Project createProject() { - User user = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); - DomainObjects.injectId(user, 6814684L); + User user = User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build(); + DomainObjects.injectId(user, 6814684L); - project = Project.builder().title("some title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); - DomainObjects.injectId(project, 1L); + project = Project.builder() + .title("some title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); + DomainObjects.injectId(project, 1L); project.setHeadSupervisor(user); return project; } diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePageTest.java index 0e54504f1c..8db0415c35 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProfilePageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.verify; + +import java.io.Serializable; +import java.util.*; import org.apache.wicket.feedback.FeedbackMessage; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.Test; @@ -8,13 +14,6 @@ import se.su.dsv.scipro.system.ResearchArea; import se.su.dsv.scipro.system.Unit; import se.su.dsv.scipro.system.User; -import java.io.Serializable; -import java.util.*; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.Mockito.verify; - public class SupervisorProfilePageTest extends SciProTest { @Test diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPageTest.java index 4d52dc14ed..333a68ce11 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectDetailsPageTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; +import java.util.Collections; import org.apache.wicket.Page; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.junit.jupiter.api.BeforeEach; @@ -16,13 +22,6 @@ import se.su.dsv.scipro.test.DomainObjects; import se.su.dsv.scipro.test.UserBuilder; import se.su.dsv.scipro.util.PageParameterKeys; -import java.time.LocalDate; -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.when; - public class SupervisorProjectDetailsPageTest extends PageTest { private Project masterProject; @@ -31,16 +30,26 @@ public class SupervisorProjectDetailsPageTest extends PageTest { public void setUp() throws Exception { User headSupervisor = new UserBuilder().setFirstName("head").setLastName("supervisor").create(); User student = new UserBuilder().setFirstName("author").setLastName("1").create(); - Project bachelorProject = createProject(headSupervisor, student, - new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"), 1L); - masterProject = createProject(headSupervisor, student, - new ProjectType(DegreeType.MASTER, "master", "master"), 3L); + Project bachelorProject = createProject( + headSupervisor, + student, + new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor"), + 1L + ); + masterProject = createProject( + headSupervisor, + student, + new ProjectType(DegreeType.MASTER, "master", "master"), + 3L + ); when(projectService.findOne(isA(Long.class))).thenReturn(bachelorProject); when(projectService.hasSupervisingRole(isA(Project.class), isA(User.class))).thenReturn(true); FileDescription fileDescription = new FileDescription(); fileDescription.setMimeType("pdf"); fileDescription.setId(1L); - when(finalSeminarService.getOppositionsByProjectAuthors(any(Project.class))).thenReturn(Collections.emptyList()); + when(finalSeminarService.getOppositionsByProjectAuthors(any(Project.class))).thenReturn( + Collections.emptyList() + ); } @Test @@ -64,16 +73,17 @@ public class SupervisorProjectDetailsPageTest extends PageTest { startPage(); PageParameters parameters = new PageParameters(); parameters.add(PageParameterKeys.MAP.get(Group.class), id); - tester.assertBookmarkablePageLink(path("groups", "groupList", 0, "groupLink"), - SupervisorGroupPage.class, parameters); + tester.assertBookmarkablePageLink( + path("groups", "groupList", 0, "groupLink"), + SupervisorGroupPage.class, + parameters + ); } private void mockGroup(long id) { Group group = new Group(); group.setId(id); - when(groupService.findAll(any(GroupService.Filter.class))).thenReturn( - Collections.singletonList(group) - ); + when(groupService.findAll(any(GroupService.Filter.class))).thenReturn(Collections.singletonList(group)); } @Override @@ -89,9 +99,12 @@ public class SupervisorProjectDetailsPageTest extends PageTest { } private Project createProject(User headSupervisor, User student, ProjectType projectType, long id) { - Project project = Project.builder().title("some title").projectType(projectType) - .startDate(LocalDate.now()) - .headSupervisor(headSupervisor).build(); + Project project = Project.builder() + .title("some title") + .projectType(projectType) + .startDate(LocalDate.now()) + .headSupervisor(headSupervisor) + .build(); DomainObjects.injectId(project, id); return project; } diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPageTest.java index fe9c6ca558..940bcd4664 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorProjectMilestoneDetailsPageTest.java @@ -1,17 +1,21 @@ -package se.su.dsv.scipro.supervisor.pages; - -import org.apache.wicket.model.Model; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; -import se.su.dsv.scipro.milestones.service.MileStoneService; - -public class SupervisorProjectMilestoneDetailsPageTest extends SciProTest { - - @Test - public void renders() throws Exception { - tester.startPage(new SupervisorProjectMilestoneDetailsPage(Model.of(new MilestoneActivityTemplate()), new MileStoneService.Filter())); - tester.assertRenderedPage(SupervisorProjectMilestoneDetailsPage.class); - - } -} +package se.su.dsv.scipro.supervisor.pages; + +import org.apache.wicket.model.Model; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.milestones.dataobjects.MilestoneActivityTemplate; +import se.su.dsv.scipro.milestones.service.MileStoneService; + +public class SupervisorProjectMilestoneDetailsPageTest extends SciProTest { + + @Test + public void renders() throws Exception { + tester.startPage( + new SupervisorProjectMilestoneDetailsPage( + Model.of(new MilestoneActivityTemplate()), + new MileStoneService.Filter() + ) + ); + tester.assertRenderedPage(SupervisorProjectMilestoneDetailsPage.class); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPageTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPageTest.java index 5177f3dfbc..f981411e87 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/pages/SupervisorStartPageTest.java @@ -1,10 +1,20 @@ package se.su.dsv.scipro.supervisor.pages; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; +import static se.su.dsv.scipro.supervisor.pages.SupervisorStartPage.PROJECTS_OVERVIEW_PANEL; + +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.project.Project; import se.su.dsv.scipro.project.ProjectService; @@ -12,22 +22,11 @@ import se.su.dsv.scipro.project.ProjectStatus; import se.su.dsv.scipro.project.ProjectTeamMemberRoles; import se.su.dsv.scipro.settings.dataobjects.UserProfile; import se.su.dsv.scipro.supervisor.panels.SupervisorMyProjectsPanel; +import se.su.dsv.scipro.system.Pageable; import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; - -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; -import static se.su.dsv.scipro.supervisor.pages.SupervisorStartPage.PROJECTS_OVERVIEW_PANEL; - public class SupervisorStartPageTest extends SciProTest { private UserProfile userProfile; @@ -46,7 +45,6 @@ public class SupervisorStartPageTest extends SciProTest { @Test public void select_supervisor_only_filter() { - filterForm().setValue(SupervisorMyProjectsPanel.SUPERVISOR, false).submit(); assertEquals(false, getFilterParams().isFilterSupervisor()); @@ -107,12 +105,19 @@ public class SupervisorStartPageTest extends SciProTest { private void mockProjectsInDatabase() { ProjectType bachelor = new ProjectType(ProjectType.BACHELOR, "Bachelor", "Bachelor"); - Project project = Project.builder().title("Some project").projectType(bachelor).startDate(LocalDate.now()).build(); - project.setHeadSupervisor(User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build()); + Project project = Project.builder() + .title("Some project") + .projectType(bachelor) + .startDate(LocalDate.now()) + .build(); + project.setHeadSupervisor( + User.builder().firstName("Bob").lastName("Sponge").emailAddress("bob@example.com").build() + ); DomainObjects.injectId(project, 1L); - when(projectService.findAll(any(ProjectService.Filter.class), any(Pageable.class))) - .thenReturn(pageContaining(project)); + when(projectService.findAll(any(ProjectService.Filter.class), any(Pageable.class))).thenReturn( + pageContaining(project) + ); when(projectService.count(any(ProjectService.Filter.class))).thenReturn(1L); } diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanelTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanelTest.java index 6700780684..35269ebf7a 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/FinalSeminarApprovalProcessPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.panels; +import static org.mockito.Mockito.mock; + +import java.util.*; import org.apache.wicket.markup.html.basic.EnumLabel; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.model.IModel; @@ -14,25 +17,25 @@ import se.su.dsv.scipro.repository.panels.ViewAttachmentPanel; import se.su.dsv.scipro.reviewing.FinalSeminarApproval; import se.su.dsv.scipro.reviewing.ReviewerApproval; -import java.util.*; - -import static org.mockito.Mockito.mock; - public class FinalSeminarApprovalProcessPanelTest extends SciProTest { + private ReviewerApproval finalSeminarApproval; private FinalSeminarApprovalProcessPanel panel; @BeforeEach public void setUp() throws Exception { final FileReference thesis = getFileReference(1L); - finalSeminarApproval = new FinalSeminarApproval(mock(Project.class), thesis,"test", new Date()); + finalSeminarApproval = new FinalSeminarApproval(mock(Project.class), thesis, "test", new Date()); startPanel(); } @Test public void shows_current_file() { tester.assertComponent(path(panel, "currentThesis"), ViewAttachmentPanel.class); - tester.assertModelValue(path(panel, "currentThesis"), finalSeminarApproval.getCurrentThesis().getFileDescription()); + tester.assertModelValue( + path(panel, "currentThesis"), + finalSeminarApproval.getCurrentThesis().getFileDescription() + ); } @Test @@ -56,7 +59,10 @@ public class FinalSeminarApprovalProcessPanelTest extends SciProTest { public void shows_current_attachment() { startPanelWithApprovedFinalSeminar(); tester.assertComponent(path(panel, "currentAttachment"), ViewAttachmentPanel.class); - tester.assertModelValue(path(panel, "currentAttachment"), finalSeminarApproval.getCurrentAttachment().map(FileReference::getFileDescription).orElse(null)); + tester.assertModelValue( + path(panel, "currentAttachment"), + finalSeminarApproval.getCurrentAttachment().map(FileReference::getFileDescription).orElse(null) + ); } private void startPanelWithApprovedFinalSeminar() { diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanelTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanelTest.java index 280d53cfc5..cedd1f903b 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorExternalProjectPanelTest.java @@ -1,5 +1,8 @@ package se.su.dsv.scipro.supervisor.panels; +import static org.mockito.Mockito.verify; +import static se.su.dsv.scipro.supervisor.panels.SupervisorExternalProjectPanel.*; + import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; @@ -11,9 +14,6 @@ import se.su.dsv.scipro.components.InfoPanel; import se.su.dsv.scipro.project.ExternalOrganization; import se.su.dsv.scipro.project.Project; -import static org.mockito.Mockito.verify; -import static se.su.dsv.scipro.supervisor.panels.SupervisorExternalProjectPanel.*; - @ExtendWith(MockitoExtension.class) public class SupervisorExternalProjectPanelTest extends SciProTest { diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanelTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanelTest.java index 38c42acb96..4bc167ebf1 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorSubTabMenuPanelTest.java @@ -1,117 +1,144 @@ -package se.su.dsv.scipro.supervisor.panels; - -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.project.Project; -import se.su.dsv.scipro.project.pages.AbstractProjectDetailsPage; -import se.su.dsv.scipro.system.DegreeType; -import se.su.dsv.scipro.system.ProjectModule; -import se.su.dsv.scipro.system.ProjectType; -import se.su.dsv.scipro.system.User; -import se.su.dsv.scipro.test.ObjectMother; -import se.su.dsv.scipro.test.UserBuilder; - -import java.time.LocalDate; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.FINAL_SEMINAR; -import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.INTERACT_WITH_REVIEWER; -import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.MILESTONES; - -public class SupervisorSubTabMenuPanelTest extends SciProTest { - - public static final Project SOME_BACHELOR_PROJECT = Project.builder().title("Title").projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")).startDate(LocalDate.now()).build(); - public static final Project SOME_MASTER_PROJECT = Project.builder().title("Title").projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")).startDate(LocalDate.now()).build(); - public static final Project ICT4D_PROJECT = Project.builder().title("ICT4D").projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")).startDate(LocalDate.now()).build(); - private User reviewer; - - @BeforeEach - public void setUp() throws Exception { - reviewer = new UserBuilder().create(); - } - - @Test - public void renders() throws Exception { - assertNotNull(startPanel(SOME_BACHELOR_PROJECT)); - } - - @Test - public void milestone_tab_is_hidden_if_no_activities_are_available() { - when(milestoneActivityTemplateService.countActivities(any(ProjectType.class), any(LocalDate.class))).thenReturn(0L); - assertNotVisible(MILESTONES, SOME_BACHELOR_PROJECT); - } - - @Test - public void milestone_is_visible_if_activities_are_available() { - when(milestoneActivityTemplateService.countActivities(any(ProjectType.class), any(LocalDate.class))).thenReturn(1L); - assertVisible(MILESTONES, SOME_BACHELOR_PROJECT); - } - - @Test - public void final_seminar_tab_is_hidden_if_no_seminar_module() { - setModules(ProjectModule.CHECKLIST); - assertNotVisible(FINAL_SEMINAR, ICT4D_PROJECT); - } - - @Test - public void final_seminar_tab_is_visible_if_first_cycle() { - assertVisible(FINAL_SEMINAR, SOME_BACHELOR_PROJECT); - } - - @Test - public void final_seminar_tab_is_visible_if_second_cycle() { - assertVisible(FINAL_SEMINAR, SOME_MASTER_PROJECT); - } - - @Test - public void reviewer_interaction_tab_is_invisible_if_not_head_supervisor() { - assertNotVisible(INTERACT_WITH_REVIEWER, SOME_BACHELOR_PROJECT); - } - - @Test - public void reviewer_interaction_tab_is_visible_if_head_supervisor() { - Project project = mockProjectWithSupervisorLoggedIn(); - project.getProjectType().setReviewed(true); - assertVisible(INTERACT_WITH_REVIEWER, project); - } - - @Test - public void reviewer_interaction_is_not_visible_if_no_reviewer_is_attached() { - Project project = mockProjectWithSupervisorLoggedIn(); - project.getProjectType().setReviewed(false); - assertNotVisible(INTERACT_WITH_REVIEWER, project); - } - - private Project mockProjectWithSupervisorLoggedIn() { - User supervisor = new UserBuilder().create(); - setLoggedInAs(supervisor); - Project project = Project.builder().title("test").projectType(ObjectMother.BACHELOR).startDate(LocalDate.now()).headSupervisor(supervisor).build(); - project.addReviewer(reviewer); - return project; - } - - private String renderedPanel(Project project) { - startPanel(project); - return tester.getLastResponseAsString(); - } - - private void assertVisible(String menuChoice, Project project) { - assertThat(renderedPanel(project), containsString(menuChoice)); - } - - private void assertNotVisible(String menuChoice, Project project) { - assertThat(renderedPanel(project), not(containsString(menuChoice))); - } - - private SupervisorSubTabMenuPanel startPanel(Project project) { - return tester.startComponentInPage(new SupervisorSubTabMenuPanel("id", AbstractProjectDetailsPage.class, new PageParameters(), Model.of(project))); - } -} +package se.su.dsv.scipro.supervisor.panels; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.FINAL_SEMINAR; +import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.INTERACT_WITH_REVIEWER; +import static se.su.dsv.scipro.supervisor.panels.SupervisorSubTabMenuPanel.MILESTONES; + +import java.time.LocalDate; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.project.Project; +import se.su.dsv.scipro.project.pages.AbstractProjectDetailsPage; +import se.su.dsv.scipro.system.DegreeType; +import se.su.dsv.scipro.system.ProjectModule; +import se.su.dsv.scipro.system.ProjectType; +import se.su.dsv.scipro.system.User; +import se.su.dsv.scipro.test.ObjectMother; +import se.su.dsv.scipro.test.UserBuilder; + +public class SupervisorSubTabMenuPanelTest extends SciProTest { + + public static final Project SOME_BACHELOR_PROJECT = Project.builder() + .title("Title") + .projectType(new ProjectType(DegreeType.BACHELOR, "Bachelor", "Bachelor")) + .startDate(LocalDate.now()) + .build(); + public static final Project SOME_MASTER_PROJECT = Project.builder() + .title("Title") + .projectType(new ProjectType(DegreeType.MASTER, "Master", "Master")) + .startDate(LocalDate.now()) + .build(); + public static final Project ICT4D_PROJECT = Project.builder() + .title("ICT4D") + .projectType(new ProjectType(DegreeType.NONE, "ICT4D", "ICT4D")) + .startDate(LocalDate.now()) + .build(); + private User reviewer; + + @BeforeEach + public void setUp() throws Exception { + reviewer = new UserBuilder().create(); + } + + @Test + public void renders() throws Exception { + assertNotNull(startPanel(SOME_BACHELOR_PROJECT)); + } + + @Test + public void milestone_tab_is_hidden_if_no_activities_are_available() { + when(milestoneActivityTemplateService.countActivities(any(ProjectType.class), any(LocalDate.class))).thenReturn( + 0L + ); + assertNotVisible(MILESTONES, SOME_BACHELOR_PROJECT); + } + + @Test + public void milestone_is_visible_if_activities_are_available() { + when(milestoneActivityTemplateService.countActivities(any(ProjectType.class), any(LocalDate.class))).thenReturn( + 1L + ); + assertVisible(MILESTONES, SOME_BACHELOR_PROJECT); + } + + @Test + public void final_seminar_tab_is_hidden_if_no_seminar_module() { + setModules(ProjectModule.CHECKLIST); + assertNotVisible(FINAL_SEMINAR, ICT4D_PROJECT); + } + + @Test + public void final_seminar_tab_is_visible_if_first_cycle() { + assertVisible(FINAL_SEMINAR, SOME_BACHELOR_PROJECT); + } + + @Test + public void final_seminar_tab_is_visible_if_second_cycle() { + assertVisible(FINAL_SEMINAR, SOME_MASTER_PROJECT); + } + + @Test + public void reviewer_interaction_tab_is_invisible_if_not_head_supervisor() { + assertNotVisible(INTERACT_WITH_REVIEWER, SOME_BACHELOR_PROJECT); + } + + @Test + public void reviewer_interaction_tab_is_visible_if_head_supervisor() { + Project project = mockProjectWithSupervisorLoggedIn(); + project.getProjectType().setReviewed(true); + assertVisible(INTERACT_WITH_REVIEWER, project); + } + + @Test + public void reviewer_interaction_is_not_visible_if_no_reviewer_is_attached() { + Project project = mockProjectWithSupervisorLoggedIn(); + project.getProjectType().setReviewed(false); + assertNotVisible(INTERACT_WITH_REVIEWER, project); + } + + private Project mockProjectWithSupervisorLoggedIn() { + User supervisor = new UserBuilder().create(); + setLoggedInAs(supervisor); + Project project = Project.builder() + .title("test") + .projectType(ObjectMother.BACHELOR) + .startDate(LocalDate.now()) + .headSupervisor(supervisor) + .build(); + project.addReviewer(reviewer); + return project; + } + + private String renderedPanel(Project project) { + startPanel(project); + return tester.getLastResponseAsString(); + } + + private void assertVisible(String menuChoice, Project project) { + assertThat(renderedPanel(project), containsString(menuChoice)); + } + + private void assertNotVisible(String menuChoice, Project project) { + assertThat(renderedPanel(project), not(containsString(menuChoice))); + } + + private SupervisorSubTabMenuPanel startPanel(Project project) { + return tester.startComponentInPage( + new SupervisorSubTabMenuPanel( + "id", + AbstractProjectDetailsPage.class, + new PageParameters(), + Model.of(project) + ) + ); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanelTest.java b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanelTest.java index 3fe9304de6..7b974d9b2b 100644 --- a/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/supervisor/panels/SupervisorTabMenuPanelTest.java @@ -1,45 +1,45 @@ -package se.su.dsv.scipro.supervisor.panels; - -import org.junit.jupiter.api.Test; -import se.su.dsv.scipro.SciProTest; -import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorPage; -import se.su.dsv.scipro.system.ProjectModule; - -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringContains.containsString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - -public class SupervisorTabMenuPanelTest extends SciProTest { - - @Test - public void ideas_tab_visible_if_project_type_have_match_module() { - when(projectTypeService.projectTypeWithModuleExists(ProjectModule.MATCH)).thenReturn(true); - startPanel(); - assertVisible("Ideas"); - } - - @Test - public void ideas_tab_not_visible_if_project_type_does_not_have_match_module() { - when(projectTypeService.projectTypeWithModuleExists(ProjectModule.MATCH)).thenReturn(false); - startPanel(); - assertNotVisible("Ideas"); - } - - private SupervisorTabMenuPanel startPanel() { - return tester.startComponentInPage(new SupervisorTabMenuPanel("id", AbstractSupervisorPage.class)); - } - - private String renderedPanel() { - startPanel(); - return tester.getLastResponseAsString(); - } - - private void assertVisible(String menuChoice) { - assertThat(renderedPanel(), containsString(menuChoice)); - } - - private void assertNotVisible(String menuChoice) { - assertThat(renderedPanel(), not(containsString(menuChoice))); - } -} +package se.su.dsv.scipro.supervisor.panels; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import se.su.dsv.scipro.SciProTest; +import se.su.dsv.scipro.supervisor.pages.AbstractSupervisorPage; +import se.su.dsv.scipro.system.ProjectModule; + +public class SupervisorTabMenuPanelTest extends SciProTest { + + @Test + public void ideas_tab_visible_if_project_type_have_match_module() { + when(projectTypeService.projectTypeWithModuleExists(ProjectModule.MATCH)).thenReturn(true); + startPanel(); + assertVisible("Ideas"); + } + + @Test + public void ideas_tab_not_visible_if_project_type_does_not_have_match_module() { + when(projectTypeService.projectTypeWithModuleExists(ProjectModule.MATCH)).thenReturn(false); + startPanel(); + assertNotVisible("Ideas"); + } + + private SupervisorTabMenuPanel startPanel() { + return tester.startComponentInPage(new SupervisorTabMenuPanel("id", AbstractSupervisorPage.class)); + } + + private String renderedPanel() { + startPanel(); + return tester.getLastResponseAsString(); + } + + private void assertVisible(String menuChoice) { + assertThat(renderedPanel(), containsString(menuChoice)); + } + + private void assertNotVisible(String menuChoice) { + assertThat(renderedPanel(), not(containsString(menuChoice))); + } +} diff --git a/view/src/test/java/se/su/dsv/scipro/thesislink/ExternalLinkPanelTest.java b/view/src/test/java/se/su/dsv/scipro/thesislink/ExternalLinkPanelTest.java index 5acd37bb05..3bb11c9be9 100644 --- a/view/src/test/java/se/su/dsv/scipro/thesislink/ExternalLinkPanelTest.java +++ b/view/src/test/java/se/su/dsv/scipro/thesislink/ExternalLinkPanelTest.java @@ -1,5 +1,13 @@ package se.su.dsv.scipro.thesislink; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static se.su.dsv.scipro.thesislink.ExternalLinkPanel.*; + +import java.time.LocalDate; +import java.util.Arrays; import org.apache.wicket.model.Model; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.BeforeEach; @@ -11,15 +19,6 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.UserBuilder; -import java.time.LocalDate; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static se.su.dsv.scipro.thesislink.ExternalLinkPanel.*; - public class ExternalLinkPanelTest extends SciProTest { private ExternalLinkPanel panel; @@ -31,7 +30,16 @@ public class ExternalLinkPanelTest extends SciProTest { project = Project.builder().title("My project").projectType(projectType).startDate(LocalDate.now()).build(); User user = new UserBuilder().setFirstName("Sten").setLastName("Sture").setEmail("sten@example.com").create(); setLoggedInAs(user); - when(externalLinkService.findByProject(isA(Project.class))).thenReturn(Arrays.asList(ExternalLink.builder().project(project).url("http://example.com").user(user).description("bla bla").build())); + when(externalLinkService.findByProject(isA(Project.class))).thenReturn( + Arrays.asList( + ExternalLink.builder() + .project(project) + .url("http://example.com") + .user(user) + .description("bla bla") + .build() + ) + ); startPanel(); } @@ -56,7 +64,7 @@ public class ExternalLinkPanelTest extends SciProTest { verify(externalLinkService).delete(isA(ExternalLink.class)); } - private void startPanel(){ + private void startPanel() { panel = tester.startComponentInPage(new ExternalLinkPanel("panel", Model.of(project))); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/user/AdminImportUserPageTest.java b/view/src/test/java/se/su/dsv/scipro/user/AdminImportUserPageTest.java index 54ba38f70d..68720dec4f 100644 --- a/view/src/test/java/se/su/dsv/scipro/user/AdminImportUserPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/user/AdminImportUserPageTest.java @@ -1,16 +1,16 @@ package se.su.dsv.scipro.user; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; import org.apache.wicket.util.tester.FormTester; import org.junit.jupiter.api.Test; import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.system.UserImportService; -import java.util.Collections; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class AdminImportUserPageTest extends SciProTest { + @Test public void search() { final String searchTerm = "199506"; @@ -57,10 +57,14 @@ public class AdminImportUserPageTest extends SciProTest { final String firstName = "John"; final String lastName = "Doe"; - UserImportService.ImportableUser importableUser = - new UserImportService.ImportableUser(firstName, lastName, email, 42); + UserImportService.ImportableUser importableUser = new UserImportService.ImportableUser( + firstName, + lastName, + email, + 42 + ); when(userImportService.search(searchTerm)).thenReturn(Collections.singletonList(importableUser)); return importableUser; } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/user/AdminSwitchUserPageTest.java b/view/src/test/java/se/su/dsv/scipro/user/AdminSwitchUserPageTest.java index 8c5884c8de..0c54bc73c8 100644 --- a/view/src/test/java/se/su/dsv/scipro/user/AdminSwitchUserPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/user/AdminSwitchUserPageTest.java @@ -1,5 +1,7 @@ package se.su.dsv.scipro.user; +import static org.hamcrest.MatcherAssert.assertThat; + import org.apache.wicket.util.tester.FormTester; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.BeforeEach; @@ -11,8 +13,6 @@ import se.su.dsv.scipro.session.SciProSession; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import static org.hamcrest.MatcherAssert.assertThat; - public class AdminSwitchUserPageTest extends SciProTest { public static final long SWITCH_TO_ID = 666L; diff --git a/view/src/test/java/se/su/dsv/scipro/user/AdminUsersPageTest.java b/view/src/test/java/se/su/dsv/scipro/user/AdminUsersPageTest.java index 2f04cb35e8..0585228ccc 100644 --- a/view/src/test/java/se/su/dsv/scipro/user/AdminUsersPageTest.java +++ b/view/src/test/java/se/su/dsv/scipro/user/AdminUsersPageTest.java @@ -5,6 +5,7 @@ import se.su.dsv.scipro.SciProTest; import se.su.dsv.scipro.security.auth.roles.Roles; public class AdminUsersPageTest extends SciProTest { + @Test public void sysadmins_default_to_switch_user() { setRoles(Roles.SYSADMIN); @@ -18,4 +19,4 @@ public class AdminUsersPageTest extends SciProTest { tester.startPage(AdminUsersPage.class); tester.assertRenderedPage(AdminRolePage.class); } -} \ No newline at end of file +} diff --git a/view/src/test/java/se/su/dsv/scipro/workerthreads/IdeaExportWorkerTest.java b/view/src/test/java/se/su/dsv/scipro/workerthreads/IdeaExportWorkerTest.java index eb8262aa44..32885ded60 100644 --- a/view/src/test/java/se/su/dsv/scipro/workerthreads/IdeaExportWorkerTest.java +++ b/view/src/test/java/se/su/dsv/scipro/workerthreads/IdeaExportWorkerTest.java @@ -1,6 +1,11 @@ package se.su.dsv.scipro.workerthreads; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import com.google.common.eventbus.EventBus; +import java.time.LocalDateTime; +import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,25 +22,24 @@ import se.su.dsv.scipro.system.ProjectType; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.DomainObjects; -import java.time.LocalDateTime; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class IdeaExportWorkerTest { @Mock private IdeaService ideaService; + @Mock private MailEventService mailService; + @Mock private IdeaCreationJudge ideaCreationJudge; + @Mock private ProjectService projectService; + @Mock private EventBus eventBus; + @Mock private FirstMeetingService firstMeetingService; @@ -45,18 +49,22 @@ public class IdeaExportWorkerTest { @BeforeEach public void setUp() throws Exception { - worker = new IdeaExportWorker(ideaService, mailService, projectService, ideaCreationJudge, eventBus, firstMeetingService) { + worker = new IdeaExportWorker( + ideaService, + mailService, + projectService, + ideaCreationJudge, + eventBus, + firstMeetingService + ) { @Override - protected void beginTransaction() { - } + protected void beginTransaction() {} @Override - protected void commitTransaction() { - } + protected void commitTransaction() {} @Override - protected void rollbackTransaction() { - } + protected void rollbackTransaction() {} }; idea = prepareIdea(); @@ -115,7 +123,11 @@ public class IdeaExportWorkerTest { private Idea prepareIdea() { User student = User.builder().firstName("Kalle").lastName("Tester").emailAddress("kalle@dsv.su.se").build(); DomainObjects.injectId(student, 234L); - User supervisor = User.builder().firstName("Henrik").lastName("Tester").emailAddress("henrik@dsv.su.se").build(); + User supervisor = User.builder() + .firstName("Henrik") + .lastName("Tester") + .emailAddress("henrik@dsv.su.se") + .build(); DomainObjects.injectId(supervisor, 34L); Match match = new Match(); match.setSupervisor(supervisor); diff --git a/view/src/test/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorkerTest.java b/view/src/test/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorkerTest.java index 710f12e5ed..bfcaef9895 100755 --- a/view/src/test/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorkerTest.java +++ b/view/src/test/java/se/su/dsv/scipro/workerthreads/NotificationCompilationWorkerTest.java @@ -1,5 +1,11 @@ package se.su.dsv.scipro.workerthreads; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,24 +27,28 @@ import se.su.dsv.scipro.springdata.services.UserProfileService; import se.su.dsv.scipro.system.User; import se.su.dsv.scipro.test.ObjectMother; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class NotificationCompilationWorkerTest { NotificationCompilationWorker worker; - @Mock NotificationService notificationService; - @Mock NotificationMailFormatter formatter; - @Mock MailEventService mailEventService; - @Mock GeneralSystemSettingsService systemSettingsService; - @Mock DeliveryConfigurationService deliveryConfiguration; - @Mock UserProfileService userProfileService; + @Mock + NotificationService notificationService; + + @Mock + NotificationMailFormatter formatter; + + @Mock + MailEventService mailEventService; + + @Mock + GeneralSystemSettingsService systemSettingsService; + + @Mock + DeliveryConfigurationService deliveryConfiguration; + + @Mock + UserProfileService userProfileService; @BeforeEach public void setUp() throws Exception { @@ -83,7 +93,14 @@ public class NotificationCompilationWorkerTest { when(userProfileService.findUsersWithMailCompilation()).thenReturn(userList); when(notificationService.findUnreadByUsers(userList)).thenReturn(notificationList); - when(deliveryConfiguration.isDelivery(eq(Notification.Type.PROJECT), isA(Enum.class), eq(DeliveryMethod.MAIL), isA(Optional.class))).thenReturn(true); + when( + deliveryConfiguration.isDelivery( + eq(Notification.Type.PROJECT), + isA(Enum.class), + eq(DeliveryMethod.MAIL), + isA(Optional.class) + ) + ).thenReturn(true); worker.doWork(); @@ -109,7 +126,14 @@ public class NotificationCompilationWorkerTest { List users = Collections.singletonList(user); when(userProfileService.findUsersWithMailCompilation()).thenReturn(users); when(notificationService.findUnreadByUsers(users)).thenReturn(notificationList); - when(deliveryConfiguration.isDelivery(eq(Notification.Type.PROJECT), isA(Enum.class), eq(DeliveryMethod.MAIL), isA(Optional.class))).thenReturn(true); + when( + deliveryConfiguration.isDelivery( + eq(Notification.Type.PROJECT), + isA(Enum.class), + eq(DeliveryMethod.MAIL), + isA(Optional.class) + ) + ).thenReturn(true); worker.doWork(); worker.doWork(); diff --git a/war/src/main/java/se/su/dsv/scipro/war/ApiConfig.java b/war/src/main/java/se/su/dsv/scipro/war/ApiConfig.java index f8b410b8aa..de84c8ddf2 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/ApiConfig.java +++ b/war/src/main/java/se/su/dsv/scipro/war/ApiConfig.java @@ -1,9 +1,10 @@ package se.su.dsv.scipro.war; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import java.util.List; import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -15,58 +16,63 @@ import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; -import java.util.List; - @Configuration(proxyBeanMethods = false) @ComponentScan("se.su.dsv.scipro.api") public class ApiConfig { + @Bean @Order(1) public SecurityFilterChain documentationSecurity( - HttpSecurity http, - HandlerMappingIntrospector introspector, - WebMvcProperties webMvcProperties) - throws Exception - { - MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector) - .servletPath(webMvcProperties.getServlet().getPath()); + HttpSecurity http, + HandlerMappingIntrospector introspector, + WebMvcProperties webMvcProperties + ) throws Exception { + MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector).servletPath( + webMvcProperties.getServlet().getPath() + ); return http - .securityMatchers(matchers -> matchers - .requestMatchers( - mvc.pattern("/v3/api-docs/**"), - mvc.pattern("/swagger"), - mvc.pattern("/swagger-ui/**"))) - .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()) - .build(); + .securityMatchers(matchers -> + matchers.requestMatchers( + mvc.pattern("/v3/api-docs/**"), + mvc.pattern("/swagger"), + mvc.pattern("/swagger-ui/**") + ) + ) + .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()) + .build(); } @Bean @Order(2) public SecurityFilterChain apiSecurity( - HttpSecurity http, - HandlerMappingIntrospector introspector, - WebMvcProperties webMvcProperties) - throws Exception - { - MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector) - .servletPath(webMvcProperties.getServlet().getPath()); + HttpSecurity http, + HandlerMappingIntrospector introspector, + WebMvcProperties webMvcProperties + ) throws Exception { + MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector).servletPath( + webMvcProperties.getServlet().getPath() + ); return http - .securityMatcher(mvc.pattern("/**")) - .authorizeHttpRequests(authorize -> authorize - .anyRequest().authenticated()) - .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults())) - .build(); + .securityMatcher(mvc.pattern("/**")) + .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) + .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults())) + .build(); } @Bean public OpenAPI customOpenAPI() { return new OpenAPI() - .security(List.of(new SecurityRequirement().addList("access-token"))) - .components(new Components() - .addSecuritySchemes("access-token", new SecurityScheme() - .type(SecurityScheme.Type.HTTP) - .in(SecurityScheme.In.HEADER) - .scheme("bearer") - .bearerFormat("opaque"))); + .security(List.of(new SecurityRequirement().addList("access-token"))) + .components( + new Components() + .addSecuritySchemes( + "access-token", + new SecurityScheme() + .type(SecurityScheme.Type.HTTP) + .in(SecurityScheme.In.HEADER) + .scheme("bearer") + .bearerFormat("opaque") + ) + ); } } diff --git a/war/src/main/java/se/su/dsv/scipro/war/MailConfig.java b/war/src/main/java/se/su/dsv/scipro/war/MailConfig.java index a96c89f56c..38e1fdcd00 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/MailConfig.java +++ b/war/src/main/java/se/su/dsv/scipro/war/MailConfig.java @@ -1,6 +1,7 @@ package se.su.dsv.scipro.war; import jakarta.mail.Session; +import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import se.su.dsv.scipro.data.facade.MailFacade; @@ -12,21 +13,16 @@ import se.su.dsv.scipro.mail.PrintingMailer; import se.su.dsv.scipro.mail.RedirectingMailer; import se.su.dsv.scipro.profiles.CurrentProfile; -import java.util.Properties; - @Configuration(proxyBeanMethods = false) public class MailConfig { + @Bean public MailFacade mailFacade() { return new MailFacade(); } @Bean - public Mailer mailer( - CurrentProfile currentProfile, - Session session, - FileService fileDescriptionService) - { + public Mailer mailer(CurrentProfile currentProfile, Session session, FileService fileDescriptionService) { return switch (currentProfile.getCurrentProfile()) { case DEV -> new PrintingMailer(); case PROD -> new Mail(session, fileDescriptionService); diff --git a/war/src/main/java/se/su/dsv/scipro/war/Main.java b/war/src/main/java/se/su/dsv/scipro/war/Main.java index 026130dd7d..9669f121d6 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/Main.java +++ b/war/src/main/java/se/su/dsv/scipro/war/Main.java @@ -5,6 +5,11 @@ import jakarta.persistence.EntityManagerFactory; import jakarta.servlet.ServletContainerInitializer; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; +import java.time.Clock; +import java.util.List; +import java.util.Optional; +import java.util.ServiceLoader; +import java.util.Set; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -34,23 +39,20 @@ import se.su.dsv.scipro.system.UserSearchProvider; import se.su.dsv.scipro.system.UserSearchService; import se.su.dsv.scipro.system.UserService; -import java.time.Clock; -import java.util.List; -import java.util.Optional; -import java.util.ServiceLoader; -import java.util.Set; - @SpringBootApplication(proxyBeanMethods = false) @EntityScan("se.su.dsv.scipro") -@Import({ +@Import( + { CoreConfig.class, ApiConfig.class, WorkerConfig.class, MailConfig.class, RepositoryConfiguration.class, - WicketConfiguration.class -}) + WicketConfiguration.class, + } +) public class Main extends SpringBootServletInitializer implements ServletContainerInitializer { + @Override public void onStartup(Set> c, ServletContext ctx) throws ServletException { onStartup(ctx); @@ -77,7 +79,7 @@ public class Main extends SpringBootServletInitializer implements ServletContain } @Bean - public CurrentProfile currentProfile(@Value("${profile}" ) String profile) { + public CurrentProfile currentProfile(@Value("${profile}") String profile) { CurrentProfile currentProfile = new CurrentProfile(); currentProfile.setCurrentProfileString(profile); return currentProfile; @@ -154,9 +156,9 @@ public class Main extends SpringBootServletInitializer implements ServletContain @Bean public UserSearchService aggregateSearchService( - Set userSearchProviders, - UserService userService) - { + Set userSearchProviders, + UserService userService + ) { return new AggregateUserSearch(userSearchProviders, userService); } diff --git a/war/src/main/java/se/su/dsv/scipro/war/SpringManagedWorkerTransactions.java b/war/src/main/java/se/su/dsv/scipro/war/SpringManagedWorkerTransactions.java index ae66a50e36..e7850528d2 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/SpringManagedWorkerTransactions.java +++ b/war/src/main/java/se/su/dsv/scipro/war/SpringManagedWorkerTransactions.java @@ -6,6 +6,7 @@ import org.springframework.transaction.TransactionStatus; import se.su.dsv.scipro.workerthreads.WorkerTransactionManager; public class SpringManagedWorkerTransactions implements WorkerTransactionManager { + private final PlatformTransactionManager platformTransactionManager; private TransactionStatus activeTransaction; diff --git a/war/src/main/java/se/su/dsv/scipro/war/WicketConfiguration.java b/war/src/main/java/se/su/dsv/scipro/war/WicketConfiguration.java index bb255d4915..db84241566 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/WicketConfiguration.java +++ b/war/src/main/java/se/su/dsv/scipro/war/WicketConfiguration.java @@ -24,13 +24,15 @@ import se.su.dsv.scipro.reviewing.RoughDraftApprovalService; @Configuration public class WicketConfiguration { + @Bean public FilterRegistrationBean wicket( - WebApplication webApplication, - ApplicationContext applicationContext) - { - webApplication.getComponentInstantiationListeners() - .add(new SpringComponentInjector(webApplication, applicationContext)); + WebApplication webApplication, + ApplicationContext applicationContext + ) { + webApplication + .getComponentInstantiationListeners() + .add(new SpringComponentInjector(webApplication, applicationContext)); WicketFilter filter = new WicketFilter(webApplication); filter.setFilterPath(""); @@ -49,52 +51,60 @@ public class WicketConfiguration { @Bean public ReviewingNotifications reviewingNotifications( - EventBus eventBus, - NotificationController notificationController, - GeneralSystemSettingsService generalSystemSettingsService, - WebApplication webApplication) - { - return new ReviewingNotifications(eventBus, notificationController, generalSystemSettingsService, - webApplication); + EventBus eventBus, + NotificationController notificationController, + GeneralSystemSettingsService generalSystemSettingsService, + WebApplication webApplication + ) { + return new ReviewingNotifications( + eventBus, + notificationController, + generalSystemSettingsService, + webApplication + ); } @Bean public ForwardPhase2Feedback forwardPhase2Feedback( - EventBus eventBus, - WebApplication webApplication, - ProjectForumService projectForumService) - { + EventBus eventBus, + WebApplication webApplication, + ProjectForumService projectForumService + ) { return new ForwardPhase2Feedback(webApplication, projectForumService, eventBus); } // Not sure why this dependency lives in the view module @Bean public ReviewerSupportMailer reviewerSupportMailer( - EventBus eventBus, - GeneralSystemSettingsService generalSystemSettingsService, - MailEventService mailEventService) - { + EventBus eventBus, + GeneralSystemSettingsService generalSystemSettingsService, + MailEventService mailEventService + ) { return new ReviewerSupportMailer(eventBus, mailEventService, generalSystemSettingsService); } // Not sure why this dependency lives in the view module @Bean public ReviewerAssignedNotifications reviewerAssignedNotifications( - EventBus eventBus, - NotificationController notificationController, - RoughDraftApprovalService roughDraftApprovalService, - FinalSeminarApprovalService finalSeminarApprovalService) - { - return new ReviewerAssignedNotifications(roughDraftApprovalService, - finalSeminarApprovalService, notificationController, eventBus); + EventBus eventBus, + NotificationController notificationController, + RoughDraftApprovalService roughDraftApprovalService, + FinalSeminarApprovalService finalSeminarApprovalService + ) { + return new ReviewerAssignedNotifications( + roughDraftApprovalService, + finalSeminarApprovalService, + notificationController, + eventBus + ); } // Not sure why this dependency lives in the view module @Bean public NotifyFailedReflection notifyFailedReflection( - EventBus eventBus, - NotificationController notificationController) - { + EventBus eventBus, + NotificationController notificationController + ) { return new NotifyFailedReflection(notificationController, eventBus); } } diff --git a/war/src/main/java/se/su/dsv/scipro/war/WorkerConfig.java b/war/src/main/java/se/su/dsv/scipro/war/WorkerConfig.java index 076bc219fc..4acdf186a7 100644 --- a/war/src/main/java/se/su/dsv/scipro/war/WorkerConfig.java +++ b/war/src/main/java/se/su/dsv/scipro/war/WorkerConfig.java @@ -3,6 +3,9 @@ package se.su.dsv.scipro.war; import com.google.common.eventbus.EventBus; import jakarta.inject.Provider; import jakarta.persistence.EntityManagerFactory; +import java.time.Clock; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -50,13 +53,10 @@ import se.su.dsv.scipro.workerthreads.ThesisUploadDeadlineWorker; import se.su.dsv.scipro.workerthreads.ThesisUploadReminderWorker; import se.su.dsv.scipro.workerthreads.WorkerTransactionManager; -import java.time.Clock; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; - @Configuration(proxyBeanMethods = false) @Import(WorkerConfig.Workers.class) public class WorkerConfig { + private static final int NUMBER_OF_WORKER_THREADS = 4; @Bean @@ -66,44 +66,60 @@ public class WorkerConfig { @Bean public SchedulerImpl scheduler( - ScheduledExecutorService scheduledExecutorService, - EntityManagerFactory entityManagerFactory) - { + ScheduledExecutorService scheduledExecutorService, + EntityManagerFactory entityManagerFactory + ) { return new SchedulerImpl(scheduledExecutorService, entityManagerFactory); } @Bean public TemporaryWorkerScheduler temporaryWorkerScheduler( - Scheduler scheduler, - Provider mailEventWorker, - Provider notificationCompilationWorker, - Provider ideaExportWorker, - Provider thesisUploadReminderWorker, - Provider thesisUploadDeadlineWorker, - Provider manualMatchRemindWorkerProvider, - Provider reviewerDecisionReminderWorker, - Provider plagiarismSubmitter, - Provider urkundPoller, - Provider removeFulfilledPartnerAds, - Provider gradeFinalSeminarParticipantReminderWorkerProvider) - { - return new TemporaryWorkerScheduler(scheduler, mailEventWorker, notificationCompilationWorker, ideaExportWorker, thesisUploadReminderWorker, thesisUploadDeadlineWorker, manualMatchRemindWorkerProvider, reviewerDecisionReminderWorker, plagiarismSubmitter, urkundPoller, removeFulfilledPartnerAds, gradeFinalSeminarParticipantReminderWorkerProvider); + Scheduler scheduler, + Provider mailEventWorker, + Provider notificationCompilationWorker, + Provider ideaExportWorker, + Provider thesisUploadReminderWorker, + Provider thesisUploadDeadlineWorker, + Provider manualMatchRemindWorkerProvider, + Provider reviewerDecisionReminderWorker, + Provider plagiarismSubmitter, + Provider urkundPoller, + Provider removeFulfilledPartnerAds, + Provider gradeFinalSeminarParticipantReminderWorkerProvider + ) { + return new TemporaryWorkerScheduler( + scheduler, + mailEventWorker, + notificationCompilationWorker, + ideaExportWorker, + thesisUploadReminderWorker, + thesisUploadDeadlineWorker, + manualMatchRemindWorkerProvider, + reviewerDecisionReminderWorker, + plagiarismSubmitter, + urkundPoller, + removeFulfilledPartnerAds, + gradeFinalSeminarParticipantReminderWorkerProvider + ); } @Bean public FirstMeetingReminderWorker.FirstMeetingReminderWorkerSchedule firstMeetingReminderWorkerScheduler( - Scheduler scheduler, - Provider firstMeetingReminderWorkerProvider) - { - return new FirstMeetingReminderWorker.FirstMeetingReminderWorkerSchedule(scheduler, firstMeetingReminderWorkerProvider); + Scheduler scheduler, + Provider firstMeetingReminderWorkerProvider + ) { + return new FirstMeetingReminderWorker.FirstMeetingReminderWorkerSchedule( + scheduler, + firstMeetingReminderWorkerProvider + ); } @Bean public PeerWorkerSchedules peerWorkerSchedules( - Scheduler scheduler, - Provider expiredRequestWorker, - Provider expiredReviewResetWorker) - { + Scheduler scheduler, + Provider expiredRequestWorker, + Provider expiredReviewResetWorker + ) { return new PeerWorkerSchedules(scheduler, expiredRequestWorker, expiredReviewResetWorker); } @@ -115,11 +131,11 @@ public class WorkerConfig { @Bean public PlagiarismSubmitter plagiarismSubmitter( - Provider urkundSettings, - PlagiarismRequestRepository plagiarismRequestRepository, - UrkundService urkundService, - FileService fileService) - { + Provider urkundSettings, + PlagiarismRequestRepository plagiarismRequestRepository, + UrkundService urkundService, + FileService fileService + ) { return new PlagiarismSubmitter(urkundSettings, plagiarismRequestRepository, urkundService, fileService); } @@ -136,12 +152,13 @@ public class WorkerConfig { @Configuration public static class Workers { + @Bean public MailEventWorker mailEventWorker( - MailEventService mailEventService, - GeneralSystemSettingsService generalSystemSettingsService, - Mailer mailer) - { + MailEventService mailEventService, + GeneralSystemSettingsService generalSystemSettingsService, + Mailer mailer + ) { return new MailEventWorker(mailEventService, generalSystemSettingsService, mailer); } @@ -152,15 +169,21 @@ public class WorkerConfig { @Bean public IdeaExportWorker ideaExportWorker( - IdeaService ideaService, - MailEventService mailEventService, - ProjectService projectService, - IdeaCreationJudge ideaCreationJudge, - EventBus eventBus, - FirstMeetingService firstMeetingService) - { - return new IdeaExportWorker(ideaService, mailEventService, projectService, ideaCreationJudge, eventBus, - firstMeetingService); + IdeaService ideaService, + MailEventService mailEventService, + ProjectService projectService, + IdeaCreationJudge ideaCreationJudge, + EventBus eventBus, + FirstMeetingService firstMeetingService + ) { + return new IdeaExportWorker( + ideaService, + mailEventService, + projectService, + ideaCreationJudge, + eventBus, + firstMeetingService + ); } @Bean @@ -175,61 +198,76 @@ public class WorkerConfig { @Bean public ManualMatchRemindWorker manualMatchRemindWorker( - ApplicationPeriodService applicationPeriodService, - MailEventService mailEventService, - GeneralSystemSettingsService generalSystemSettingsService, - IdeaService ideaService, - Clock clock) - { - return new ManualMatchRemindWorker(applicationPeriodService, mailEventService, generalSystemSettingsService, - ideaService, clock); + ApplicationPeriodService applicationPeriodService, + MailEventService mailEventService, + GeneralSystemSettingsService generalSystemSettingsService, + IdeaService ideaService, + Clock clock + ) { + return new ManualMatchRemindWorker( + applicationPeriodService, + mailEventService, + generalSystemSettingsService, + ideaService, + clock + ); } @Bean public ReviewerDecisionReminderWorker reviewerDecisionReminderWorker( - MyReviewService myReviewService, - DaysService daysService, - MailEventService mailEventService) - { + MyReviewService myReviewService, + DaysService daysService, + MailEventService mailEventService + ) { return new ReviewerDecisionReminderWorker(myReviewService, daysService, mailEventService); } @Bean public StatusPollingWorker statusPollingWorker( - UrkundSubmissionRepository urkundSubmissionRepository, - UrkundApi urkundApi, - Provider urkundSettingsProvider, - Sukat sukat) - { + UrkundSubmissionRepository urkundSubmissionRepository, + UrkundApi urkundApi, + Provider urkundSettingsProvider, + Sukat sukat + ) { return new StatusPollingWorker(urkundSubmissionRepository, urkundApi, urkundSettingsProvider, sukat); } @Bean public RemoveFulfilledPartnerAdsWorker removeFulfilledPartnerAdsWorker( - IdeaService ideaService, - ProjectPartnerRepository projectPartnerRepository) - { + IdeaService ideaService, + ProjectPartnerRepository projectPartnerRepository + ) { return new RemoveFulfilledPartnerAdsWorker(ideaService, projectPartnerRepository); } @Bean public GradeFinalSeminarParticipantReminderWorker gradeFinalSeminarParticipantReminderWorker( - MailEventService mailEventService, - GeneralSystemSettingsService generalSystemSettingsService, - FinalSeminarService finalSeminarService) - { - return new GradeFinalSeminarParticipantReminderWorker(finalSeminarService, mailEventService, generalSystemSettingsService); + MailEventService mailEventService, + GeneralSystemSettingsService generalSystemSettingsService, + FinalSeminarService finalSeminarService + ) { + return new GradeFinalSeminarParticipantReminderWorker( + finalSeminarService, + mailEventService, + generalSystemSettingsService + ); } @Bean public FirstMeetingReminderWorker firstMeetingReminderWorker( - IdeaService ideaService, - DaysService daysService, - MailEventService mailEventService, - GeneralSystemSettingsService generalSystemSettingsService, - Clock clock) - { - return new FirstMeetingReminderWorker(ideaService, daysService, mailEventService, generalSystemSettingsService, clock); + IdeaService ideaService, + DaysService daysService, + MailEventService mailEventService, + GeneralSystemSettingsService generalSystemSettingsService, + Clock clock + ) { + return new FirstMeetingReminderWorker( + ideaService, + daysService, + mailEventService, + generalSystemSettingsService, + clock + ); } @Bean diff --git a/war/src/main/java/se/su/dsv/scipro/workerthreads/SchedulerImpl.java b/war/src/main/java/se/su/dsv/scipro/workerthreads/SchedulerImpl.java index 0acb56920c..6422184dd1 100755 --- a/war/src/main/java/se/su/dsv/scipro/workerthreads/SchedulerImpl.java +++ b/war/src/main/java/se/su/dsv/scipro/workerthreads/SchedulerImpl.java @@ -1,7 +1,15 @@ package se.su.dsv.scipro.workerthreads; +import jakarta.inject.Inject; +import jakarta.inject.Provider; +import jakarta.inject.Singleton; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.jpa.EntityManagerFactoryUtils; @@ -9,16 +17,6 @@ import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import se.su.dsv.scipro.system.Lifecycle; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import jakarta.inject.Singleton; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ScheduledExecutorService; - @Singleton public class SchedulerImpl implements Lifecycle, Scheduler { @@ -45,7 +43,12 @@ public class SchedulerImpl implements Lifecycle, Scheduler { Task task = new Task(description, worker, schedule); Runnable runnable = tracked(task); tasks.add(task); - scheduledExecutorService.scheduleAtFixedRate(runnable, schedule.getDelay(), schedule.getPeriod(), schedule.getTimeUnit()); + scheduledExecutorService.scheduleAtFixedRate( + runnable, + schedule.getDelay(), + schedule.getPeriod(), + schedule.getTimeUnit() + ); } private Runnable tracked(final Task task) { @@ -61,16 +64,15 @@ public class SchedulerImpl implements Lifecycle, Scheduler { runningWorkers.add(task); task.execute(); - } - catch (Exception e) { + } catch (Exception e) { LOGGER.error("Worker task '{}' failed", task.getWorkerName(), e); - } - finally { + } finally { runningWorkers.remove(task); // Clean up the shared EntityManager - EntityManagerHolder emHolder = (EntityManagerHolder) - TransactionSynchronizationManager.unbindResource(emf); + EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource( + emf + ); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } }; @@ -82,8 +84,7 @@ public class SchedulerImpl implements Lifecycle, Scheduler { } @Override - public void start() { - } + public void start() {} @Override public void stop() { diff --git a/war/src/test/java/se/su/dsv/scipro/workerthreads/SchedulerImplTest.java b/war/src/test/java/se/su/dsv/scipro/workerthreads/SchedulerImplTest.java index f79a05cd26..b73fe65de5 100644 --- a/war/src/test/java/se/su/dsv/scipro/workerthreads/SchedulerImplTest.java +++ b/war/src/test/java/se/su/dsv/scipro/workerthreads/SchedulerImplTest.java @@ -1,7 +1,13 @@ package se.su.dsv.scipro.workerthreads; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; + import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Answers; @@ -10,24 +16,21 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) public class SchedulerImplTest { @Mock private ScheduledExecutorService scheduledExecutorService; + @Mock private Worker abstractWorker; + @Mock private Task task; + @Mock(answer = Answers.RETURNS_MOCKS) private EntityManagerFactory emf; + @InjectMocks private SchedulerImpl scheduler;