From eb829bfa26f78fb16795e2d8a7868259aba1faca Mon Sep 17 00:00:00 2001 From: _Bastler Date: Wed, 13 Apr 2022 16:38:23 +0200 Subject: [PATCH] upgrade spring, add javadoc, formatting --- .../main/java/de/bstly/we/Application.java | 6 +- .../businesslogic/BorrowItemManager.java | 79 ++--- .../businesslogic/BorrowRequestManager.java | 93 +++-- .../controller/BorrowItemController.java | 23 +- .../controller/BorrowRequestController.java | 49 ++- .../validation/BorrowItemValidator.java | 27 +- .../validation/BorrowJwtValidator.java | 3 +- .../validation/BorrowRequestValidator.java | 26 +- .../BorrowItemManualSlotRepository.java | 4 +- .../BorrowItemPeriodSlotRepository.java | 4 +- .../repository/BorrowItemRepository.java | 3 +- .../repository/BorrowRequestRepository.java | 10 +- core/pom.xml | 14 +- .../we/businesslogic/PermissionManager.java | 130 +++---- .../PermissionMappingManager.java | 53 ++- .../bstly/we/businesslogic/PretixManager.java | 125 +++---- .../bstly/we/businesslogic/QuotaManager.java | 77 ++--- .../we/businesslogic/QuotaMappingManager.java | 42 +-- .../java/de/bstly/we/businesslogic/Setup.java | 10 +- .../SystemProfileFieldManager.java | 6 +- .../businesslogic/SystemPropertyManager.java | 17 +- .../we/businesslogic/UserAliasManager.java | 6 +- .../we/businesslogic/UserDataManager.java | 57 +--- .../we/businesslogic/UserDomainManager.java | 9 +- .../bstly/we/businesslogic/UserManager.java | 73 ++-- .../UserProfileFieldManager.java | 37 +- .../we/businesslogic/UserTotpManager.java | 43 +-- .../businesslogic/VoucherMappingManager.java | 30 +- .../support/AbstractModelEventListener.java | 11 +- .../businesslogic/support/InstantHelper.java | 23 +- .../Authentication2FAController.java | 9 +- .../controller/AuthenticationController.java | 16 +- .../bstly/we/controller/ItemController.java | 9 +- .../we/controller/PermissionController.java | 3 +- .../PermissionManagementController.java | 9 +- .../PermissionMappingController.java | 30 +- .../we/controller/PretixApiController.java | 10 +- .../controller/QuotaManagementController.java | 6 +- .../we/controller/QuotaMappingController.java | 12 +- .../bstly/we/controller/SystemController.java | 3 +- .../SystemProfileFieldController.java | 6 +- .../we/controller/UserAliasController.java | 3 +- .../bstly/we/controller/UserController.java | 14 +- .../UserDataManagementController.java | 5 +- .../we/controller/UserDomainController.java | 8 +- .../UserDomainManagementController.java | 3 +- .../controller/UserManagementController.java | 17 +- .../UserProfileFieldController.java | 5 +- .../controller/VoucherMappingController.java | 11 +- .../model/SecondFactorProviderModel.java | 2 +- .../support/ControllerExceptionHandler.java | 2 +- .../EntityResponseStatusException.java | 6 +- .../JsonStringBodyControllerAdvice.java | 35 +- .../controller/support/RequestBodyErrors.java | 5 +- .../support/TokenSessionManager.java | 29 +- .../validation/PasswordModelValidator.java | 4 +- .../validation/UserAliasValidator.java | 2 +- .../validation/UserDomainValidator.java | 4 +- .../validation/UserModelValidator.java | 9 +- .../validation/UserProfileFieldValidator.java | 6 +- .../de/bstly/we/event/AbstractModelEvent.java | 2 +- .../de/bstly/we/model/PermissionMapping.java | 14 - .../de/bstly/we/model/SystemProperty.java | 2 +- .../de/bstly/we/model/UserProfileField.java | 3 +- .../we/repository/PermissionRepository.java | 3 +- .../SystemProfileFieldRepository.java | 4 +- .../we/repository/UserAliasRepository.java | 3 +- .../we/repository/UserDomainRepository.java | 3 +- .../UserProfileFieldRepository.java | 3 +- .../LocalAuthenticationEntryPoint.java | 6 +- .../security/LocalAuthenticationProvider.java | 35 +- .../we/security/LocalRememberMeServices.java | 9 +- .../security/LocalServletContextListener.java | 11 +- .../we/security/LocalUserDetailsService.java | 34 +- .../we/security/PasswordEncoderConfig.java | 25 ++ .../de/bstly/we/security/SecurityConfig.java | 111 +++--- .../businesslogic/SecondFactorProvider.java | 4 +- .../SecondFactorProviderManager.java | 7 +- .../SecondFactorRequestProvider.java | 3 +- .../FormSecondFactorAuthenticationFilter.java | 25 +- .../LocalAnonymousAuthenticationFilter.java | 13 +- .../filter/RestAuthenticationFilter.java | 13 +- .../RestSecondFactorAuthenticationFilter.java | 31 +- .../FormAuthenticationSuccessHandler.java | 50 +-- .../RestAuthenticationFailureHandler.java | 7 +- .../RestAuthenticationSuccessHandler.java | 20 +- .../we/security/model/LocalUserDetails.java | 6 +- .../LocalAnonymousAuthenticationToken.java | 5 +- .../LocalSecondFactorAuthenticationToken.java | 10 +- .../we/email/businesslogic/EmailManager.java | 18 +- .../we/email/controller/EmailController.java | 8 +- .../email/controller/model/UserMailModel.java | 2 +- .../we/i18n/businesslogic/I18nManager.java | 6 +- .../we/i18n/controller/I18nController.java | 8 +- .../we/i18n/repository/I18nRepository.java | 3 +- .../invite/businesslogic/InviteManager.java | 41 ++- .../businesslogic/InviteMappingManager.java | 27 +- .../invite/controller/InviteController.java | 75 ++-- .../controller/InviteManagingController.java | 11 +- .../controller/InviteMappingController.java | 6 +- .../invite/repository/InviteRepository.java | 3 +- jitsi/pom.xml | 1 + .../jitsi/businesslogic/JitsiRoomManager.java | 47 ++- .../support/UrlShortenerSync.java | 12 +- .../jitsi/controller/JitsiRoomController.java | 19 +- .../JitsiRoomManagementController.java | 8 +- .../validation/JitsiRoomValidator.java | 60 ++-- .../jitsi/repository/JitsiRoomRepository.java | 3 +- .../jukebox/controller/JukeboxController.java | 14 +- .../JukeboxManagementController.java | 8 +- jwt/pom.xml | 1 + .../we/jwt/businesslogic/JwtKeyManager.java | 27 +- .../we/jwt/businesslogic/JwtUserManager.java | 17 +- .../jwt/controller/JwtUserDataController.java | 29 +- .../we/jwt/repository/JwtKeyRepository.java | 3 +- .../businesslogic/MembershipManager.java | 320 +++++++----------- .../controller/MembershipController.java | 10 +- .../businesslogic/MinetestAccountManager.java | 20 +- .../controller/MinetestAccountController.java | 3 +- .../MinetestAccountManagementController.java | 17 +- .../validation/MinetestAccountValidator.java | 15 +- .../OidcAuthorizationCodeManager.java | 8 +- .../oidc/businesslogic/OidcClientManager.java | 47 ++- .../oidc/businesslogic/OidcTokenManager.java | 27 +- .../oidc/controller/OIDCClientController.java | 17 +- .../OidcAuthorizationController.java | 78 ++--- .../controller/OidcDiscoveryController.java | 8 +- .../oidc/controller/OidcTokenController.java | 59 ++-- .../controller/model/OidcClientModel.java | 6 +- .../we/oidc/model/OidcAuthorizationCode.java | 11 +- .../de/bstly/we/oidc/model/OidcClient.java | 6 +- .../we/oidc/model/OidcConfiguration.java | 6 +- .../we/oidc/model/OidcTokenErrorCode.java | 6 +- .../bstly/we/oidc/model/OidcTokenRequest.java | 14 +- .../api/controller/DebugController.java | 7 +- .../partey/api/controller/MapController.java | 6 +- .../api/controller/ReportController.java | 2 +- .../partey/api/controller/RoomController.java | 22 +- .../partey/api/controller/WokaController.java | 3 +- .../api/controller/support/DebugLogger.java | 20 +- .../controller/support/WokaListManager.java | 7 +- .../api/security/ParteyApiAuthentication.java | 3 +- .../businesslogic/ParteyMapManager.java | 8 +- .../ParteyUserReportManager.java | 16 +- .../ParteyUserReportModeratorManager.java | 12 +- .../businesslogic/ParteyUserTagManager.java | 28 +- .../ParteyUserTexturesManager.java | 12 +- .../controller/MapManagementController.java | 7 +- .../UserReportManagementController.java | 16 +- ...erReportModeratorManagementController.java | 8 +- .../UserTagManagementController.java | 20 +- .../bstly/we/partey/model/ParteyUserTag.java | 2 +- .../repository/ParteyMapRepository.java | 3 +- .../ParteyUserReportModeratorRepository.java | 3 +- .../repository/ParteyUserTagRepository.java | 4 +- .../ParteyUserTexturesRepository.java | 4 +- .../businesslogic/TimeslotManager.java | 37 +- .../controller/TimeslotController.java | 39 +-- .../TimeslotManagementController.java | 29 +- .../validation/TimeslotValidator.java | 43 +-- .../repository/TimeslotRepository.java | 3 +- pom.xml | 6 +- .../businesslogic/ServiceManager.java | 22 +- .../de/bstly/we/services/model/Service.java | 2 +- .../businesslogic/ShortenedUrlManager.java | 92 +++-- .../controller/ShortenedUrlController.java | 91 +++-- .../ShortenedUrlManagementController.java | 19 +- .../ShortenedUrlModelValidator.java | 8 +- 168 files changed, 1554 insertions(+), 2020 deletions(-) create mode 100644 core/src/main/java/de/bstly/we/security/PasswordEncoderConfig.java diff --git a/application/src/main/java/de/bstly/we/Application.java b/application/src/main/java/de/bstly/we/Application.java index 874019e..dfaf09e 100755 --- a/application/src/main/java/de/bstly/we/Application.java +++ b/application/src/main/java/de/bstly/we/Application.java @@ -20,7 +20,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application extends SpringBootServletInitializer { - + /** * The main method. * @@ -31,7 +31,9 @@ public class Application extends SpringBootServletInitializer { } /* - * @see org.springframework.boot.web.servlet.support.SpringBootServletInitializer#onStartup(javax.servlet.ServletContext) + * @see + * org.springframework.boot.web.servlet.support.SpringBootServletInitializer# + * onStartup(javax.servlet.ServletContext) */ @Override public void onStartup(ServletContext servletContext) throws ServletException { diff --git a/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowItemManager.java b/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowItemManager.java index 1e97a91..54454e2 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowItemManager.java +++ b/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowItemManager.java @@ -108,52 +108,49 @@ public class BorrowItemManager implements UserDataProvider { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending - * @param search the search + * @param search the search * @return the page */ - public Page get(int page, int size, String sortBy, boolean descending, - String search) { + public Page get(int page, int size, String sortBy, boolean descending, String search) { if (StringUtils.hasText(search)) { - return borrowItemRepository.findAll( - qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)), - PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() - : Sort.by(sortBy).ascending())); + return borrowItemRepository + .findAll(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)), PageRequest + .of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } - return borrowItemRepository.findAll(PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return borrowItemRepository.findAll( + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Gets the for user. * - * @param userId the user id - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending - * @param search the search + * @param search the search * @return the for user */ - public Page getForUser(Long userId, int page, int size, String sortBy, - boolean descending, String search) { + public Page getForUser(Long userId, int page, int size, String sortBy, boolean descending, + String search) { BooleanBuilder query = new BooleanBuilder(); query.and(qBorrowItem.owner.eq(userId)); if (StringUtils.hasText(search)) { - query.and( - qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search))); + query.and(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search))); } - return borrowItemRepository.findAll(query.getValue(), PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return borrowItemRepository.findAll(query.getValue(), + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** @@ -165,10 +162,10 @@ public class BorrowItemManager implements UserDataProvider { public BorrowItem save(BorrowItem borrowItem) { if (borrowItem.getId() != null && !borrowItem.getId().equals(0L)) { - borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository - .findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId()))); - borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository - .findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId()))); + borrowItemManualSlotRepository.deleteAll( + borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId()))); + borrowItemPeriodSlotRepository.deleteAll( + borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId()))); } List slots = borrowItem.getSlots(); @@ -216,12 +213,11 @@ public class BorrowItemManager implements UserDataProvider { * @param borrowItem the borrow item */ public void delete(BorrowItem borrowItem) { - borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository - .findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId()))); - borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository - .findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId()))); - borrowRequestRepository.deleteAll( - borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId()))); + borrowItemManualSlotRepository + .deleteAll(borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId()))); + borrowItemPeriodSlotRepository + .deleteAll(borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId()))); + borrowRequestRepository.deleteAll(borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId()))); borrowItemRepository.delete(borrowItem); } @@ -233,8 +229,7 @@ public class BorrowItemManager implements UserDataProvider { */ public void delete(Long id) { BorrowItem borrowItem = get(id); - Assert.notNull(borrowItem, "Invalid borrow item id: " - + id); + Assert.notNull(borrowItem, "Invalid borrow item id: " + id); delete(borrowItem); } @@ -244,12 +239,8 @@ public class BorrowItemManager implements UserDataProvider { * @param borrowItem the borrow item */ public void notifyOwner(BorrowItem borrowItem) { - Assert.isTrue( - borrowItem.getEmailNotification() != null - && borrowItem.getEmailNotification().booleanValue(), - "Email notification not enabled for '" - + borrowItem.getId() - + "'!"); + Assert.isTrue(borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue(), + "Email notification not enabled for '" + borrowItem.getId() + "'!"); String email = borrowItem.getEmail(); if (!StringUtils.hasText(email)) { @@ -276,8 +267,7 @@ public class BorrowItemManager implements UserDataProvider { public List getUserData(Long userId) { List result = Lists.newArrayList(); - Iterator items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)) - .iterator(); + Iterator items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator(); while (items.hasNext()) { result.add(items.next()); } @@ -290,8 +280,7 @@ public class BorrowItemManager implements UserDataProvider { */ @Override public void purgeUserData(Long userId) { - Iterator items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)) - .iterator(); + Iterator items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator(); while (items.hasNext()) { delete(items.next()); } diff --git a/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowRequestManager.java b/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowRequestManager.java index 6e6a8ab..1ca1da3 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowRequestManager.java +++ b/borrow/src/main/java/de/bstly/we/borrow/businesslogic/BorrowRequestManager.java @@ -68,69 +68,65 @@ public class BorrowRequestManager implements UserDataProvider { /** * Gets the for user. * - * @param userId the user id - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the for user */ - public Page getForUser(Long userId, int page, int size, String sortBy, - boolean descending) { - return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId), PageRequest.of(page, - size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + public Page getForUser(Long userId, int page, int size, String sortBy, boolean descending) { + return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId), + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Gets the for user and status. * - * @param userId the user id - * @param status the status - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param status the status + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the for user and status */ - public Page getForUserAndStatus(Long userId, BorrowRequestStatus status, - int page, int size, String sortBy, boolean descending) { - return borrowRequestRepository.findAll( - qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)), - PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + public Page getForUserAndStatus(Long userId, BorrowRequestStatus status, int page, int size, + String sortBy, boolean descending) { + return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)), + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Gets the for owner. * - * @param userId the user id - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the for owner */ - public Page getForOwner(Long userId, int page, int size, String sortBy, - boolean descending) { - return borrowRequestRepository.findAllByOwner(userId, PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + public Page getForOwner(Long userId, int page, int size, String sortBy, boolean descending) { + return borrowRequestRepository.findAllByOwner(userId, + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Gets the for owner and status. * - * @param userId the user id - * @param status the status - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param status the status + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the for owner and status */ - public Page getForOwnerAndStatus(Long userId, BorrowRequestStatus status, - int page, int size, String sortBy, boolean descending) { - return borrowRequestRepository.findAllByOwnerAndStatus(userId, status, PageRequest.of(page, - size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + public Page getForOwnerAndStatus(Long userId, BorrowRequestStatus status, int page, int size, + String sortBy, boolean descending) { + return borrowRequestRepository.findAllByOwnerAndStatus(userId, status, + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** @@ -165,7 +161,7 @@ public class BorrowRequestManager implements UserDataProvider { * Creates the code. * * @param borrowRequest the borrow request - * @param issuer the issuer + * @param issuer the issuer * @return the signed JWT * @throws JOSEException the JOSE exception */ @@ -207,8 +203,7 @@ public class BorrowRequestManager implements UserDataProvider { JwtKey jwtKey = jwtKeyManager.getLatest(JWT_BORROW_KEY_NAME, true); - JWSHeader.Builder headerBuilder = new JWSHeader.Builder( - jwtKeyManager.getJwsAlgorithm(jwtKey)); + JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey)); headerBuilder.keyID(jwtKey.getKeyID()); headerBuilder.type(JOSEObjectType.JWT); @@ -222,7 +217,7 @@ public class BorrowRequestManager implements UserDataProvider { * * @param jwt the jwt * @return true, if successful - * @throws JOSEException the JOSE exception + * @throws JOSEException the JOSE exception * @throws ParseException the parse exception */ public boolean verify(SignedJWT jwt) throws JOSEException, ParseException { @@ -233,9 +228,7 @@ public class BorrowRequestManager implements UserDataProvider { JwtKey jwtKey = jwtKeyManager.getByKeyID(jwt.getHeader().getKeyID()); if (jwtKey == null) { - throw new KeySourceException("No key found for given KeyID! (" - + jwt.getHeader().getKeyID() - + ")"); + throw new KeySourceException("No key found for given KeyID! (" + jwt.getHeader().getKeyID() + ")"); } if (jwt.getJWTClaimsSet() == null) { @@ -259,14 +252,13 @@ public class BorrowRequestManager implements UserDataProvider { @Override public List getUserData(Long userId) { List result = Lists.newArrayList(); - Iterator userRequests = borrowRequestRepository - .findAll(qBorrowRequest.user.eq(userId)).iterator(); + Iterator userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId)) + .iterator(); while (userRequests.hasNext()) { result.add(userRequests.next()); } - Iterator ownerRequests = borrowRequestRepository.findAllByOwner(userId) - .iterator(); + Iterator ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator(); while (ownerRequests.hasNext()) { result.add(ownerRequests.next()); } @@ -279,14 +271,13 @@ public class BorrowRequestManager implements UserDataProvider { */ @Override public void purgeUserData(Long userId) { - Iterator userRequests = borrowRequestRepository - .findAll(qBorrowRequest.user.eq(userId)).iterator(); + Iterator userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId)) + .iterator(); while (userRequests.hasNext()) { delete(userRequests.next()); } - Iterator ownerRequests = borrowRequestRepository.findAllByOwner(userId) - .iterator(); + Iterator ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator(); while (ownerRequests.hasNext()) { delete(ownerRequests.next()); } diff --git a/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowItemController.java b/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowItemController.java index dd3dc43..b3e7ab5 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowItemController.java +++ b/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowItemController.java @@ -46,19 +46,18 @@ public class BorrowItemController extends BaseController { /** * Gets the borrow items. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParameter the sort parameter - * @param descParameter the desc parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParameter the sort parameter + * @param descParameter the desc parameter * @param searchParameter the search parameter - * @param ownerParameter the owner parameter + * @param ownerParameter the owner parameter * @return the borrow items */ @PreAuthorize("isAuthenticated()") @GetMapping public Page getBorrowItems(@RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter, @RequestParam("search") Optional searchParameter, @RequestParam("owner") Optional ownerParameter) { @@ -71,17 +70,15 @@ public class BorrowItemController extends BaseController { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } borrowItems = borrowItemManager.getForUser(getCurrentUserId(), pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("id"), - descParameter.orElse(false), searchParameter.orElse(null)); + sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false), + searchParameter.orElse(null)); } else { - if (!permissionManager.hasPermission(getCurrentUserId(), - BorrowPermissions.BORROW_REQUESTS) + if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS) || !permissionManager.isFullUser(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } borrowItems = borrowItemManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), - sortParameter.orElse("id"), descParameter.orElse(false), - searchParameter.orElse(null)); + sortParameter.orElse("id"), descParameter.orElse(false), searchParameter.orElse(null)); } for (BorrowItem borrowItem : borrowItems.getContent()) { diff --git a/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowRequestController.java b/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowRequestController.java index f90aa46..8c8f7ae 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowRequestController.java +++ b/borrow/src/main/java/de/bstly/we/borrow/controller/BorrowRequestController.java @@ -66,19 +66,17 @@ public class BorrowRequestController extends BaseController { /** * Gets the borrow requests. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParameter the sort parameter - * @param descParameter the desc parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParameter the sort parameter + * @param descParameter the desc parameter * @param ownerParameter the owner parameter * @return the borrow requests */ @PreAuthorize("isAuthenticated()") @GetMapping - public Page getBorrowRequests( - @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + public Page getBorrowRequests(@RequestParam("page") Optional pageParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter, @RequestParam("owner") Optional ownerParameter) { @@ -89,18 +87,15 @@ public class BorrowRequestController extends BaseController { || !permissionManager.isFullUser(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(), - pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"), - descParameter.orElse(false)); + borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(), pageParameter.orElse(0), + sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); } else { - if (!permissionManager.hasPermission(getCurrentUserId(), - BorrowPermissions.BORROW_REQUESTS) + if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS) || !permissionManager.isFullUser(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(), - pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"), - descParameter.orElse(false)); + borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(), pageParameter.orElse(0), + sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); } for (BorrowRequest borrowRequest : borrowRequests.getContent()) { @@ -153,8 +148,7 @@ public class BorrowRequestController extends BaseController { } if (borrowRequest.getId() == null || borrowRequest.getId().equals(0L)) { - if (borrowItem.getEmailNotification() != null - && borrowItem.getEmailNotification().booleanValue()) { + if (borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue()) { borrowItemManager.notifyOwner(borrowItem); } } @@ -212,7 +206,7 @@ public class BorrowRequestController extends BaseController { /** * Gets the code. * - * @param id the id + * @param id the id * @param request the request * @return the code */ @@ -230,12 +224,9 @@ public class BorrowRequestController extends BaseController { String issuer = jwtBorrowIssuer; if (!StringUtils.hasText(issuer)) { - issuer = request.getScheme() - + "://" - + request.getServerName(); + issuer = request.getScheme() + "://" + request.getServerName(); if (request.getServerPort() != 443 && request.getServerPort() != 80) { - issuer += ":" - + request.getServerPort(); + issuer += ":" + request.getServerPort(); } } try { @@ -250,21 +241,19 @@ public class BorrowRequestController extends BaseController { * Verfiy. * * @param serialized the serialized - * @param request the request - * @param response the response + * @param request the request + * @param response the response * @return the object */ @PostMapping("verify") - public Object verfiy(@RequestBody String serialized, HttpServletRequest request, - HttpServletResponse response) { + public Object verfiy(@RequestBody String serialized, HttpServletRequest request, HttpServletResponse response) { try { SignedJWT signedJwt = SignedJWT.parse(serialized); Errors errors = new RequestBodyErrors(signedJwt); borrowJwtValidator.validate(signedJwt, errors); if (errors.hasErrors()) { if (errors.getGlobalErrors().isEmpty()) { - throw new EntityResponseStatusException(errors.getAllErrors(), - HttpStatus.PRECONDITION_FAILED); + throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.PRECONDITION_FAILED); } else { throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE); } diff --git a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowItemValidator.java b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowItemValidator.java index 5668d90..aa3a0a9 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowItemValidator.java +++ b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowItemValidator.java @@ -48,13 +48,11 @@ public class BorrowItemValidator implements Validator { errors.rejectValue("availability", "REQUIRED"); } - if (StringUtils.hasText(borrowItem.getUrl()) - && !urlValidator.isValid(borrowItem.getUrl())) { + if (StringUtils.hasText(borrowItem.getUrl()) && !urlValidator.isValid(borrowItem.getUrl())) { errors.rejectValue("url", "INVALID_URL"); } - if (StringUtils.hasText(borrowItem.getEmail()) - && !emailValidator.isValid(borrowItem.getEmail())) { + if (StringUtils.hasText(borrowItem.getEmail()) && !emailValidator.isValid(borrowItem.getEmail())) { errors.rejectValue("email", "INVALID_EMAIL"); } @@ -64,18 +62,15 @@ public class BorrowItemValidator implements Validator { errors.rejectValue("maxDuration", "INVALID"); } - if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null - && !borrowItem.getSlots().isEmpty()) { + if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null && !borrowItem.getSlots().isEmpty()) { for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) { switch (borrowItem.getAvailability()) { case MANUAL: if (borrowItemSlot instanceof BorrowItemManualSlot) { BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot; - if (borrowItemManualSlot.getStart() == null - || borrowItemManualSlot.getEnd() == null) { + if (borrowItemManualSlot.getStart() == null || borrowItemManualSlot.getEnd() == null) { errors.rejectValue("slots", "MISSING_DATES"); - } else if (borrowItemManualSlot.getStart() - .isAfter(borrowItemManualSlot.getEnd())) { + } else if (borrowItemManualSlot.getStart().isAfter(borrowItemManualSlot.getEnd())) { errors.rejectValue("slots", "INVALID_DATES"); } } @@ -83,18 +78,14 @@ public class BorrowItemValidator implements Validator { case PERIOD: if (borrowItemSlot instanceof BorrowItemPeriodSlot) { BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot; - if (borrowItemPeriodSlot.getStartDay() == null - || borrowItemPeriodSlot.getStartTime() == null + if (borrowItemPeriodSlot.getStartDay() == null || borrowItemPeriodSlot.getStartTime() == null || borrowItemPeriodSlot.getEndDay() == null || borrowItemPeriodSlot.getEndTime() == null) { errors.rejectValue("slots", "MISSING_DATES"); - } else if (borrowItemPeriodSlot.getStartDay() - .compareTo(borrowItemPeriodSlot.getEndDay()) > 0) { + } else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) > 0) { errors.rejectValue("slots", "INVALID_DAY"); - } else if (borrowItemPeriodSlot.getStartDay() - .compareTo(borrowItemPeriodSlot.getEndDay()) == 0 - && borrowItemPeriodSlot.getStartTime() - .isAfter(borrowItemPeriodSlot.getEndTime())) { + } else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) == 0 + && borrowItemPeriodSlot.getStartTime().isAfter(borrowItemPeriodSlot.getEndTime())) { errors.rejectValue("slots", "INVALID_TIME"); } } diff --git a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowJwtValidator.java b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowJwtValidator.java index c28edef..2772328 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowJwtValidator.java +++ b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowJwtValidator.java @@ -111,8 +111,7 @@ public class BorrowJwtValidator implements Validator { } try { - if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status")) - .equals(BorrowRequestStatus.ACCEPTED)) { + if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status")).equals(BorrowRequestStatus.ACCEPTED)) { errors.rejectValue("status", "INVALID"); } } catch (ParseException e) { diff --git a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowRequestValidator.java b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowRequestValidator.java index 9913a54..489a45c 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowRequestValidator.java +++ b/borrow/src/main/java/de/bstly/we/borrow/controller/validation/BorrowRequestValidator.java @@ -66,6 +66,13 @@ public class BorrowRequestValidator implements Validator { validateTime(borrowRequest, borrowItem, errors); } + /** + * Validate time. + * + * @param borrowRequest the borrow request + * @param borrowItem the borrow item + * @param errors the errors + */ public void validateTime(BorrowRequest borrowRequest, BorrowItem borrowItem, Errors errors) { if (borrowRequest.getStarts() == null) { errors.rejectValue("starts", "REQUIRED"); @@ -77,16 +84,14 @@ public class BorrowRequestValidator implements Validator { return; } - borrowRequest - .setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS)); + borrowRequest.setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS)); borrowRequest.setEnds(InstantHelper.truncate(borrowRequest.getEnds(), ChronoUnit.SECONDS)); // expiry + start if (borrowRequest.getStarts().isAfter(borrowRequest.getEnds()) || borrowRequestRepository.exists(qBorrowRequest.item.eq(borrowRequest.getItem()) // exlude self - .and(qBorrowRequest.id - .ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId())) + .and(qBorrowRequest.id.ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId())) // accepted .and(qBorrowRequest.status.eq(BorrowRequestStatus.ACCEPTED)) // expires after start @@ -96,8 +101,8 @@ public class BorrowRequestValidator implements Validator { errors.rejectValue("starts", "ALREADY_USED"); errors.rejectValue("ends", "ALREADY_USED"); } else { - if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration().compareTo( - Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) { + if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration() + .compareTo(Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) { errors.rejectValue("starts", "TOO_SHORT"); errors.rejectValue("ends", "TOO_SHORT"); } else if (borrowItem.getMaxDuration() != null @@ -119,12 +124,10 @@ public class BorrowRequestValidator implements Validator { for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) { if (borrowItemSlot instanceof BorrowItemManualSlot) { BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot; - if (borrowRequest.getStarts() - .compareTo(borrowItemManualSlot.getStart()) >= 0) { + if (borrowRequest.getStarts().compareTo(borrowItemManualSlot.getStart()) >= 0) { validStart = true; } - if (borrowRequest.getEnds() - .compareTo(borrowItemManualSlot.getEnd()) <= 0) { + if (borrowRequest.getEnds().compareTo(borrowItemManualSlot.getEnd()) <= 0) { validEnd = true; } if (validStart && validEnd) { @@ -140,8 +143,7 @@ public class BorrowRequestValidator implements Validator { BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot; if (borrowRequest.getStarts().atZone(ZoneOffset.UTC).getDayOfWeek() .compareTo(borrowItemPeriodSlot.getStartDay()) >= 0 - && LocalTime - .ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC) + && LocalTime.ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC) .compareTo(borrowItemPeriodSlot.getStartTime()) >= 0) { validStart = true; } diff --git a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemManualSlotRepository.java b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemManualSlotRepository.java index 3480784..b0567d6 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemManualSlotRepository.java +++ b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemManualSlotRepository.java @@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemManualSlot; * The Interface BorrowItemManualSlotRepository. */ @Repository -public interface BorrowItemManualSlotRepository extends JpaRepository, - QuerydslPredicateExecutor { +public interface BorrowItemManualSlotRepository + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemPeriodSlotRepository.java b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemPeriodSlotRepository.java index 8498452..a7906be 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemPeriodSlotRepository.java +++ b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemPeriodSlotRepository.java @@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemPeriodSlot; * The Interface BorrowItemPeriodSlotRepository. */ @Repository -public interface BorrowItemPeriodSlotRepository extends JpaRepository, - QuerydslPredicateExecutor { +public interface BorrowItemPeriodSlotRepository + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemRepository.java b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemRepository.java index f195d8b..0c20bdd 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemRepository.java +++ b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowItemRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.borrow.model.BorrowItem; * The Interface BorrowItemRepository. */ @Repository -public interface BorrowItemRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface BorrowItemRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowRequestRepository.java b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowRequestRepository.java index e45352c..e76ba27 100644 --- a/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowRequestRepository.java +++ b/borrow/src/main/java/de/bstly/we/borrow/repository/BorrowRequestRepository.java @@ -33,7 +33,7 @@ public interface BorrowRequestRepository /** * Find all by owner. * - * @param owner the owner + * @param owner the owner * @param pageable the pageable * @return the page */ @@ -43,13 +43,13 @@ public interface BorrowRequestRepository /** * Find all by owner and status. * - * @param owner the owner - * @param status the status + * @param owner the owner + * @param status the status * @param pageable the pageable * @return the page */ @Query("SELECT request FROM BorrowRequest request INNER JOIN BorrowItem as item ON request.item = item.id WHERE item.owner = :owner AND request.status = :status") - Page findAllByOwnerAndStatus(@Param("owner") Long owner, - @Param("status") BorrowRequestStatus status, Pageable pageable); + Page findAllByOwnerAndStatus(@Param("owner") Long owner, @Param("status") BorrowRequestStatus status, + Pageable pageable); } diff --git a/core/pom.xml b/core/pom.xml index 2da7163..59df752 100755 --- a/core/pom.xml +++ b/core/pom.xml @@ -7,7 +7,7 @@ webstly-main ${revision} - + core webstly-core @@ -56,6 +56,12 @@ 1.7 + + com.google.guava + guava + 31.1-jre + + com.google.code.gson gson @@ -64,7 +70,7 @@ org.passay passay - 1.6.0 + 1.6.1 @@ -76,7 +82,7 @@ org.bouncycastle bcprov-jdk15on - 1.66 + 1.70 @@ -87,7 +93,7 @@ javax.measure unit-api - 2.1.2 + 2.1.3 diff --git a/core/src/main/java/de/bstly/we/businesslogic/PermissionManager.java b/core/src/main/java/de/bstly/we/businesslogic/PermissionManager.java index 2b21309..341ab5e 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/PermissionManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/PermissionManager.java @@ -42,13 +42,13 @@ public class PermissionManager implements UserDataProvider { * Gets the. * * @param target the target - * @param name the name + * @param name the name * @return the list */ public List get(Long target, String name) { if (target != null && StringUtils.hasText(name)) { - return Lists.newArrayList(permissionRepository - .findAll(qPermission.target.eq(target).and(qPermission.name.eq(name)))); + return Lists.newArrayList( + permissionRepository.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name)))); } return Lists.newArrayList(); } @@ -57,15 +57,14 @@ public class PermissionManager implements UserDataProvider { * Gets the not expires. * * @param target the target - * @param name the name + * @param name the name * @return the not expires */ public List getNotExpires(Long target, String name) { if (target != null && StringUtils.hasText(name)) { - return Lists.newArrayList(permissionRepository - .findAll(qPermission.target.eq(target).and(qPermission.name.eq(name)) - .and(qPermission.expires.after(Instant.now()).and(qPermission.starts - .isNull().or(qPermission.starts.before(Instant.now())))))); + return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target) + .and(qPermission.name.eq(name)).and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))))); } return Lists.newArrayList(); } @@ -91,9 +90,9 @@ public class PermissionManager implements UserDataProvider { */ public List getNotExpiresByTarget(Long target) { if (target != null) { - return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target) - .and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull() - .or(qPermission.starts.before(Instant.now())))))); + return Lists.newArrayList(permissionRepository + .findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))))); } return Lists.newArrayList(); } @@ -106,9 +105,9 @@ public class PermissionManager implements UserDataProvider { */ public List getNotExpiresByName(String name) { if (name != null) { - return Lists.newArrayList(permissionRepository.findAll(qPermission.name.eq(name) - .and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull() - .or(qPermission.starts.before(Instant.now())))))); + return Lists.newArrayList( + permissionRepository.findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))))); } return Lists.newArrayList(); } @@ -121,8 +120,8 @@ public class PermissionManager implements UserDataProvider { */ public List getNotExpiresByTargetIgnoreStart(Long target) { if (target != null) { - return Lists.newArrayList(permissionRepository.findAll( - qPermission.target.eq(target).and(qPermission.expires.after(Instant.now())))); + return Lists.newArrayList(permissionRepository + .findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now())))); } return Lists.newArrayList(); } @@ -134,16 +133,16 @@ public class PermissionManager implements UserDataProvider { * @return true, if is full user */ public boolean isFullUser(Long target) { - return permissionRepository.exists(qPermission.target.eq(target) - .and(qPermission.addon.isFalse()).and(qPermission.expires.after(Instant.now()).and( - qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))); + return permissionRepository.exists(qPermission.target.eq(target).and(qPermission.addon.isFalse()) + .and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))); } /** * Checks for permission. * * @param target the target - * @param name the name + * @param name the name * @return true, if successful */ public boolean hasPermission(Long target, String name) { @@ -152,23 +151,21 @@ public class PermissionManager implements UserDataProvider { } return target != null && permissionRepository.exists(qPermission.name.eq(name) - .and(qPermission.target.eq(target)) - .and(qPermission.expires.after(Instant.now()).and( - qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))); + .and(qPermission.target.eq(target)).and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))); } /** * Creates the. * - * @param target the target - * @param name the name - * @param addon the addon - * @param starts the starts + * @param target the target + * @param name the name + * @param addon the addon + * @param starts the starts * @param expires the expires * @return the permission */ - public Permission create(Long target, String name, boolean addon, Instant starts, - Instant expires) { + public Permission create(Long target, String name, boolean addon, Instant starts, Instant expires) { Permission newPermission = new Permission(); newPermission.setTarget(target); newPermission.setName(name); @@ -186,11 +183,8 @@ public class PermissionManager implements UserDataProvider { * @return the permission */ public Permission update(Permission permission) { - Assert.isTrue(permissionRepository.existsById(permission.getId()), "Permission '" - + permission.getName() - + "' for target + '" - + permission.getTarget() - + "' not exists!"); + Assert.isTrue(permissionRepository.existsById(permission.getId()), + "Permission '" + permission.getName() + "' for target + '" + permission.getTarget() + "' not exists!"); Permission updatePermission = permissionRepository.getById(permission.getId()); updatePermission.setStarts(permission.getStarts()); updatePermission.setExpires(permission.getExpires()); @@ -201,7 +195,7 @@ public class PermissionManager implements UserDataProvider { /** * Clone. * - * @param name the name + * @param name the name * @param clone the clone * @return the list */ @@ -210,11 +204,11 @@ public class PermissionManager implements UserDataProvider { for (Permission permission : permissionRepository .findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now())))) { - if (!permissionRepository.exists( - qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget())) + if (!permissionRepository + .exists(qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget())) .and(qPermission.expires.goe(permission.getExpires())))) { - permissions.add(create(permission.getTarget(), clone, permission.isAddon(), - permission.getStarts(), permission.getExpires())); + permissions.add(create(permission.getTarget(), clone, permission.isAddon(), permission.getStarts(), + permission.getExpires())); } } @@ -225,7 +219,7 @@ public class PermissionManager implements UserDataProvider { * Delete. * * @param target the target - * @param name the name + * @param name the name */ public void delete(Long target, String name) { for (Permission permission : get(target, name)) { @@ -254,14 +248,13 @@ public class PermissionManager implements UserDataProvider { /** * Apply item. * - * @param target the target - * @param item the item + * @param target the target + * @param item the item * @param answers the answers - * @param starts the starts + * @param starts the starts * @param expires the expires */ - public void applyItem(Long target, Integer item, JsonArray answers, Instant starts, - Instant expires) { + public void applyItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) { for (Permission permission : getForItem(target, item, answers, starts, expires)) { permissionRepository.save(permission); } @@ -270,15 +263,14 @@ public class PermissionManager implements UserDataProvider { /** * Gets the for item. * - * @param target the target - * @param item the item + * @param target the target + * @param item the item * @param answers the answers - * @param starts the starts + * @param starts the starts * @param expires the expires * @return the for item */ - public List getForItem(Long target, Integer item, JsonArray answers, Instant starts, - Instant expires) { + public List getForItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) { List permissions = Lists.newArrayList(); for (PermissionMapping permissionMapping : permissionMappingManager.getAllByItem(item)) { for (String name : permissionMapping.getNames()) { @@ -294,51 +286,42 @@ public class PermissionManager implements UserDataProvider { } if (permissionMapping.isLifetimeRound()) { - permissionStarts = InstantHelper.truncate(permissionStarts, - permissionMapping.getLifetimeUnit()); + permissionStarts = InstantHelper.truncate(permissionStarts, permissionMapping.getLifetimeUnit()); } if (permissionsExpires == null) { - permissionsExpires = InstantHelper.plus( - permissionStarts == null ? Instant.now() : permissionStarts, + permissionsExpires = InstantHelper.plus(permissionStarts == null ? Instant.now() : permissionStarts, permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()); } boolean additional = permissionMapping.isAddon(); for (JsonElement anwser : answers) { - if (anwser.isJsonObject() - && anwser.getAsJsonObject().has("question_identifier")) { + if (anwser.isJsonObject() && anwser.getAsJsonObject().has("question_identifier")) { if (StringUtils.hasText(permissionMapping.getStartsQuestion()) && permissionMapping.getStartsQuestion() - .equals(anwser.getAsJsonObject().get("question_identifier") - .getAsString()) + .equals(anwser.getAsJsonObject().get("question_identifier").getAsString()) && anwser.getAsJsonObject().has("answer")) { - String dateTimeString = anwser.getAsJsonObject().get("answer") - .getAsString(); + String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString(); if (StringUtils.hasText(dateTimeString)) { dateTimeString = dateTimeString.replace(" ", "T"); permissionStarts = OffsetDateTime.parse(dateTimeString).toInstant(); permissionsExpires = InstantHelper.plus(permissionStarts, - permissionMapping.getLifetime(), - permissionMapping.getLifetimeUnit()); + permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()); additional = false; } } if (StringUtils.hasText(permissionMapping.getExpiresQuestion()) && permissionMapping.getExpiresQuestion() - .equals(anwser.getAsJsonObject().get("question_identifier") - .getAsString()) + .equals(anwser.getAsJsonObject().get("question_identifier").getAsString()) && anwser.getAsJsonObject().has("answer")) { - String dateTimeString = anwser.getAsJsonObject().get("answer") - .getAsString(); + String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString(); if (StringUtils.hasText(dateTimeString)) { dateTimeString = dateTimeString.replace(" ", "T"); permissionsExpires = InstantHelper.plus( OffsetDateTime.parse(dateTimeString).toInstant(), - permissionMapping.getLifetime(), - permissionMapping.getLifetimeUnit()); + permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()); additional = false; } } @@ -372,18 +355,17 @@ public class PermissionManager implements UserDataProvider { permission.setStarts(permissionStarts); permission.setExpires(permissionsExpires); } else { - if (permission.getStarts() != null - && permission.getStarts().isBefore(Instant.now())) { + if (permission.getStarts() != null && permission.getStarts().isBefore(Instant.now())) { permission.setStarts(null); } - permission.setExpires(InstantHelper.plus(permission.getExpires(), - permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit())); + permission.setExpires(InstantHelper.plus(permission.getExpires(), permissionMapping.getLifetime(), + permissionMapping.getLifetimeUnit())); } if (permissionMapping.isLifetimeRound()) { - permission.setExpires(InstantHelper.truncate(permission.getExpires(), - permissionMapping.getLifetimeUnit())); + permission.setExpires( + InstantHelper.truncate(permission.getExpires(), permissionMapping.getLifetimeUnit())); } permissions.add(permission); diff --git a/core/src/main/java/de/bstly/we/businesslogic/PermissionMappingManager.java b/core/src/main/java/de/bstly/we/businesslogic/PermissionMappingManager.java index 4a4aac3..93f4555 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/PermissionMappingManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/PermissionMappingManager.java @@ -38,8 +38,7 @@ public class PermissionMappingManager { * @return the all by item */ public List getAllByItem(Integer item) { - return Lists.newArrayList( - permissionMappingRepository.findAll(qPermissionMapping.item.eq(item))); + return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.item.eq(item))); } /** @@ -49,8 +48,7 @@ public class PermissionMappingManager { * @return the all by name */ public List getAllByName(String name) { - return Lists.newArrayList( - permissionMappingRepository.findAll(qPermissionMapping.names.contains(name))); + return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.names.contains(name))); } /** @@ -71,35 +69,32 @@ public class PermissionMappingManager { * @return true, if successful */ public boolean exists(Integer item, String name) { - return permissionMappingRepository.exists( - qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name))); + return permissionMappingRepository + .exists(qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name))); } /** * Creates the. * - * @param item the item - * @param names the names - * @param lifetime the lifetime - * @param lifetimeUnit the lifetime unit - * @param lifetimeRound the lifetime round - * @param addon the addon - * @param product the product - * @param starts the starts - * @param expires the expires - * @param startsQuestion the starts question + * @param item the item + * @param names the names + * @param lifetime the lifetime + * @param lifetimeUnit the lifetime unit + * @param lifetimeRound the lifetime round + * @param addon the addon + * @param product the product + * @param starts the starts + * @param expires the expires + * @param startsQuestion the starts question * @param expiresQuestion the expires question * @return the permission mapping */ - public PermissionMapping create(Integer item, Set names, Long lifetime, - ChronoUnit lifetimeUnit, boolean lifetimeRound, boolean addon, String product, - Instant starts, Instant expires, String startsQuestion, String expiresQuestion) { + public PermissionMapping create(Integer item, Set names, Long lifetime, ChronoUnit lifetimeUnit, + boolean lifetimeRound, boolean addon, String product, Instant starts, Instant expires, + String startsQuestion, String expiresQuestion) { for (String name : names) { - Assert.isTrue(!exists(item, name), "PermissionMapping for item '" - + item - + "' with permission '" - + name - + "' already exists!"); + Assert.isTrue(!exists(item, name), + "PermissionMapping for item '" + item + "' with permission '" + name + "' already exists!"); } PermissionMapping permissionMapping = new PermissionMapping(); permissionMapping.setItem(item); @@ -132,9 +127,7 @@ public class PermissionMappingManager { * @param id the id */ public void delete(Long id) { - Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '" - + id - + "' does not exists!"); + Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '" + id + "' does not exists!"); PermissionMapping permissionMapping = permissionMappingRepository.findById(id).get(); permissionMappingRepository.delete(permissionMapping); } @@ -142,9 +135,9 @@ public class PermissionMappingManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/PretixManager.java b/core/src/main/java/de/bstly/we/businesslogic/PretixManager.java index 631ca5b..a5368b6 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/PretixManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/PretixManager.java @@ -91,9 +91,9 @@ public class PretixManager implements SmartInitializingSingleton { private int quotaAddons; protected WebClient webClient; - /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() + * @see org.springframework.beans.factory.SmartInitializingSingleton# + * afterSingletonsInstantiated() */ @Override public void afterSingletonsInstantiated() { @@ -119,21 +119,21 @@ public class PretixManager implements SmartInitializingSingleton { environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_CHECKINLIST, "")); } if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS)) { - systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, environment - .getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0")); + systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, + environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0")); } if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS)) { - systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, environment - .getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0")); + systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, + environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0")); } if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM)) { - systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, environment - .getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0")); + systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, + environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0")); } if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM)) { - systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, environment - .getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0")); + systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, + environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0")); } buildWebClient(); @@ -148,11 +148,9 @@ public class PretixManager implements SmartInitializingSingleton { organizer = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_ORGANIZER); event = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_EVENT); checkinlist = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_CHECKINLIST); - quotaRegistration = systemPropertyManager - .getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS); + quotaRegistration = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS); quotaAddons = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS); - webClient = WebClient.builder().baseUrl(host) - .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json") + webClient = WebClient.builder().baseUrl(host).defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json") .defaultHeader(HttpHeaders.AUTHORIZATION, "Token " + token).build(); } @@ -199,10 +197,8 @@ public class PretixManager implements SmartInitializingSingleton { public JsonObject getCheckInItemBySecret(String secret) { MultiValueMap queryParams = new LinkedMultiValueMap(); queryParams.add("secret", secret); - JsonObject orderPositions = request( - String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/", - organizer, event, checkinlist), - HttpMethod.GET, queryParams).getAsJsonObject(); + JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/", + organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject(); JsonArray results = orderPositions.getAsJsonArray("results"); if (results.size() == 1) { @@ -219,8 +215,7 @@ public class PretixManager implements SmartInitializingSingleton { * @return the order */ public JsonObject getOrder(String code) { - return request( - String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code), + return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code), HttpMethod.GET).getAsJsonObject(); } @@ -235,15 +230,14 @@ public class PretixManager implements SmartInitializingSingleton { queryParams.add("secret", secret); JsonObject orderPositions = request( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), - HttpMethod.GET, queryParams).getAsJsonObject(); + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET, + queryParams).getAsJsonObject(); JsonArray results = orderPositions.getAsJsonArray("results"); if (results.size() == 1) { JsonObject orderPosition = results.get(0).getAsJsonObject(); - return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, - event, orderPosition.get("order").getAsString()), HttpMethod.GET) - .getAsJsonObject(); + return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, + orderPosition.get("order").getAsString()), HttpMethod.GET).getAsJsonObject(); } return null; @@ -256,20 +250,20 @@ public class PretixManager implements SmartInitializingSingleton { * @return the json object */ public JsonObject createOrder(JsonObject order) { - return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event), - HttpMethod.POST, order).getAsJsonObject(); + return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event), HttpMethod.POST, + order).getAsJsonObject(); } /** * Extend order. * - * @param code the code + * @param code the code * @param expire the expire * @return the json object */ public JsonObject extendOrder(String code, JsonObject expire) { - return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer, - event, code), HttpMethod.POST, expire).getAsJsonObject(); + return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer, event, code), + HttpMethod.POST, expire).getAsJsonObject(); } /** @@ -278,8 +272,8 @@ public class PretixManager implements SmartInitializingSingleton { * @param code the code */ public void sendEmail(String code) { - request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer, - event, code), HttpMethod.POST); + request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer, event, code), + HttpMethod.POST); } /** @@ -293,8 +287,8 @@ public class PretixManager implements SmartInitializingSingleton { queryParams.add("secret", secret); JsonObject orderPositions = request( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), - HttpMethod.GET, queryParams).getAsJsonObject(); + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET, + queryParams).getAsJsonObject(); JsonArray results = orderPositions.getAsJsonArray("results"); if (results.size() == 1) { @@ -313,8 +307,7 @@ public class PretixManager implements SmartInitializingSingleton { */ public Instant getLastPaymentDateForOrder(String order) { JsonArray paymentResults = request( - String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer, - event, order), + String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer, event, order), HttpMethod.GET).getAsJsonObject().getAsJsonArray("results"); Instant lastDate = null; @@ -343,10 +336,8 @@ public class PretixManager implements SmartInitializingSingleton { public JsonObject getCheckInItemByItem(Integer item) { MultiValueMap queryParams = new LinkedMultiValueMap(); queryParams.add("item", String.valueOf(item)); - JsonObject orderPositions = request( - String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/", - organizer, event, checkinlist), - HttpMethod.GET, queryParams).getAsJsonObject(); + JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/", + organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject(); JsonArray results = orderPositions.getAsJsonArray("results"); if (results.size() == 1) { @@ -377,10 +368,8 @@ public class PretixManager implements SmartInitializingSingleton { * @return the check in positions */ public JsonObject getCheckInPositions(String idOrSecret) { - return request( - String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/", - organizer, event, checkinlist, idOrSecret), - HttpMethod.GET).getAsJsonObject(); + return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/", organizer, event, + checkinlist, idOrSecret), HttpMethod.GET).getAsJsonObject(); } /** @@ -390,8 +379,7 @@ public class PretixManager implements SmartInitializingSingleton { * @return the json object */ public JsonObject redeem(String idOrSecret) { - return request(String.format( - "/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer, + return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer, event, checkinlist, idOrSecret), HttpMethod.POST).getAsJsonObject(); } @@ -424,8 +412,8 @@ public class PretixManager implements SmartInitializingSingleton { voucher.addProperty("max_usages", 1); voucher.addProperty("quota", quotaId); voucher.addProperty("block_quota", true); - return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event), - HttpMethod.POST, voucher).getAsJsonObject(); + return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event), HttpMethod.POST, + voucher).getAsJsonObject(); } /** @@ -435,8 +423,7 @@ public class PretixManager implements SmartInitializingSingleton { * @return the item */ public JsonObject getItem(Integer item) { - return request( - String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item), + return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item), HttpMethod.GET).getAsJsonObject(); } @@ -447,32 +434,31 @@ public class PretixManager implements SmartInitializingSingleton { * @return the variations */ public JsonArray getVariations(Integer item) { - return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/", - organizer, event, item), HttpMethod.GET).getAsJsonObject() - .getAsJsonArray("results"); + return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/", organizer, event, item), + HttpMethod.GET).getAsJsonObject().getAsJsonArray("results"); } /** * Update variation. * - * @param item the item + * @param item the item * @param variationId the variation id - * @param variation the variation + * @param variation the variation */ public void updateVariation(Integer item, Integer variationId, JsonObject variation) { - request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, - event, item, variationId), HttpMethod.PATCH, variation); + request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item, + variationId), HttpMethod.PATCH, variation); } /** * Delete variation. * - * @param item the item + * @param item the item * @param variation the variation */ public void deleteVariation(Integer item, Integer variation) { - request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, - event, item, variation), HttpMethod.DELETE); + request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item, + variation), HttpMethod.DELETE); } /** @@ -490,7 +476,7 @@ public class PretixManager implements SmartInitializingSingleton { /** * Request. * - * @param path the path + * @param path the path * @param method the method * @return the json element */ @@ -501,21 +487,20 @@ public class PretixManager implements SmartInitializingSingleton { /** * Request. * - * @param path the path - * @param method the method + * @param path the path + * @param method the method * @param queryParameters the query parameters * @return the json element */ - public JsonElement request(String path, HttpMethod method, - MultiValueMap queryParameters) { + public JsonElement request(String path, HttpMethod method, MultiValueMap queryParameters) { return request(path, method, null, queryParameters); } /** * Request. * - * @param path the path - * @param method the method + * @param path the path + * @param method the method * @param payload the payload * @return the json element */ @@ -526,9 +511,9 @@ public class PretixManager implements SmartInitializingSingleton { /** * Request. * - * @param path the path - * @param method the method - * @param payload the payload + * @param path the path + * @param method the method + * @param payload the payload * @param queryParameters the query parameters * @return the json element */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/QuotaManager.java b/core/src/main/java/de/bstly/we/businesslogic/QuotaManager.java index 249d451..68d3f43 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/QuotaManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/QuotaManager.java @@ -33,13 +33,12 @@ public class QuotaManager implements UserDataProvider { * Gets the. * * @param target the target - * @param name the name + * @param name the name * @return the quota */ public Quota get(Long target, String name) { if (target != null && name != null) { - return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))) - .orElse(null); + return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))).orElse(null); } return null; } @@ -75,8 +74,7 @@ public class QuotaManager implements UserDataProvider { */ public List getNotExpiresByTarget(Long target) { if (target != null) { - return Lists.newArrayList( - quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0)))); + return Lists.newArrayList(quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0)))); } return Lists.newArrayList(); } @@ -85,21 +83,21 @@ public class QuotaManager implements UserDataProvider { * Checks for quota. * * @param target the target - * @param name the name + * @param name the name * @return true, if successful */ public boolean hasQuota(Long target, String name) { - return target != null && quotaRepository - .exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0))); + return target != null + && quotaRepository.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0))); } /** * Creates the. * - * @param target the target - * @param name the name - * @param value the value - * @param unit the unit + * @param target the target + * @param name the name + * @param value the value + * @param unit the unit * @param disposable the disposable * @return the quota */ @@ -121,17 +119,10 @@ public class QuotaManager implements UserDataProvider { * @return the quota */ public Quota update(Quota quota) { - Assert.isTrue( - quotaRepository.exists( - qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))), - "Quota '" - + quota.getName() - + "' for target + '" - + quota.getTarget() - + "' not exists!"); + Assert.isTrue(quotaRepository.exists(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))), + "Quota '" + quota.getName() + "' for target + '" + quota.getTarget() + "' not exists!"); Quota updateQuota = quotaRepository - .findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))) - .get(); + .findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))).get(); updateQuota.setValue(quota.getValue()); updateQuota.setUnit(quota.getUnit()); updateQuota.setDisposable(quota.isDisposable()); @@ -141,7 +132,7 @@ public class QuotaManager implements UserDataProvider { /** * Clone. * - * @param name the name + * @param name the name * @param clone the clone * @param value the value * @return the list @@ -150,10 +141,9 @@ public class QuotaManager implements UserDataProvider { List quotas = Lists.newArrayList(); for (Quota quota : quotaRepository.findAll(qQuota.name.eq(name))) { - if (!quotaRepository - .exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) { - quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), - quota.getUnit(), quota.isDisposable())); + if (!quotaRepository.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) { + quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), quota.getUnit(), + quota.isDisposable())); } } @@ -164,17 +154,12 @@ public class QuotaManager implements UserDataProvider { * Delete. * * @param target the target - * @param name the name + * @param name the name */ public void delete(Long target, String name) { Assert.isTrue(quotaRepository.exists(qQuota.target.eq(target).and(qQuota.name.eq(name))), - "Quota '" - + name - + "' for target + '" - + target - + "' not exists!"); - Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name))) - .get(); + "Quota '" + name + "' for target + '" + target + "' not exists!"); + Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name))).get(); quotaRepository.delete(delete); } @@ -200,7 +185,7 @@ public class QuotaManager implements UserDataProvider { * Adds the for item. * * @param target the target - * @param item the item + * @param item the item * @param quotas the quotas */ public void addForItem(Long target, Integer item, List quotas) { @@ -208,9 +193,8 @@ public class QuotaManager implements UserDataProvider { boolean added = false; for (Quota quota : quotas) { if (quota.getName().equals(quotaMapping.getName())) { - quota.setValue( - quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() - : quotaMapping.getValue()); + quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() + : quotaMapping.getValue()); added = true; } } @@ -219,9 +203,8 @@ public class QuotaManager implements UserDataProvider { if (target != null && hasQuota(target, quotaMapping.getName())) { Quota quota = get(target, quotaMapping.getName()); - quota.setValue( - quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() - : quotaMapping.getValue()); + quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() + : quotaMapping.getValue()); quotas.add(quota); added = true; @@ -242,18 +225,18 @@ public class QuotaManager implements UserDataProvider { * Apply item. * * @param target the target - * @param item the item + * @param item the item */ public void applyItem(Long target, Integer item) { for (QuotaMapping quotaMapping : quotaMappingManager.getAllByItem(item)) { Quota quota = get(target, quotaMapping.getName()); if (quota == null) { - quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), - quotaMapping.getUnit(), quotaMapping.isDisposable()); + quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), quotaMapping.getUnit(), + quotaMapping.isDisposable()); } else { - quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() - : quotaMapping.getValue()); + quota.setValue( + quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue()); quota = update(quota); } diff --git a/core/src/main/java/de/bstly/we/businesslogic/QuotaMappingManager.java b/core/src/main/java/de/bstly/we/businesslogic/QuotaMappingManager.java index f21b754..de80b7b 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/QuotaMappingManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/QuotaMappingManager.java @@ -36,8 +36,7 @@ public class QuotaMappingManager { * @return the all by item */ public List getAllByItem(Integer item) { - return Lists - .newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item))); + return Lists.newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item))); } /** @@ -58,27 +57,26 @@ public class QuotaMappingManager { * @return true, if successful */ public boolean exists(Integer item, String name) { - return quotaMappingRepository - .exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name))); + return quotaMappingRepository.exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name))); } /** * Creates the. * - * @param items the items - * @param name the name - * @param value the value - * @param unit the unit - * @param append the append - * @param products the products + * @param items the items + * @param name the name + * @param value the value + * @param unit the unit + * @param append the append + * @param products the products * @param disposable the disposable * @return the quota mapping */ - public QuotaMapping create(Set items, String name, long value, String unit, - boolean append, Set products, boolean disposable) { + public QuotaMapping create(Set items, String name, long value, String unit, boolean append, + Set products, boolean disposable) { for (Integer item : items) { - Assert.isTrue(!exists(item, name), "QuotaMapping for item '" + item + "' with quota '" - + name + "' already exists!"); + Assert.isTrue(!exists(item, name), + "QuotaMapping for item '" + item + "' with quota '" + name + "' already exists!"); } QuotaMapping quotaMapping = new QuotaMapping(); quotaMapping.setItems(items); @@ -98,13 +96,10 @@ public class QuotaMappingManager { * @return the quota mapping */ public QuotaMapping update(QuotaMapping quotaMapping) { - Assert.isTrue( - quotaMapping.getId() != null - && quotaMappingRepository.existsById(quotaMapping.getId()), + Assert.isTrue(quotaMapping.getId() != null && quotaMappingRepository.existsById(quotaMapping.getId()), "QuotaMapping '" + quotaMapping.getId() + "' does not exists!"); - QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId()) - .get(); + QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId()).get(); updateQuotaMapping.setProducts(quotaMapping.getProducts()); updateQuotaMapping.setItems(quotaMapping.getItems()); updateQuotaMapping.setValue(quotaMapping.getValue()); @@ -120,17 +115,16 @@ public class QuotaMappingManager { * @param id the id */ public void delete(Long id) { - Assert.isTrue(quotaMappingRepository.existsById(id), - "QuotaMapping '" + id + "' does not exists!"); + Assert.isTrue(quotaMappingRepository.existsById(id), "QuotaMapping '" + id + "' does not exists!"); quotaMappingRepository.deleteById(id); } /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/Setup.java b/core/src/main/java/de/bstly/we/businesslogic/Setup.java index 3fc8415..5968d04 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/Setup.java +++ b/core/src/main/java/de/bstly/we/businesslogic/Setup.java @@ -52,9 +52,9 @@ public class Setup implements SmartInitializingSingleton { private Logger logger = LoggerFactory.getLogger(Setup.class); - /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() + * @see org.springframework.beans.factory.SmartInitializingSingleton# + * afterSingletonsInstantiated() */ @Override public void afterSingletonsInstantiated() { @@ -75,14 +75,12 @@ public class Setup implements SmartInitializingSingleton { Resource resource = resourceLoader.getResource("classpath:usernames.txt"); if (resource.exists()) { - BufferedReader br = new BufferedReader( - new InputStreamReader(resource.getInputStream())); + BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream())); List usernames = Lists.newArrayList(); String line; while ((line = br.readLine()) != null) { - if (StringUtils.hasText(line) && !usernames.contains(line) - && !line.startsWith("#")) { + if (StringUtils.hasText(line) && !usernames.contains(line) && !line.startsWith("#")) { usernames.add(line); } } diff --git a/core/src/main/java/de/bstly/we/businesslogic/SystemProfileFieldManager.java b/core/src/main/java/de/bstly/we/businesslogic/SystemProfileFieldManager.java index 6544992..a539ff3 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/SystemProfileFieldManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/SystemProfileFieldManager.java @@ -44,9 +44,9 @@ public class SystemProfileFieldManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/SystemPropertyManager.java b/core/src/main/java/de/bstly/we/businesslogic/SystemPropertyManager.java index f7db183..671ebf4 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/SystemPropertyManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/SystemPropertyManager.java @@ -42,13 +42,12 @@ public class SystemPropertyManager { /** * Gets the. * - * @param key the key + * @param key the key * @param defaultValue the default value * @return the string */ public String get(String key, String defaultValue) { - return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)) - .getValue(); + return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue(); } /** @@ -64,7 +63,7 @@ public class SystemPropertyManager { /** * Gets the boolean. * - * @param key the key + * @param key the key * @param defaultValue the default value * @return the boolean */ @@ -85,7 +84,7 @@ public class SystemPropertyManager { /** * Gets the integer. * - * @param key the key + * @param key the key * @param defaultValue the default value * @return the integer */ @@ -106,7 +105,7 @@ public class SystemPropertyManager { /** * Gets the long. * - * @param key the key + * @param key the key * @param defaultValue the default value * @return the long */ @@ -117,7 +116,7 @@ public class SystemPropertyManager { /** * Adds the. * - * @param key the key + * @param key the key * @param value the value */ public void add(String key, String value) { @@ -129,7 +128,7 @@ public class SystemPropertyManager { /** * Update. * - * @param key the key + * @param key the key * @param value the value */ public void update(String key, String value) { @@ -143,7 +142,7 @@ public class SystemPropertyManager { /** * Sets the. * - * @param key the key + * @param key the key * @param value the value */ public void set(String key, String value) { diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserAliasManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserAliasManager.java index bdfed30..6be4bc2 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/UserAliasManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserAliasManager.java @@ -89,9 +89,9 @@ public class UserAliasManager implements UserDataProvider { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserDataManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserDataManager.java index 7cf164e..9797437 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/UserDataManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserDataManager.java @@ -61,9 +61,7 @@ public class UserDataManager implements SmartInitializingSingleton { private Gson gson = new Gson(); /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() - */ - /* + * * @see org.springframework.beans.factory.SmartInitializingSingleton# * afterSingletonsInstantiated() */ @@ -90,8 +88,7 @@ public class UserDataManager implements SmartInitializingSingleton { * @param dry the dry */ public void purge(boolean dry) { - long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS, - SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT); + long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS, SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT); Pageable pageable = PageRequest.of(0, 100, Sort.by("id")); Page page; @@ -99,14 +96,12 @@ public class UserDataManager implements SmartInitializingSingleton { page = userRepository.findAll(pageable); for (User user : page.getContent()) { if (!UserStatus.SLEEP.equals(user.getStatus())) { - if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId()) - .isEmpty()) { + if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId()).isEmpty()) { if (UserStatus.PURGE.equals(user.getStatus())) { purge(user, dry); } else if (UserStatus.NORMAL.equals(user.getStatus())) { Instant last = Instant.MIN; - for (Permission permission : permissionManager - .getAllByTarget(user.getId())) { + for (Permission permission : permissionManager.getAllByTarget(user.getId())) { if (permission.getExpires().isAfter(last)) { last = permission.getExpires(); } @@ -127,56 +122,36 @@ public class UserDataManager implements SmartInitializingSingleton { * Purge. * * @param user the user - * @param dry the dry + * @param dry the dry */ public void purge(User user, boolean dry) { Long userId = user.getId(); if (dry) { - logger.debug("Would purge all data of user '" - + user.getUsername() - + "' [id=" - + user.getId() - + "]!"); + logger.debug("Would purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!"); } else { - logger.warn("Purge all data of user '" - + user.getUsername() - + "' [id=" - + user.getId() - + "]!"); + logger.warn("Purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!"); } for (UserDataProvider provider : providers) { if (dry) { List result = provider.getUserData(userId); if (!result.isEmpty()) { - logger.debug("\tWould have purged '" - + provider.getId() - + "' data of user '" - + user.getUsername() - + "' [id=" - + user.getId() - + "]!"); + logger.debug("\tWould have purged '" + provider.getId() + "' data of user '" + user.getUsername() + + "' [id=" + user.getId() + "]!"); if (logger.isTraceEnabled()) { for (UserData userData : result) { - logger.trace("\t\t" - + gson.toJson(userData)); + logger.trace("\t\t" + gson.toJson(userData)); } } } } else { List result = provider.getUserData(userId); if (!result.isEmpty()) { - logger.warn("\tPurge '" - + provider.getId() - + "' data of user '" - + user.getUsername() - + "' [id=" - + user.getId() - + "]!"); + logger.warn("\tPurge '" + provider.getId() + "' data of user '" + user.getUsername() + "' [id=" + + user.getId() + "]!"); if (logger.isTraceEnabled()) { for (UserData userData : result) { - logger.trace("\t\t" - + gson.toJson(userData)); + logger.trace("\t\t" + gson.toJson(userData)); } } provider.purgeUserData(userId); @@ -185,11 +160,7 @@ public class UserDataManager implements SmartInitializingSingleton { } if (!dry) { - logger.warn("Purged all data of user '" - + user.getUsername() - + "' [id=" - + user.getId() - + "]!"); + logger.warn("Purged all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!"); } } diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserDomainManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserDomainManager.java index 50b0f80..65d09f5 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/UserDomainManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserDomainManager.java @@ -119,9 +119,9 @@ public class UserDomainManager implements UserDataProvider { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ @@ -161,8 +161,7 @@ public class UserDomainManager implements UserDataProvider { * @throws NamingException the naming exception */ public boolean validate(UserDomain userDomain) throws NamingException { - Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(), - new String[] { "TXT" }); + Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(), new String[] { "TXT" }); NamingEnumeration attributeEnumeration = attributes.getAll(); while (attributeEnumeration.hasMore()) { diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserManager.java index 105f19f..840bcab 100755 --- a/core/src/main/java/de/bstly/we/businesslogic/UserManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserManager.java @@ -87,8 +87,7 @@ public class UserManager implements UserDataProvider { * @return the by bstly email */ public User getByBstlyEmail(String email) { - String username = email.replace("@" - + userEmailDomain, ""); + String username = email.replace("@" + userEmailDomain, ""); return getByUsername(username); } @@ -109,23 +108,19 @@ public class UserManager implements UserDataProvider { * @return the password hash */ public String getPasswordHash(Long id) { - Assert.isTrue(userRepository.existsById(id), "User with id '" - + id - + "' not exists!"); + Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!"); return userRepository.findById(id).get().getPasswordHash(); } /** * Sets the password. * - * @param id the id + * @param id the id * @param password the password * @return the user */ public User setPassword(Long id, String password) { - Assert.isTrue(userRepository.existsById(id), "User with id '" - + id - + "' not exists!"); + Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!"); User user = userRepository.findById(id).get(); user.setPasswordHash(passwordEncoder.encode(password)); return userRepository.save(user); @@ -136,14 +131,12 @@ public class UserManager implements UserDataProvider { * * @param username the username * @param password the password - * @param status the status + * @param status the status * @return the user */ public User create(String username, String password, UserStatus status) { Assert.isTrue(!userRepository.exists(qUser.username.equalsIgnoreCase(username)), - "Username '" - + username - + "' already exists!"); + "Username '" + username + "' already exists!"); User user = new User(); user.setUsername(username); if (StringUtils.hasText(password)) { @@ -160,9 +153,9 @@ public class UserManager implements UserDataProvider { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ @@ -178,9 +171,7 @@ public class UserManager implements UserDataProvider { * @return the user */ public User update(User user) { - Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" - + user.getId() - + "' not exists!"); + Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!"); User merge = get(user.getId()); merge.setUsername(user.getUsername()); @@ -201,9 +192,7 @@ public class UserManager implements UserDataProvider { * @param user the user */ public void delete(User user) { - Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" - + user.getId() - + "' not exists!"); + Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!"); File publicKey = new File(getPublicKeyPath(user.getUsername())); if (publicKey.exists()) { @@ -222,15 +211,13 @@ public class UserManager implements UserDataProvider { * @return the bstly email */ public String getBstlyEmail(String username) { - return username - + "@" - + userEmailDomain; + return username + "@" + userEmailDomain; } /** * Write public key. * - * @param username the username + * @param username the username * @param publicKey the public key */ public void writePublicKey(String username, String publicKey) { @@ -250,8 +237,7 @@ public class UserManager implements UserDataProvider { FileWriter myWriter = new FileWriter(publicKeyPath); myWriter.write(publicKey); myWriter.close(); - String command = "gpg --import " - + publicKeyPath; + String command = "gpg --import " + publicKeyPath; Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); @@ -266,25 +252,19 @@ public class UserManager implements UserDataProvider { * @return the public key path */ public String getPublicKeyPath(String username) { - return userDataDirectory - + username - + File.separator - + "public.key"; + return userDataDirectory + username + File.separator + "public.key"; } /** * Password reset. * - * @param user the user + * @param user the user * @param outputStream the output stream */ public void passwordReset(User user, ServletOutputStream outputStream) { // TODO: change to public key profile field String resetToken = RandomStringUtils.random(64, true, true); - String command = "echo \"" - + resetToken - + "\" | gpg -ear " - + getBstlyEmail(user.getUsername()) + String command = "echo \"" + resetToken + "\" | gpg -ear " + getBstlyEmail(user.getUsername()) + " --always-trust"; user.setResetToken(resetToken); @@ -293,10 +273,8 @@ public class UserManager implements UserDataProvider { ProcessBuilder b = new ProcessBuilder("/bin/bash", "-c", command); Process process = b.start(); - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - BufferedReader errorReader = new BufferedReader( - new InputStreamReader(process.getErrorStream())); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); int c; while ((c = reader.read()) != -1) { outputStream.write(c); @@ -328,8 +306,7 @@ public class UserManager implements UserDataProvider { * @param user the user */ protected void deleteSessionsForUser(User user) { - Map usersSessions = sessionRepository - .findByPrincipalName(user.getUsername()); + Map usersSessions = sessionRepository.findByPrincipalName(user.getUsername()); for (Session session : usersSessions.values()) { sessionRepository.deleteById(session.getId()); } @@ -363,16 +340,10 @@ public class UserManager implements UserDataProvider { user.setDisabled(true); user.setLocked(true); user = update(user); - logger.warn("User '" - + user.getUsername() - + "' [" - + user.getId() - + "] should be purged!"); + logger.warn("User '" + user.getUsername() + "' [" + user.getId() + "] should be purged!"); } else { - logger.error("No user found for [" - + userId - + "]!"); + logger.error("No user found for [" + userId + "]!"); } } diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserProfileFieldManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserProfileFieldManager.java index c1e0076..9f6d3e9 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/UserProfileFieldManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserProfileFieldManager.java @@ -32,13 +32,12 @@ public class UserProfileFieldManager implements UserDataProvider { * Gets the. * * @param target the target - * @param name the name + * @param name the name * @return the user profile field */ public UserProfileField get(Long target, String name) { return userProfileFieldRepository - .findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))) - .orElse(null); + .findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))).orElse(null); } /** @@ -48,15 +47,15 @@ public class UserProfileFieldManager implements UserDataProvider { * @return the all by target */ public List getAllByTarget(Long target) { - return Lists.newArrayList(userProfileFieldRepository.findAll( - qUserProfileField.target.eq(target), Sort.by("index", "name").ascending())); + return Lists.newArrayList(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target), + Sort.by("index", "name").ascending())); } /** * Gets the by target filtered. * * @param target the target - * @param names the names + * @param names the names * @return the by target filtered */ public List getByTargetFiltered(Long target, List names) { @@ -68,15 +67,13 @@ public class UserProfileFieldManager implements UserDataProvider { /** * Gets the all by target and visibilities. * - * @param target the target + * @param target the target * @param visibilities the visibilities * @return the all by target and visibilities */ - public List getAllByTargetAndVisibilities(Long target, - List visibilities) { + public List getAllByTargetAndVisibilities(Long target, List visibilities) { return Lists.newArrayList(userProfileFieldRepository.findAll( - qUserProfileField.target.eq(target) - .and(qUserProfileField.visibility.in(visibilities)), + qUserProfileField.target.eq(target).and(qUserProfileField.visibility.in(visibilities)), Sort.by("index", "name").ascending())); } @@ -94,20 +91,15 @@ public class UserProfileFieldManager implements UserDataProvider { * Delete. * * @param target the target - * @param name the name + * @param name the name */ public void delete(Long target, String name) { Assert.isTrue( - userProfileFieldRepository.exists( - qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))), - "ProfileField '" - + name - + "' for target + '" - + target - + "' not exists!"); + userProfileFieldRepository + .exists(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))), + "ProfileField '" + name + "' for target + '" + target + "' not exists!"); UserProfileField delete = userProfileFieldRepository - .findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))) - .get(); + .findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))).get(); userProfileFieldRepository.delete(delete); } @@ -117,8 +109,7 @@ public class UserProfileFieldManager implements UserDataProvider { * @param target the target */ public void deleteAll(Long target) { - userProfileFieldRepository - .deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target))); + userProfileFieldRepository.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target))); } /* diff --git a/core/src/main/java/de/bstly/we/businesslogic/UserTotpManager.java b/core/src/main/java/de/bstly/we/businesslogic/UserTotpManager.java index c1fd743..7ec0930 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/UserTotpManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/UserTotpManager.java @@ -50,27 +50,30 @@ public class UserTotpManager implements SecondFactorProvider { return "totp"; } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang.String) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang. + * String) */ @Override public boolean supports(String provider) { return getId().equals(provider); } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang.Long) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang. + * Long) */ @Override public boolean isEnabled(Long userId) { - return userTotpRepository - .exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue())); + return userTotpRepository.exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue())); } /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang.Long, java.lang.String) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang. + * Long, java.lang.String) */ @Override public boolean validate(Long userId, String code) { @@ -83,18 +86,19 @@ public class UserTotpManager implements SecondFactorProvider { return false; } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long) */ @Override public UserTotp get(Long userId) { return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null); } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang.Long) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang. + * Long) */ @Override public UserTotp create(Long userId) { @@ -105,8 +109,8 @@ public class UserTotpManager implements SecondFactorProvider { userTotp.setSecret(secretGenerator.generate()); User user = userManager.get(userId); - QrData data = qrDataFactory.newBuilder().label(user.getUsername()) - .secret(userTotp.getSecret()).issuer("we.bstly").build(); + QrData data = qrDataFactory.newBuilder().label(user.getUsername()).secret(userTotp.getSecret()) + .issuer("we.bstly").build(); userTotp.setQrData(data.getUri()); userTotp.setRecoveryCodes(Lists.newArrayList(recoveryCodeGenerator.generateCodes(16))); return userTotpRepository.save(userTotp); @@ -114,15 +118,15 @@ public class UserTotpManager implements SecondFactorProvider { return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null); } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang.Long, java.lang.String) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang. + * Long, java.lang.String) */ @Override public boolean enable(Long userId, String code) { if (validate(userId, code)) { - UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId)) - .orElse(null); + UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null); userTotp.setEnabled(true); userTotpRepository.save(userTotp); return true; @@ -130,9 +134,10 @@ public class UserTotpManager implements SecondFactorProvider { return false; } - /* - * @see de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang.Long) + * @see + * de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang. + * Long) */ @Override public void delete(Long userId) { diff --git a/core/src/main/java/de/bstly/we/businesslogic/VoucherMappingManager.java b/core/src/main/java/de/bstly/we/businesslogic/VoucherMappingManager.java index 06e970a..6af5e5c 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/VoucherMappingManager.java +++ b/core/src/main/java/de/bstly/we/businesslogic/VoucherMappingManager.java @@ -59,18 +59,14 @@ public class VoucherMappingManager { /** * Creates the. * - * @param name the name + * @param name the name * @param voucher the voucher - * @param quota the quota - * @param isFree the is free + * @param quota the quota + * @param isFree the is free * @return the voucher mapping */ public VoucherMapping create(String name, int voucher, String quota, boolean isFree) { - Assert.isTrue(!exists(name), "QuotaMapping for voucher '" - + voucher - + "' with '" - + name - + "' already exists!"); + Assert.isTrue(!exists(name), "QuotaMapping for voucher '" + voucher + "' with '" + name + "' already exists!"); VoucherMapping voucherMapping = new VoucherMapping(); voucherMapping.setName(name); @@ -87,12 +83,8 @@ public class VoucherMappingManager { * @return the voucher mapping */ public VoucherMapping update(VoucherMapping voucherMapping) { - Assert.isTrue( - voucherMapping.getId() != null - && voucherMappingRepository.existsById(voucherMapping.getId()), - "VoucherMapping '" - + voucherMapping.getId() - + "' does not exists!"); + Assert.isTrue(voucherMapping.getId() != null && voucherMappingRepository.existsById(voucherMapping.getId()), + "VoucherMapping '" + voucherMapping.getId() + "' does not exists!"); return voucherMappingRepository.save(voucherMapping); } @@ -103,18 +95,16 @@ public class VoucherMappingManager { * @param id the id */ public void delete(Long id) { - Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" - + id - + "' does not exists!"); + Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" + id + "' does not exists!"); voucherMappingRepository.deleteById(id); } /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/core/src/main/java/de/bstly/we/businesslogic/support/AbstractModelEventListener.java b/core/src/main/java/de/bstly/we/businesslogic/support/AbstractModelEventListener.java index 65d35d9..f052ae6 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/support/AbstractModelEventListener.java +++ b/core/src/main/java/de/bstly/we/businesslogic/support/AbstractModelEventListener.java @@ -20,12 +20,11 @@ import de.bstly.we.event.AbstractModelEventType; import de.bstly.we.model.AbstractModel; /** - * The listener interface for receiving abstractModelEvent events. - * The class that is interested in processing a abstractModelEvent - * event implements this interface, and the object created - * with that class is registered with a component using the - * component's addAbstractModelEventListener method. When - * the abstractModelEvent event occurs, that object's appropriate + * The listener interface for receiving abstractModelEvent events. The class + * that is interested in processing a abstractModelEvent event implements this + * interface, and the object created with that class is registered with a + * component using the component's addAbstractModelEventListener + * method. When the abstractModelEvent event occurs, that object's appropriate * method is invoked. * * @see AbstractModelEventEvent diff --git a/core/src/main/java/de/bstly/we/businesslogic/support/InstantHelper.java b/core/src/main/java/de/bstly/we/businesslogic/support/InstantHelper.java index ead9e03..95361db 100644 --- a/core/src/main/java/de/bstly/we/businesslogic/support/InstantHelper.java +++ b/core/src/main/java/de/bstly/we/businesslogic/support/InstantHelper.java @@ -20,7 +20,7 @@ public class InstantHelper { * Plus. * * @param instant the instant - * @param amount the amount + * @param amount the amount * @return the instant */ public static Instant plus(Instant instant, TemporalAmount amount) { @@ -30,9 +30,9 @@ public class InstantHelper { /** * Plus. * - * @param instant the instant + * @param instant the instant * @param amountToAdd the amount to add - * @param unit the unit + * @param unit the unit * @return the instant */ public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) { @@ -43,7 +43,7 @@ public class InstantHelper { * Minus. * * @param instant the instant - * @param amount the amount + * @param amount the amount * @return the instant */ public static Instant minus(Instant instant, TemporalAmount amount) { @@ -53,32 +53,29 @@ public class InstantHelper { /** * Minus. * - * @param instant the instant + * @param instant the instant * @param amountToAdd the amount to add - * @param unit the unit + * @param unit the unit * @return the instant */ public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) { - return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit) - .toInstant(); + return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant(); } /** * Truncate. * * @param instant the instant - * @param unit the unit + * @param unit the unit * @return the instant */ public static Instant truncate(Instant instant, TemporalUnit unit) { if (ChronoUnit.YEARS.equals(unit)) { instant = instant.truncatedTo(ChronoUnit.DAYS); - return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) - .with(ChronoField.DAY_OF_YEAR, 1L).toInstant(); + return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant(); } else if (ChronoUnit.MONTHS.equals(unit)) { instant = instant.truncatedTo(ChronoUnit.DAYS); - return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) - .with(ChronoField.DAY_OF_MONTH, 1L).toInstant(); + return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant(); } return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant(); diff --git a/core/src/main/java/de/bstly/we/controller/Authentication2FAController.java b/core/src/main/java/de/bstly/we/controller/Authentication2FAController.java index 7476c42..369da7e 100644 --- a/core/src/main/java/de/bstly/we/controller/Authentication2FAController.java +++ b/core/src/main/java/de/bstly/we/controller/Authentication2FAController.java @@ -96,8 +96,8 @@ public class Authentication2FAController extends BaseController { } for (SecondFactorProvider provider : secondFactorProviderManager.getEnabled(userId)) { - SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel( - provider.getId(), provider instanceof SecondFactorRequestProvider); + SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(provider.getId(), + provider instanceof SecondFactorRequestProvider); result.remove(enabledProvider); } return result; @@ -175,12 +175,11 @@ public class Authentication2FAController extends BaseController { * Enable second factor. * * @param providerId the provider id - * @param token the token + * @param token the token */ @PreAuthorize("authentication.authenticated") @PatchMapping("/{id}") - public void enableSecondFactor(@PathVariable("id") String providerId, - @RequestBody String token) { + public void enableSecondFactor(@PathVariable("id") String providerId, @RequestBody String token) { SecondFactorProvider provider = secondFactorProviderManager.getProvider(providerId); if (provider == null) { diff --git a/core/src/main/java/de/bstly/we/controller/AuthenticationController.java b/core/src/main/java/de/bstly/we/controller/AuthenticationController.java index 525ff3e..a4c44e5 100755 --- a/core/src/main/java/de/bstly/we/controller/AuthenticationController.java +++ b/core/src/main/java/de/bstly/we/controller/AuthenticationController.java @@ -56,14 +56,14 @@ public class AuthenticationController extends BaseController { * Password request. * * @param username the username - * @param req the req - * @param resp the resp + * @param req the req + * @param resp the resp * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAnonymous()") @PostMapping("/password/request") - public void passwordRequest(@RequestBody String username, HttpServletRequest req, - HttpServletResponse resp) throws IOException { + public void passwordRequest(@RequestBody String username, HttpServletRequest req, HttpServletResponse resp) + throws IOException { User user = userManager.getByUsername(username); if (user != null) { @@ -78,13 +78,13 @@ public class AuthenticationController extends BaseController { * Password reset. * * @param passwordResetModel the password reset model - * @param req the req - * @param resp the resp + * @param req the req + * @param resp the resp */ @PreAuthorize("isAnonymous()") @PostMapping("/password/reset") - public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, - HttpServletRequest req, HttpServletResponse resp) { + public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, HttpServletRequest req, + HttpServletResponse resp) { User user = userManager.getByResetToken(passwordResetModel.getToken().trim()); if (user == null) { diff --git a/core/src/main/java/de/bstly/we/controller/ItemController.java b/core/src/main/java/de/bstly/we/controller/ItemController.java index 3320cf5..3ef3eb0 100755 --- a/core/src/main/java/de/bstly/we/controller/ItemController.java +++ b/core/src/main/java/de/bstly/we/controller/ItemController.java @@ -80,7 +80,7 @@ public class ItemController extends BaseController { /** * Adds the item. * - * @param secret the secret + * @param secret the secret * @param session the session */ @PutMapping("") @@ -99,7 +99,7 @@ public class ItemController extends BaseController { /** * Removes the item. * - * @param secret the secret + * @param secret the secret * @param session the session */ @DeleteMapping @@ -131,7 +131,7 @@ public class ItemController extends BaseController { * Redeem for user. * * @param username the username - * @param session the session + * @param session the session */ @PreAuthorize("isAuthenticated()") @PostMapping("/{username}") @@ -147,8 +147,7 @@ public class ItemController extends BaseController { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } - tokenSessionManager.applyTokens(user.getId(), - tokenSessionManager.getTokenFromSession(session)); + tokenSessionManager.applyTokens(user.getId(), tokenSessionManager.getTokenFromSession(session)); tokenSessionManager.removeTokensFromSession(session); } diff --git a/core/src/main/java/de/bstly/we/controller/PermissionController.java b/core/src/main/java/de/bstly/we/controller/PermissionController.java index e112715..e1403cc 100644 --- a/core/src/main/java/de/bstly/we/controller/PermissionController.java +++ b/core/src/main/java/de/bstly/we/controller/PermissionController.java @@ -59,8 +59,7 @@ public class PermissionController extends BaseController { } for (String token : tokenSessionManager.getTokenFromSession(session)) { - permissions - .addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token)); + permissions.addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token)); } return permissions; diff --git a/core/src/main/java/de/bstly/we/controller/PermissionManagementController.java b/core/src/main/java/de/bstly/we/controller/PermissionManagementController.java index 1a8de01..2df39d6 100644 --- a/core/src/main/java/de/bstly/we/controller/PermissionManagementController.java +++ b/core/src/main/java/de/bstly/we/controller/PermissionManagementController.java @@ -82,8 +82,8 @@ public class PermissionManagementController extends BaseController { @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping public Permission createPermission(@RequestBody Permission permission) { - return permissionManager.create(permission.getTarget(), permission.getName(), - permission.isAddon(), permission.getStarts(), permission.getExpires()); + return permissionManager.create(permission.getTarget(), permission.getName(), permission.isAddon(), + permission.getStarts(), permission.getExpires()); } /** @@ -125,14 +125,13 @@ public class PermissionManagementController extends BaseController { /** * Clone. * - * @param name the name + * @param name the name * @param clone the clone * @return the list */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/{name}/clone/{clone}") - public List clone(@PathVariable("name") String name, - @PathVariable("clone") String clone) { + public List clone(@PathVariable("name") String name, @PathVariable("clone") String clone) { if (name.equals(clone)) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } diff --git a/core/src/main/java/de/bstly/we/controller/PermissionMappingController.java b/core/src/main/java/de/bstly/we/controller/PermissionMappingController.java index 5e7e79f..b6cc542 100644 --- a/core/src/main/java/de/bstly/we/controller/PermissionMappingController.java +++ b/core/src/main/java/de/bstly/we/controller/PermissionMappingController.java @@ -49,11 +49,9 @@ public class PermissionMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getPermissionMappings( - @RequestParam("page") Optional pageParameter, + public Page getPermissionMappings(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), - "item", true); + return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "item", true); } /** @@ -71,12 +69,11 @@ public class PermissionMappingController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - return permissionMappingManager.create(permissionMapping.getItem(), - permissionMapping.getNames(), permissionMapping.getLifetime(), - permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(), - permissionMapping.isAddon(), permissionMapping.getProduct(), - permissionMapping.getStarts(), permissionMapping.getExpires(), - permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion()); + return permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(), + permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(), + permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(), + permissionMapping.getStarts(), permissionMapping.getExpires(), permissionMapping.getStartsQuestion(), + permissionMapping.getExpiresQuestion()); } /** @@ -87,8 +84,7 @@ public class PermissionMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/list") - public List createList( - @RequestBody List permissionMappings) { + public List createList(@RequestBody List permissionMappings) { List result = Lists.newArrayList(); for (PermissionMapping permissionMapping : permissionMappings) { Errors errors = new RequestBodyErrors(permissionMapping); @@ -97,10 +93,9 @@ public class PermissionMappingController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - result.add(permissionMappingManager.create(permissionMapping.getItem(), - permissionMapping.getNames(), permissionMapping.getLifetime(), - permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(), - permissionMapping.isAddon(), permissionMapping.getProduct(), + result.add(permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(), + permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(), + permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(), permissionMapping.getStarts(), permissionMapping.getExpires(), permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion())); } @@ -132,8 +127,7 @@ public class PermissionMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PatchMapping("/list") - public List updateList( - @RequestBody List permissionMappings) { + public List updateList(@RequestBody List permissionMappings) { List result = Lists.newArrayList(); for (PermissionMapping permissionMapping : permissionMappings) { Errors errors = new RequestBodyErrors(permissionMapping); diff --git a/core/src/main/java/de/bstly/we/controller/PretixApiController.java b/core/src/main/java/de/bstly/we/controller/PretixApiController.java index 8f92ae8..6dde47e 100755 --- a/core/src/main/java/de/bstly/we/controller/PretixApiController.java +++ b/core/src/main/java/de/bstly/we/controller/PretixApiController.java @@ -41,9 +41,9 @@ public class PretixApiController extends BaseController { * Debug. * * @param pretixRequest the pretix request - * @param response the response + * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/debug") @@ -58,10 +58,8 @@ public class PretixApiController extends BaseController { } } - gson.toJson( - pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(), - gson.toJsonTree(pretixRequest.getPayload()), queryParemeters), - response.getWriter()); + gson.toJson(pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(), + gson.toJsonTree(pretixRequest.getPayload()), queryParemeters), response.getWriter()); } catch (WebClientResponseException e) { throw new EntityResponseStatusException(e.getMessage(), e.getStatusCode()); } diff --git a/core/src/main/java/de/bstly/we/controller/QuotaManagementController.java b/core/src/main/java/de/bstly/we/controller/QuotaManagementController.java index 3f522b6..fbec65a 100644 --- a/core/src/main/java/de/bstly/we/controller/QuotaManagementController.java +++ b/core/src/main/java/de/bstly/we/controller/QuotaManagementController.java @@ -98,8 +98,8 @@ public class QuotaManagementController extends BaseController { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } - return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), - quota.getUnit(), quota.isDisposable()); + return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), quota.getUnit(), + quota.isDisposable()); } /** @@ -143,7 +143,7 @@ public class QuotaManagementController extends BaseController { /** * Clone. * - * @param name the name + * @param name the name * @param clone the clone * @param value the value * @return the list diff --git a/core/src/main/java/de/bstly/we/controller/QuotaMappingController.java b/core/src/main/java/de/bstly/we/controller/QuotaMappingController.java index aa19e92..9cb19c5 100644 --- a/core/src/main/java/de/bstly/we/controller/QuotaMappingController.java +++ b/core/src/main/java/de/bstly/we/controller/QuotaMappingController.java @@ -49,11 +49,9 @@ public class QuotaMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getQuotaMappings( - @RequestParam("page") Optional pageParameter, + public Page getQuotaMappings(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", - true); + return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true); } /** @@ -74,9 +72,9 @@ public class QuotaMappingController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(), - quotaMapping.getValue(), quotaMapping.getUnit(), quotaMapping.isAppend(), - quotaMapping.getProducts(), quotaMapping.isDisposable()); + return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(), quotaMapping.getValue(), + quotaMapping.getUnit(), quotaMapping.isAppend(), quotaMapping.getProducts(), + quotaMapping.isDisposable()); } /** diff --git a/core/src/main/java/de/bstly/we/controller/SystemController.java b/core/src/main/java/de/bstly/we/controller/SystemController.java index 12761ab..4ca08dc 100644 --- a/core/src/main/java/de/bstly/we/controller/SystemController.java +++ b/core/src/main/java/de/bstly/we/controller/SystemController.java @@ -58,8 +58,7 @@ public class SystemController extends BaseController { public List getProperties(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { Sort sort = Sort.by("key").ascending(); - return systemPropertyRepository - .findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort)) + return systemPropertyRepository.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort)) .getContent(); } diff --git a/core/src/main/java/de/bstly/we/controller/SystemProfileFieldController.java b/core/src/main/java/de/bstly/we/controller/SystemProfileFieldController.java index 20e9b11..69fd6fa 100644 --- a/core/src/main/java/de/bstly/we/controller/SystemProfileFieldController.java +++ b/core/src/main/java/de/bstly/we/controller/SystemProfileFieldController.java @@ -46,8 +46,7 @@ public class SystemProfileFieldController extends BaseController { @GetMapping public Page get(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), - "name", true); + return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true); } /** @@ -88,8 +87,7 @@ public class SystemProfileFieldController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/list") - public List updateList( - @RequestBody List systemProfileFields) { + public List updateList(@RequestBody List systemProfileFields) { List result = Lists.newArrayList(); for (SystemProfileField systemProfileField : systemProfileFields) { diff --git a/core/src/main/java/de/bstly/we/controller/UserAliasController.java b/core/src/main/java/de/bstly/we/controller/UserAliasController.java index 07916c0..522626d 100644 --- a/core/src/main/java/de/bstly/we/controller/UserAliasController.java +++ b/core/src/main/java/de/bstly/we/controller/UserAliasController.java @@ -131,8 +131,7 @@ public class UserAliasController extends BaseController { Quota aliasCreation = quotaManager.get(getCurrentUserId(), Quotas.ALIAS_CREATION); if (aliasCreation == null) { - aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#", - true); + aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#", true); } aliasCreation.setValue(aliasCreation.getValue() + 1); diff --git a/core/src/main/java/de/bstly/we/controller/UserController.java b/core/src/main/java/de/bstly/we/controller/UserController.java index 0864519..aeb255a 100755 --- a/core/src/main/java/de/bstly/we/controller/UserController.java +++ b/core/src/main/java/de/bstly/we/controller/UserController.java @@ -89,7 +89,7 @@ public class UserController extends BaseController { * Check model. * * @param userModel the user model - * @param session the session + * @param session the session * @return the user model */ @PostMapping("/model") @@ -108,7 +108,7 @@ public class UserController extends BaseController { * Register. * * @param userModel the user model - * @param session the session + * @param session the session * @return the user model */ @PreAuthorize("isAnonymous()") @@ -165,8 +165,7 @@ public class UserController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - User user = userManager.create(userModel.getUsername(), userModel.getPassword(), - userModel.getStatus()); + User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus()); for (UserProfileField userProfileField : userModel.getProfileFields()) { userProfileField.setTarget(user.getId()); @@ -210,8 +209,8 @@ public class UserController extends BaseController { User user = userManager.get(getCurrentUserId()); - if (!StringUtils.hasText(passwordModel.getOld()) || !passwordEncoder - .matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) { + if (!StringUtils.hasText(passwordModel.getOld()) + || !passwordEncoder.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) { throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED); } @@ -235,8 +234,7 @@ public class UserController extends BaseController { User user = userManager.get(getCurrentUserId()); if (StringUtils.hasText(userModel.getOld())) { Errors errors = new RequestBodyErrors(userModel); - if (!passwordEncoder.matches(userModel.getOld(), - userManager.getPasswordHash(getCurrentUserId()))) { + if (!passwordEncoder.matches(userModel.getOld(), userManager.getPasswordHash(getCurrentUserId()))) { throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED); } diff --git a/core/src/main/java/de/bstly/we/controller/UserDataManagementController.java b/core/src/main/java/de/bstly/we/controller/UserDataManagementController.java index 6755c23..f3723f3 100644 --- a/core/src/main/java/de/bstly/we/controller/UserDataManagementController.java +++ b/core/src/main/java/de/bstly/we/controller/UserDataManagementController.java @@ -67,12 +67,11 @@ public class UserDataManagementController extends BaseController { * Purge by username. * * @param username the username - * @param dry the dry + * @param dry the dry */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/purge/{username}") - public void purgeByUsername(@PathVariable("username") String username, - @RequestParam("dry") boolean dry) { + public void purgeByUsername(@PathVariable("username") String username, @RequestParam("dry") boolean dry) { User user = userManager.getByUsername(username); if (user == null) { diff --git a/core/src/main/java/de/bstly/we/controller/UserDomainController.java b/core/src/main/java/de/bstly/we/controller/UserDomainController.java index 45d6cb8..908814f 100644 --- a/core/src/main/java/de/bstly/we/controller/UserDomainController.java +++ b/core/src/main/java/de/bstly/we/controller/UserDomainController.java @@ -53,16 +53,14 @@ public class UserDomainController extends BaseController { if (!permissionManager.isFullUser(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - - + if (userDomain.getVisibility() == null) { userDomain.setVisibility(Visibility.PRIVATE); } userDomain.setTarget(getCurrentUserId()); userDomain.setValidated(false); - userDomain.setSecret( - RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true)); + userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true)); Errors errors = new RequestBodyErrors(userDomain); @@ -92,7 +90,7 @@ public class UserDomainController extends BaseController { if (oldDomain == null) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } - + if (!oldDomain.getTarget().equals(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } diff --git a/core/src/main/java/de/bstly/we/controller/UserDomainManagementController.java b/core/src/main/java/de/bstly/we/controller/UserDomainManagementController.java index 591c9f7..85c46a0 100644 --- a/core/src/main/java/de/bstly/we/controller/UserDomainManagementController.java +++ b/core/src/main/java/de/bstly/we/controller/UserDomainManagementController.java @@ -100,8 +100,7 @@ public class UserDomainManagementController extends BaseController { if (userDomain.getId() == null) { userDomain.setValidated(false); - userDomain.setSecret( - RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true)); + userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true)); } return userDomainManager.save(userDomain); diff --git a/core/src/main/java/de/bstly/we/controller/UserManagementController.java b/core/src/main/java/de/bstly/we/controller/UserManagementController.java index dbb7928..024e4d1 100644 --- a/core/src/main/java/de/bstly/we/controller/UserManagementController.java +++ b/core/src/main/java/de/bstly/we/controller/UserManagementController.java @@ -130,15 +130,13 @@ public class UserManagementController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - User user = userManager.create(userModel.getUsername(), userModel.getPassword(), - userModel.getStatus()); + User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus()); if (userModel.getPermissionMappings() != null) { for (PermissionMapping permissionMapping : userModel.getPermissionMappings()) { for (String name : permissionMapping.getNames()) { - permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null, - InstantHelper.plus(Instant.now(), permissionMapping.getLifetime(), - permissionMapping.getLifetimeUnit())); + permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null, InstantHelper + .plus(Instant.now(), permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit())); } } } @@ -159,8 +157,8 @@ public class UserManagementController extends BaseController { if (userModel.getQuotas() != null) { for (Quota quota : userModel.getQuotas()) { - quotaManager.create(user.getId(), quota.getName(), quota.getValue(), - quota.getUnit(), quota.isDisposable()); + quotaManager.create(user.getId(), quota.getName(), quota.getValue(), quota.getUnit(), + quota.isDisposable()); } } @@ -213,12 +211,11 @@ public class UserManagementController extends BaseController { * Purge. * * @param username the username - * @param dry the dry + * @param dry the dry */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/purge") - public void purge(@RequestParam("username") Optional username, - @RequestParam("dry") Optional dry) { + public void purge(@RequestParam("username") Optional username, @RequestParam("dry") Optional dry) { if (username.isPresent()) { User user = userManager.getByUsername(username.get()); diff --git a/core/src/main/java/de/bstly/we/controller/UserProfileFieldController.java b/core/src/main/java/de/bstly/we/controller/UserProfileFieldController.java index 263e7b4..5acd0fd 100644 --- a/core/src/main/java/de/bstly/we/controller/UserProfileFieldController.java +++ b/core/src/main/java/de/bstly/we/controller/UserProfileFieldController.java @@ -138,8 +138,7 @@ public class UserProfileFieldController extends BaseController { } - profileFields.addAll( - userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities)); + profileFields.addAll(userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities)); if (profileFields.isEmpty()) { throttleForbidden(); @@ -178,7 +177,7 @@ public class UserProfileFieldController extends BaseController { * Gets the field for user. * * @param username the username - * @param name the name + * @param name the name * @return the field for user */ @GetMapping("/{username}/field/{name}") diff --git a/core/src/main/java/de/bstly/we/controller/VoucherMappingController.java b/core/src/main/java/de/bstly/we/controller/VoucherMappingController.java index 36ce9d1..cd9b0db 100644 --- a/core/src/main/java/de/bstly/we/controller/VoucherMappingController.java +++ b/core/src/main/java/de/bstly/we/controller/VoucherMappingController.java @@ -49,11 +49,9 @@ public class VoucherMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getVoucherMappings( - @RequestParam("page") Optional pageParameter, + public Page getVoucherMappings(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", - true); + return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true); } /** @@ -98,9 +96,8 @@ public class VoucherMappingController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - result.add(voucherMappingManager.create(voucherMapping.getName(), - voucherMapping.getVoucher(), voucherMapping.getQuota(), - voucherMapping.isFree())); + result.add(voucherMappingManager.create(voucherMapping.getName(), voucherMapping.getVoucher(), + voucherMapping.getQuota(), voucherMapping.isFree())); } return result; } diff --git a/core/src/main/java/de/bstly/we/controller/model/SecondFactorProviderModel.java b/core/src/main/java/de/bstly/we/controller/model/SecondFactorProviderModel.java index 005216d..959a47a 100644 --- a/core/src/main/java/de/bstly/we/controller/model/SecondFactorProviderModel.java +++ b/core/src/main/java/de/bstly/we/controller/model/SecondFactorProviderModel.java @@ -14,7 +14,7 @@ public class SecondFactorProviderModel { /** * Instantiates a new second factor provider model. * - * @param id the id + * @param id the id * @param request the request */ public SecondFactorProviderModel(String id, boolean request) { diff --git a/core/src/main/java/de/bstly/we/controller/support/ControllerExceptionHandler.java b/core/src/main/java/de/bstly/we/controller/support/ControllerExceptionHandler.java index 98d9f94..faaa549 100644 --- a/core/src/main/java/de/bstly/we/controller/support/ControllerExceptionHandler.java +++ b/core/src/main/java/de/bstly/we/controller/support/ControllerExceptionHandler.java @@ -20,7 +20,7 @@ public class ControllerExceptionHandler extends ResponseEntityExceptionHandler { * Handle response entity status exception. * * @param exception the exception - * @param request the request + * @param request the request * @return the response entity */ @ExceptionHandler(value = { EntityResponseStatusException.class }) diff --git a/core/src/main/java/de/bstly/we/controller/support/EntityResponseStatusException.java b/core/src/main/java/de/bstly/we/controller/support/EntityResponseStatusException.java index da6dd7e..b0f76b8 100644 --- a/core/src/main/java/de/bstly/we/controller/support/EntityResponseStatusException.java +++ b/core/src/main/java/de/bstly/we/controller/support/EntityResponseStatusException.java @@ -37,7 +37,7 @@ public class EntityResponseStatusException extends NestedRuntimeException { /** * Instantiates a new entity response status exception. * - * @param body the body + * @param body the body * @param status the status */ public EntityResponseStatusException(@Nullable Object body, HttpStatus status) { @@ -47,9 +47,9 @@ public class EntityResponseStatusException extends NestedRuntimeException { /** * Instantiates a new entity response status exception. * - * @param body the body + * @param body the body * @param status the status - * @param cause the cause + * @param cause the cause */ public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) { super(null, cause); diff --git a/core/src/main/java/de/bstly/we/controller/support/JsonStringBodyControllerAdvice.java b/core/src/main/java/de/bstly/we/controller/support/JsonStringBodyControllerAdvice.java index 8a139de..1a24a6d 100644 --- a/core/src/main/java/de/bstly/we/controller/support/JsonStringBodyControllerAdvice.java +++ b/core/src/main/java/de/bstly/we/controller/support/JsonStringBodyControllerAdvice.java @@ -29,9 +29,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon private Gson gson = new Gson(); - /* - * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) + * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice# + * supports(org.springframework.core.MethodParameter, java.lang.reflect.Type, + * java.lang.Class) */ @Override public boolean supports(MethodParameter methodParameter, Type targetType, @@ -40,7 +41,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon } /* - * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#beforeBodyRead(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) + * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice# + * beforeBodyRead(org.springframework.http.HttpInputMessage, + * org.springframework.core.MethodParameter, java.lang.reflect.Type, + * java.lang.Class) */ @Override public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, @@ -48,9 +52,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon return inputMessage; } - /* - * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) + * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice# + * afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage, + * org.springframework.core.MethodParameter, java.lang.reflect.Type, + * java.lang.Class) */ @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, @@ -59,9 +65,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon return body; } - /* - * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) + * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice# + * handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage, + * org.springframework.core.MethodParameter, java.lang.reflect.Type, + * java.lang.Class) */ @Override public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, @@ -69,18 +77,23 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon return body; } - /* - * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.Class) + * @see + * org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice# + * supports(org.springframework.core.MethodParameter, java.lang.Class) */ @Override public boolean supports(MethodParameter returnType, Class> converterType) { return converterType == StringHttpMessageConverter.class; } - /* - * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.http.MediaType, java.lang.Class, org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse) + * @see + * org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice# + * beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, + * org.springframework.http.MediaType, java.lang.Class, + * org.springframework.http.server.ServerHttpRequest, + * org.springframework.http.server.ServerHttpResponse) */ @Override public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, diff --git a/core/src/main/java/de/bstly/we/controller/support/RequestBodyErrors.java b/core/src/main/java/de/bstly/we/controller/support/RequestBodyErrors.java index b9a8f26..9553646 100644 --- a/core/src/main/java/de/bstly/we/controller/support/RequestBodyErrors.java +++ b/core/src/main/java/de/bstly/we/controller/support/RequestBodyErrors.java @@ -33,9 +33,10 @@ public class RequestBodyErrors extends AbstractBindingResult { return target; } - /* - * @see org.springframework.validation.AbstractBindingResult#getActualFieldValue(java.lang.String) + * @see + * org.springframework.validation.AbstractBindingResult#getActualFieldValue(java + * .lang.String) */ @Override protected Object getActualFieldValue(String field) { diff --git a/core/src/main/java/de/bstly/we/controller/support/TokenSessionManager.java b/core/src/main/java/de/bstly/we/controller/support/TokenSessionManager.java index 41c29c1..0ac5c80 100644 --- a/core/src/main/java/de/bstly/we/controller/support/TokenSessionManager.java +++ b/core/src/main/java/de/bstly/we/controller/support/TokenSessionManager.java @@ -55,7 +55,7 @@ public class TokenSessionManager { * Gets the permission mappings for token. * * @param userId the user id - * @param token the token + * @param token the token * @return the permission mappings for token */ public List getPermissionMappingsForToken(Long userId, String token) { @@ -79,7 +79,7 @@ public class TokenSessionManager { * Gets the permissions for token. * * @param userId the user id - * @param token the token + * @param token the token * @return the permissions for token */ public List getPermissionsForToken(Long userId, String token) { @@ -100,7 +100,7 @@ public class TokenSessionManager { } permissions.addAll(permissionManager.getForItem(userId, item, - orderPosition.get("answers").getAsJsonArray(),lastPaymentDate, null)); + orderPosition.get("answers").getAsJsonArray(), lastPaymentDate, null)); } } catch (Exception e) { // ignore @@ -113,7 +113,7 @@ public class TokenSessionManager { * Gets the quota mappings for token. * * @param userId the user id - * @param token the token + * @param token the token * @return the quota mappings for token */ public List getQuotaMappingsForToken(Long userId, String token) { @@ -137,7 +137,7 @@ public class TokenSessionManager { * Adds the quotas for token. * * @param userId the user id - * @param token the token + * @param token the token * @param quotas the quotas */ public void addQuotasForToken(Long userId, String token, List quotas) { @@ -179,8 +179,8 @@ public class TokenSessionManager { throw new Exception("This should not happen!"); } - permissionManager.applyItem(userId, item, - position.get("answers").getAsJsonArray(), lastPaymentDate, null); + permissionManager.applyItem(userId, item, position.get("answers").getAsJsonArray(), lastPaymentDate, + null); permissionMappings.addAll(permissionMappingManager.getAllByItem(item)); quotaManager.applyItem(userId, item); quotaMappings.addAll(quotaMappingManager.getAllByItem(item)); @@ -222,7 +222,7 @@ public class TokenSessionManager { /** * Adds the token to session. * - * @param secret the secret + * @param secret the secret * @param session the session */ public void addTokenToSession(String secret, HttpSession session) { @@ -236,8 +236,7 @@ public class TokenSessionManager { } if (StringUtils.hasLength(tokens)) { - tokens += "," - + secret; + tokens += "," + secret; } else { tokens = secret; } @@ -249,7 +248,7 @@ public class TokenSessionManager { /** * Removes the token from session. * - * @param secret the secret + * @param secret the secret * @param session the session */ public void removeTokenFromSession(String secret, HttpSession session) { @@ -261,8 +260,7 @@ public class TokenSessionManager { for (String token : ((String) sessionAttribute).split(",")) { if (!token.equals(secret)) { if (StringUtils.hasLength(tokens)) { - tokens += "," - + secret; + tokens += "," + secret; } else { tokens = secret; } @@ -285,15 +283,14 @@ public class TokenSessionManager { /** * Creates the new auth. * - * @param auth the auth + * @param auth the auth * @param details the details * @return the authentication */ protected Authentication createNewAuth(Authentication auth, LocalUserDetails details) { Authentication newAuth = null; if (auth instanceof UsernamePasswordAuthenticationToken) { - newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), - details.getAuthorities()); + newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), details.getAuthorities()); } else { newAuth = new LocalAnonymousAuthenticationToken(details); } diff --git a/core/src/main/java/de/bstly/we/controller/validation/PasswordModelValidator.java b/core/src/main/java/de/bstly/we/controller/validation/PasswordModelValidator.java index 34283d2..5a7d5a9 100755 --- a/core/src/main/java/de/bstly/we/controller/validation/PasswordModelValidator.java +++ b/core/src/main/java/de/bstly/we/controller/validation/PasswordModelValidator.java @@ -46,9 +46,9 @@ public class PasswordModelValidator implements Validator { return clazz.isAssignableFrom(PasswordModel.class); } - /* - * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) + * @see org.springframework.validation.Validator#validate(java.lang.Object, + * org.springframework.validation.Errors) */ @Override public void validate(Object target, Errors errors) { diff --git a/core/src/main/java/de/bstly/we/controller/validation/UserAliasValidator.java b/core/src/main/java/de/bstly/we/controller/validation/UserAliasValidator.java index 8f3092f..73df165 100644 --- a/core/src/main/java/de/bstly/we/controller/validation/UserAliasValidator.java +++ b/core/src/main/java/de/bstly/we/controller/validation/UserAliasValidator.java @@ -16,7 +16,7 @@ import de.bstly.we.model.UserAlias; */ @Component public class UserAliasValidator implements Validator { - + @Autowired private UserModelValidator userModelValidator; diff --git a/core/src/main/java/de/bstly/we/controller/validation/UserDomainValidator.java b/core/src/main/java/de/bstly/we/controller/validation/UserDomainValidator.java index ee375ba..fcbb284 100644 --- a/core/src/main/java/de/bstly/we/controller/validation/UserDomainValidator.java +++ b/core/src/main/java/de/bstly/we/controller/validation/UserDomainValidator.java @@ -51,8 +51,8 @@ public class UserDomainValidator implements Validator { UserDomain existingDomain = userDomainManager.getByDomain(userDomain.getDomain()); - if (existingDomain != null && (userDomain.getId() == null - || !(existingDomain.getId().equals(userDomain.getId())))) { + if (existingDomain != null + && (userDomain.getId() == null || !(existingDomain.getId().equals(userDomain.getId())))) { errors.rejectValue("domain", "NOT_VALID"); return; } diff --git a/core/src/main/java/de/bstly/we/controller/validation/UserModelValidator.java b/core/src/main/java/de/bstly/we/controller/validation/UserModelValidator.java index 344a12f..963b6a2 100755 --- a/core/src/main/java/de/bstly/we/controller/validation/UserModelValidator.java +++ b/core/src/main/java/de/bstly/we/controller/validation/UserModelValidator.java @@ -60,14 +60,13 @@ public class UserModelValidator implements Validator { * Validate username. * * @param username the username - * @param field the field - * @param errors the errors + * @param field the field + * @param errors the errors */ public void validateUsername(String username, String field, Errors errors) { for (String systemUsername : systemPropertyManager.get(RESERVED_USERNAMES, "").split(",")) { - if (StringUtils.hasText(systemUsername) - && (username.toLowerCase().equals(systemUsername) - || username.toLowerCase().matches(systemUsername))) { + if (StringUtils.hasText(systemUsername) && (username.toLowerCase().equals(systemUsername) + || username.toLowerCase().matches(systemUsername))) { errors.rejectValue(field, "NOT_VALID"); break; } diff --git a/core/src/main/java/de/bstly/we/controller/validation/UserProfileFieldValidator.java b/core/src/main/java/de/bstly/we/controller/validation/UserProfileFieldValidator.java index 8ebbe21..2dc94da 100644 --- a/core/src/main/java/de/bstly/we/controller/validation/UserProfileFieldValidator.java +++ b/core/src/main/java/de/bstly/we/controller/validation/UserProfileFieldValidator.java @@ -40,8 +40,7 @@ public class UserProfileFieldValidator implements Validator { private DoubleValidator doubleValidator = DoubleValidator.getInstance(); private EmailValidator emailValidator = EmailValidator.getInstance(); private UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES); - private List validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false", - "False", "FALSE", "0"); + private List validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false", "False", "FALSE", "0"); /* * @see org.springframework.validation.Validator#supports(java.lang.Class) @@ -65,8 +64,7 @@ public class UserProfileFieldValidator implements Validator { errors.rejectValue("name", "TOO_LONG"); } - SystemProfileField systemProfileField = systemProfileFieldManager - .get(userProfileField.getName()); + SystemProfileField systemProfileField = systemProfileFieldManager.get(userProfileField.getName()); if (systemProfileField != null) { if (!systemProfileField.getType().equals(userProfileField.getType())) { diff --git a/core/src/main/java/de/bstly/we/event/AbstractModelEvent.java b/core/src/main/java/de/bstly/we/event/AbstractModelEvent.java index c4477ae..4e725e3 100644 --- a/core/src/main/java/de/bstly/we/event/AbstractModelEvent.java +++ b/core/src/main/java/de/bstly/we/event/AbstractModelEvent.java @@ -23,7 +23,7 @@ public class AbstractModelEvent extends ApplicationEvent { /** * Instantiates a new abstract model event. * - * @param type the type + * @param type the type * @param model the model */ public AbstractModelEvent(AbstractModelEventType type, AbstractModel model) { diff --git a/core/src/main/java/de/bstly/we/model/PermissionMapping.java b/core/src/main/java/de/bstly/we/model/PermissionMapping.java index e029327..8e3b4c5 100755 --- a/core/src/main/java/de/bstly/we/model/PermissionMapping.java +++ b/core/src/main/java/de/bstly/we/model/PermissionMapping.java @@ -283,25 +283,11 @@ public class PermissionMapping { @Converter public static class ChronoUnitConverter implements AttributeConverter { - /* - * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object) - */ - /* - * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang. - * Object) - */ @Override public String convertToDatabaseColumn(ChronoUnit chronoUnit) { return chronoUnit.name(); } - /* - * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object) - */ - /* - * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang. - * Object) - */ @Override public ChronoUnit convertToEntityAttribute(String value) { return ChronoUnit.valueOf(value); diff --git a/core/src/main/java/de/bstly/we/model/SystemProperty.java b/core/src/main/java/de/bstly/we/model/SystemProperty.java index 8ef67b3..fb57992 100755 --- a/core/src/main/java/de/bstly/we/model/SystemProperty.java +++ b/core/src/main/java/de/bstly/we/model/SystemProperty.java @@ -33,7 +33,7 @@ public class SystemProperty { /** * Instantiates a new system property. * - * @param key the key + * @param key the key * @param value the value */ public SystemProperty(String key, String value) { diff --git a/core/src/main/java/de/bstly/we/model/UserProfileField.java b/core/src/main/java/de/bstly/we/model/UserProfileField.java index 0601b2d..fc0ebd2 100644 --- a/core/src/main/java/de/bstly/we/model/UserProfileField.java +++ b/core/src/main/java/de/bstly/we/model/UserProfileField.java @@ -20,8 +20,7 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId; */ @Entity @IdClass(UserProfileFieldId.class) -@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target", - "name" })) +@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target", "name" })) public class UserProfileField implements UserData { @Id diff --git a/core/src/main/java/de/bstly/we/repository/PermissionRepository.java b/core/src/main/java/de/bstly/we/repository/PermissionRepository.java index 2438ac9..a2ed23a 100755 --- a/core/src/main/java/de/bstly/we/repository/PermissionRepository.java +++ b/core/src/main/java/de/bstly/we/repository/PermissionRepository.java @@ -13,7 +13,6 @@ import de.bstly.we.model.Permission; * The Interface PermissionRepository. */ @Repository -public interface PermissionRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface PermissionRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/core/src/main/java/de/bstly/we/repository/SystemProfileFieldRepository.java b/core/src/main/java/de/bstly/we/repository/SystemProfileFieldRepository.java index 443c38d..211f5e2 100644 --- a/core/src/main/java/de/bstly/we/repository/SystemProfileFieldRepository.java +++ b/core/src/main/java/de/bstly/we/repository/SystemProfileFieldRepository.java @@ -13,7 +13,7 @@ import de.bstly.we.model.SystemProfileField; * The Interface SystemProfileFieldRepository. */ @Repository -public interface SystemProfileFieldRepository extends JpaRepository, - QuerydslPredicateExecutor { +public interface SystemProfileFieldRepository + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/core/src/main/java/de/bstly/we/repository/UserAliasRepository.java b/core/src/main/java/de/bstly/we/repository/UserAliasRepository.java index 73328e8..87a4211 100644 --- a/core/src/main/java/de/bstly/we/repository/UserAliasRepository.java +++ b/core/src/main/java/de/bstly/we/repository/UserAliasRepository.java @@ -13,7 +13,6 @@ import de.bstly.we.model.UserAlias; * The Interface UserAliasRepository. */ @Repository -public interface UserAliasRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface UserAliasRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/core/src/main/java/de/bstly/we/repository/UserDomainRepository.java b/core/src/main/java/de/bstly/we/repository/UserDomainRepository.java index 4f70670..88d6457 100644 --- a/core/src/main/java/de/bstly/we/repository/UserDomainRepository.java +++ b/core/src/main/java/de/bstly/we/repository/UserDomainRepository.java @@ -13,7 +13,6 @@ import de.bstly.we.model.UserDomain; * The Interface UserDomainRepository. */ @Repository -public interface UserDomainRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface UserDomainRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/core/src/main/java/de/bstly/we/repository/UserProfileFieldRepository.java b/core/src/main/java/de/bstly/we/repository/UserProfileFieldRepository.java index 0aa9eb9..f0095e6 100644 --- a/core/src/main/java/de/bstly/we/repository/UserProfileFieldRepository.java +++ b/core/src/main/java/de/bstly/we/repository/UserProfileFieldRepository.java @@ -15,7 +15,6 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId; */ @Repository public interface UserProfileFieldRepository - extends JpaRepository, - QuerydslPredicateExecutor { + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/core/src/main/java/de/bstly/we/security/LocalAuthenticationEntryPoint.java b/core/src/main/java/de/bstly/we/security/LocalAuthenticationEntryPoint.java index 64e55bd..500b8b9 100644 --- a/core/src/main/java/de/bstly/we/security/LocalAuthenticationEntryPoint.java +++ b/core/src/main/java/de/bstly/we/security/LocalAuthenticationEntryPoint.java @@ -33,9 +33,11 @@ public class LocalAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPo super(loginFormUrl); }; - /* - * @see org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException) + * @see org.springframework.security.web.authentication. + * LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http. + * HttpServletRequest, javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.AuthenticationException) */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, diff --git a/core/src/main/java/de/bstly/we/security/LocalAuthenticationProvider.java b/core/src/main/java/de/bstly/we/security/LocalAuthenticationProvider.java index 2c47478..a1b4450 100755 --- a/core/src/main/java/de/bstly/we/security/LocalAuthenticationProvider.java +++ b/core/src/main/java/de/bstly/we/security/LocalAuthenticationProvider.java @@ -10,7 +10,9 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; +import org.springframework.stereotype.Component; import de.bstly.we.security.businesslogic.SecondFactorProvider; import de.bstly.we.security.businesslogic.SecondFactorProviderManager; @@ -21,14 +23,25 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken; /** * The Class LocalAuthenticationProvider. */ +@Component public class LocalAuthenticationProvider extends DaoAuthenticationProvider { @Autowired private SecondFactorProviderManager secondFactorProviderManager; + /** + * Instantiates a new local authentication provider. + * + * @param userDetailService the user detail service + */ + public LocalAuthenticationProvider(UserDetailsService userDetailService) { + setUserDetailsService(userDetailService); + } /* - * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework.security.core.Authentication) + * @see org.springframework.security.authentication.dao. + * AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework. + * security.core.Authentication) */ @Override public Authentication authenticate(Authentication auth) throws AuthenticationException { @@ -38,8 +51,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { if (auth.getPrincipal() instanceof LocalUserDetails) { LocalUserDetails details = (LocalUserDetails) auth.getPrincipal(); if (!secondFactorProviderManager.getEnabled(details.getUserId()).isEmpty()) { - PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken( - details, "", AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER")); + PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "", + AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER")); newAuth.setAuthenticated(false); return newAuth; } @@ -57,8 +70,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { .getProvider(secondFactorAuth.getProvider()); if (provider == null) { - throw new SecondFactorAuthenticationException( - "invalid provider: " + secondFactorAuth.getProvider(), details); + throw new SecondFactorAuthenticationException("invalid provider: " + secondFactorAuth.getProvider(), + details); } if (!provider.isEnabled(details.getUserId())) { @@ -70,8 +83,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { return new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), details.getAuthorities()); } else { - PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken( - details, "", auth.getAuthorities()); + PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "", + auth.getAuthorities()); newAuth.setAuthenticated(false); return newAuth; } @@ -82,7 +95,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { } /* - * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class) + * @see org.springframework.security.authentication.dao. + * AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class) */ public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) @@ -93,8 +107,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { /** * The Class SecondFactorAuthenticationException. */ - public static class SecondFactorAuthenticationException - extends InsufficientAuthenticationException { + public static class SecondFactorAuthenticationException extends InsufficientAuthenticationException { private LocalUserDetails principal; @@ -106,7 +119,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider { /** * Instantiates a new second factor authentication exception. * - * @param message the message + * @param message the message * @param principal the principal */ public SecondFactorAuthenticationException(String message, LocalUserDetails principal) { diff --git a/core/src/main/java/de/bstly/we/security/LocalRememberMeServices.java b/core/src/main/java/de/bstly/we/security/LocalRememberMeServices.java index 8a2f736..789390e 100644 --- a/core/src/main/java/de/bstly/we/security/LocalRememberMeServices.java +++ b/core/src/main/java/de/bstly/we/security/LocalRememberMeServices.java @@ -17,18 +17,19 @@ public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServi /** * Instantiates a new local remember me services. * - * @param key the key + * @param key the key * @param userDetailsService the user details service - * @param tokenRepository the token repository + * @param tokenRepository the token repository */ public LocalRememberMeServices(String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository) { super(key, userDetailsService, tokenRepository); } - /* - * @see org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.HttpServletRequest, java.lang.String) + * @see org.springframework.security.web.authentication.rememberme. + * AbstractRememberMeServices#rememberMeRequested(javax.servlet.http. + * HttpServletRequest, java.lang.String) */ @Override protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { diff --git a/core/src/main/java/de/bstly/we/security/LocalServletContextListener.java b/core/src/main/java/de/bstly/we/security/LocalServletContextListener.java index 19d6958..ecf4f64 100644 --- a/core/src/main/java/de/bstly/we/security/LocalServletContextListener.java +++ b/core/src/main/java/de/bstly/we/security/LocalServletContextListener.java @@ -4,12 +4,11 @@ package de.bstly.we.security; /** - * The listener interface for receiving localServletContext events. - * The class that is interested in processing a localServletContext - * event implements this interface, and the object created - * with that class is registered with a component using the - * component's addLocalServletContextListener method. When - * the localServletContext event occurs, that object's appropriate + * The listener interface for receiving localServletContext events. The class + * that is interested in processing a localServletContext event implements this + * interface, and the object created with that class is registered with a + * component using the component's addLocalServletContextListener + * method. When the localServletContext event occurs, that object's appropriate * method is invoked. * * @see LocalServletContextEvent diff --git a/core/src/main/java/de/bstly/we/security/LocalUserDetailsService.java b/core/src/main/java/de/bstly/we/security/LocalUserDetailsService.java index 4089330..87d03d8 100755 --- a/core/src/main/java/de/bstly/we/security/LocalUserDetailsService.java +++ b/core/src/main/java/de/bstly/we/security/LocalUserDetailsService.java @@ -1,5 +1,6 @@ package de.bstly.we.security; +import java.time.Instant; import java.util.HashSet; import java.util.Set; @@ -14,10 +15,14 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import de.bstly.we.businesslogic.PermissionManager; -import de.bstly.we.businesslogic.UserManager; +import com.google.common.collect.Lists; + import de.bstly.we.model.Permission; +import de.bstly.we.model.QPermission; +import de.bstly.we.model.QUser; import de.bstly.we.model.User; +import de.bstly.we.repository.PermissionRepository; +import de.bstly.we.repository.UserRepository; import de.bstly.we.security.model.LocalUserDetails; /** @@ -27,23 +32,26 @@ import de.bstly.we.security.model.LocalUserDetails; public class LocalUserDetailsService implements UserDetailsService { @Autowired - private UserManager userManager; + private UserRepository userRepository; @Autowired - private PermissionManager permissionManager; + private PermissionRepository permissionRepository; + + private QUser qUser = QUser.user; + private QPermission qPermission = QPermission.permission; /* - * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) + * @see org.springframework.security.core.userdetails.UserDetailsService# + * loadUserByUsername(java.lang.String) */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - User user = userManager.getByUsername(username); + User user = userRepository.findOne(qUser.username.equalsIgnoreCase(username)).orElse(null); if (user != null) { - String password = userManager.getPasswordHash(user.getId()); + String password = userRepository.findById(user.getId()).get().getPasswordHash(); if (password == null) { - throw new AuthenticationCredentialsNotFoundException( - "No password found: " + username); + throw new AuthenticationCredentialsNotFoundException("No password found: " + username); } if (user.isDisabled()) { @@ -75,8 +83,8 @@ public class LocalUserDetailsService implements UserDetailsService { // } // Create user details - LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), - password, authorities); + LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), password, + authorities); return userDetails; } @@ -93,7 +101,9 @@ public class LocalUserDetailsService implements UserDetailsService { */ public Set getAuthoritiesForUser(Long userId) { Set authorities = new HashSet(); - for (Permission permission : permissionManager.getNotExpiresByTarget(userId)) { + for (Permission permission : Lists.newArrayList( + permissionRepository.findAll(qPermission.target.eq(userId).and(qPermission.expires.after(Instant.now()) + .and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))))) { authorities.add(new SimpleGrantedAuthority(permission.getName())); } return authorities; diff --git a/core/src/main/java/de/bstly/we/security/PasswordEncoderConfig.java b/core/src/main/java/de/bstly/we/security/PasswordEncoderConfig.java new file mode 100644 index 0000000..072e62b --- /dev/null +++ b/core/src/main/java/de/bstly/we/security/PasswordEncoderConfig.java @@ -0,0 +1,25 @@ +/** + * + */ +package de.bstly.we.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; + +/** + * The Class PasswordEncoderConfig. + */ +@Configuration +public class PasswordEncoderConfig { + + /** + * Password encoder. + * + * @return the argon 2 password encoder + */ + @Bean(name = "passwordEncoder") + public Argon2PasswordEncoder passwordEncoder() { + return new Argon2PasswordEncoder(); + } +} diff --git a/core/src/main/java/de/bstly/we/security/SecurityConfig.java b/core/src/main/java/de/bstly/we/security/SecurityConfig.java index 4d856fa..b0d9456 100755 --- a/core/src/main/java/de/bstly/we/security/SecurityConfig.java +++ b/core/src/main/java/de/bstly/we/security/SecurityConfig.java @@ -11,14 +11,13 @@ import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @@ -33,6 +32,7 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import de.bstly.we.controller.support.TokenSessionManager; import de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter; import de.bstly.we.security.filter.LocalAnonymousAuthenticationFilter; import de.bstly.we.security.filter.RestAuthenticationFilter; @@ -55,11 +55,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired - private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler; - @Autowired private RestAuthenticationFailureHandler restAuthenticationFailureHandler; @Autowired private LocalAccessDeniedHandler localAccessDeniedHandler; + @Autowired + private PasswordEncoder passwordEncoder; + @Autowired + private TokenSessionManager tokenSessionManager; + @Autowired + private LocalAuthenticationProvider localAuthenticationProvider; @Value("${server.servlet.session.cookie.secure:false}") private boolean secureCookie; @@ -84,12 +88,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { */ @Autowired public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(daoAuthenticationProvider()); + localAuthenticationProvider.setPasswordEncoder(passwordEncoder); + auth.authenticationProvider(localAuthenticationProvider); } - /* - * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) + * @see org.springframework.security.config.annotation.web.configuration. + * WebSecurityConfigurerAdapter#configure(org.springframework.security.config. + * annotation.web.builders.HttpSecurity) */ @Override protected void configure(HttpSecurity http) throws Exception { @@ -102,26 +108,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { // disable deprectated xss protection .headers().xssProtection().disable().and() // form login - .formLogin().loginPage(loginUrl).usernameParameter("username") - .passwordParameter("password").loginProcessingUrl("/auth/login") - .defaultSuccessUrl(loginTargetUrl) + .formLogin().loginPage(loginUrl).usernameParameter("username").passwordParameter("password") + .loginProcessingUrl("/auth/login").defaultSuccessUrl(loginTargetUrl) .successHandler(formAuthenticationSuccessHandler()) - .failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")) - .and() + .failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")).and() // remember me .rememberMe().rememberMeServices(rememberMeServices()).and() // form totp - .addFilterBefore(formSecondFactorAuthenticationFilter(), - LocalAnonymousAuthenticationFilter.class) + .addFilterBefore(formSecondFactorAuthenticationFilter(), LocalAnonymousAuthenticationFilter.class) // rest login - .addFilterBefore(restAuthenticationFilter(), - UsernamePasswordAuthenticationFilter.class) + .addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) // rest totp - .addFilterAfter(restSecondFactorAuthenticationFilter(), - UsernamePasswordAuthenticationFilter.class) + .addFilterAfter(restSecondFactorAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) // Logout - .logout().logoutUrl("/auth/logout") - .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).and() + .logout().logoutUrl("/auth/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()) + .and() // exception .exceptionHandling().accessDeniedHandler(localAccessDeniedHandler) .authenticationEntryPoint(localAuthenticationEntryPoint()).and() @@ -155,29 +156,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { return source; } - /** - * Dao authentication provider. - * - * @return the dao authentication provider - */ - @Bean - public DaoAuthenticationProvider daoAuthenticationProvider() { - LocalAuthenticationProvider provider = new LocalAuthenticationProvider(); - provider.setUserDetailsService(localUserDetailsService); - provider.setPasswordEncoder(passwordEncoder()); - return provider; - } - - /** - * Password encoder. - * - * @return the argon 2 password encoder - */ - @Bean(name = "passwordEncoder") - public Argon2PasswordEncoder passwordEncoder() { - return new Argon2PasswordEncoder(); - } - /** * Local anonymous authentication filter. * @@ -195,10 +173,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { */ @Bean public LocalAuthenticationEntryPoint localAuthenticationEntryPoint() { - LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint( - loginUrl); - localAuthenticationEntryPoint - .addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize")); + LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(loginUrl); + localAuthenticationEntryPoint.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize")); return localAuthenticationEntryPoint; } @@ -211,14 +187,25 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public FormAuthenticationSuccessHandler formAuthenticationSuccessHandler() { FormAuthenticationSuccessHandler formAuthenticationSuccessHandler = new FormAuthenticationSuccessHandler( - loginTargetUrl, SecurityConfig.KEEP_PARAM); + rememberMeServices(), tokenSessionManager, loginTargetUrl, SecurityConfig.KEEP_PARAM); formAuthenticationSuccessHandler.setTotpRedirectUrl(secondFactorUrl); formAuthenticationSuccessHandler.setTargetUrlParameter("forward"); - formAuthenticationSuccessHandler - .addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize")); + formAuthenticationSuccessHandler.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize")); return formAuthenticationSuccessHandler; } + /** + * Rest authentication success handler. + * + * @return the rest authentication success handler + */ + @Bean + public RestAuthenticationSuccessHandler restAuthenticationSuccessHandler() { + RestAuthenticationSuccessHandler restAuthenticationSuccessHandler = new RestAuthenticationSuccessHandler( + rememberMeServices(), tokenSessionManager); + return restAuthenticationSuccessHandler; + } + /** * Form second factor authentication filter. * @@ -226,13 +213,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { * @throws Exception the exception */ @Bean - public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() - throws Exception { + public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() throws Exception { FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter = new FormSecondFactorAuthenticationFilter( "/auth/login/2fa"); formSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager()); - formSecondFactorAuthenticationFilter - .setAuthenticationSuccessHandler(formAuthenticationSuccessHandler()); + formSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler()); formSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices()); return formSecondFactorAuthenticationFilter; } @@ -245,10 +230,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { */ @Bean public RestAuthenticationFilter restAuthenticationFilter() throws Exception { - RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter( - "/auth/restlogin"); + RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter("/auth/restlogin"); restAuthenticationFilter.setAuthenticationManager(authenticationManager()); - restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler); + restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler()); restAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler); return restAuthenticationFilter; } @@ -260,15 +244,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { * @throws Exception the exception */ @Bean - public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() - throws Exception { + public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() throws Exception { RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter = new RestSecondFactorAuthenticationFilter( "/auth/restlogin/2fa"); restSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager()); - restSecondFactorAuthenticationFilter - .setAuthenticationSuccessHandler(restAuthenticationSuccessHandler); - restSecondFactorAuthenticationFilter - .setAuthenticationFailureHandler(restAuthenticationFailureHandler); + restSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler()); + restSecondFactorAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler); restSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices()); return restSecondFactorAuthenticationFilter; } @@ -302,8 +283,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { */ @Bean public RememberMeServices rememberMeServices() { - PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices( - KEEP_PARAM, localUserDetailsService, persistentTokenRepository()); + PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(KEEP_PARAM, + localUserDetailsService, persistentTokenRepository()); rememberMeServices.setCookieName("SESSION_" + KEEP_PARAM.toUpperCase()); rememberMeServices.setParameter(KEEP_PARAM); rememberMeServices.setUseSecureCookie(secureCookie); diff --git a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProvider.java b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProvider.java index 9f6976c..c340b10 100644 --- a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProvider.java +++ b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProvider.java @@ -38,7 +38,7 @@ public interface SecondFactorProvider extends UserDataPr * Validate. * * @param userId the user id - * @param code the code + * @param code the code * @return true, if successful */ boolean validate(Long userId, String code); @@ -63,7 +63,7 @@ public interface SecondFactorProvider extends UserDataPr * Enable. * * @param userId the user id - * @param code the code + * @param code the code * @return true, if successful */ boolean enable(Long userId, String code); diff --git a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProviderManager.java b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProviderManager.java index 48da821..677ee9d 100644 --- a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProviderManager.java +++ b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorProviderManager.java @@ -26,16 +26,15 @@ public class SecondFactorProviderManager implements SmartInitializingSingleton { */ private List> providers; - /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() + * @see org.springframework.beans.factory.SmartInitializingSingleton# + * afterSingletonsInstantiated() */ @Override public void afterSingletonsInstantiated() { providers = Lists.newArrayList(); - for (SecondFactorProvider provider : context.getBeansOfType(SecondFactorProvider.class) - .values()) { + for (SecondFactorProvider provider : context.getBeansOfType(SecondFactorProvider.class).values()) { providers.add(provider); } } diff --git a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorRequestProvider.java b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorRequestProvider.java index 04cf747..8e74365 100644 --- a/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorRequestProvider.java +++ b/core/src/main/java/de/bstly/we/security/businesslogic/SecondFactorRequestProvider.java @@ -10,8 +10,7 @@ import de.bstly.we.model.SecondFactor; * * @param the generic type */ -public interface SecondFactorRequestProvider - extends SecondFactorProvider { +public interface SecondFactorRequestProvider extends SecondFactorProvider { /** * Request. diff --git a/core/src/main/java/de/bstly/we/security/filter/FormSecondFactorAuthenticationFilter.java b/core/src/main/java/de/bstly/we/security/filter/FormSecondFactorAuthenticationFilter.java index 4cc2730..00bb174 100644 --- a/core/src/main/java/de/bstly/we/security/filter/FormSecondFactorAuthenticationFilter.java +++ b/core/src/main/java/de/bstly/we/security/filter/FormSecondFactorAuthenticationFilter.java @@ -40,24 +40,22 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication super(defaultFilterProcessesUrl); } - /* - * @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + * @see org.springframework.security.web.authentication. + * AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet. + * http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public Authentication attemptAuthentication(HttpServletRequest request, - HttpServletResponse response) + public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!request.getMethod().equals("POST")) { - throw new AuthenticationServiceException( - "Authentication method not supported: " + request.getMethod()); + throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null - || !(authentication instanceof PreAuthenticatedAuthenticationToken) + if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken) || !(authentication.getPrincipal() instanceof LocalUserDetails)) { throw new InsufficientAuthenticationException("login first!"); } @@ -75,14 +73,15 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication } - /* - * @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException) + * @see org.springframework.security.web.authentication. + * AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax. + * servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.AuthenticationException) */ @Override - protected void unsuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, AuthenticationException failed) - throws IOException, ServletException { + protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, + AuthenticationException failed) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication request failed: " + failed.toString(), failed); logger.debug("Updated SecurityContextHolder to contain null Authentication"); diff --git a/core/src/main/java/de/bstly/we/security/filter/LocalAnonymousAuthenticationFilter.java b/core/src/main/java/de/bstly/we/security/filter/LocalAnonymousAuthenticationFilter.java index 644eb31..ab79146 100755 --- a/core/src/main/java/de/bstly/we/security/filter/LocalAnonymousAuthenticationFilter.java +++ b/core/src/main/java/de/bstly/we/security/filter/LocalAnonymousAuthenticationFilter.java @@ -32,22 +32,25 @@ public class LocalAnonymousAuthenticationFilter extends AnonymousAuthenticationF super(KEY); } - /* - * @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) + * @see + * org.springframework.security.web.authentication.AnonymousAuthenticationFilter + * #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, + * javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (SecurityContextHolder.getContext().getAuthentication() == null) { - SecurityContextHolder.getContext() - .setAuthentication(createAuthentication((HttpServletRequest) req)); + SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req)); } chain.doFilter(req, res); } /* - * @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#createAuthentication(javax.servlet.http.HttpServletRequest) + * @see + * org.springframework.security.web.authentication.AnonymousAuthenticationFilter + * #createAuthentication(javax.servlet.http.HttpServletRequest) */ @Override protected Authentication createAuthentication(HttpServletRequest request) { diff --git a/core/src/main/java/de/bstly/we/security/filter/RestAuthenticationFilter.java b/core/src/main/java/de/bstly/we/security/filter/RestAuthenticationFilter.java index 997f0bc..f647681 100644 --- a/core/src/main/java/de/bstly/we/security/filter/RestAuthenticationFilter.java +++ b/core/src/main/java/de/bstly/we/security/filter/RestAuthenticationFilter.java @@ -44,16 +44,16 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi } /* - * @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + * @see org.springframework.security.web.authentication. + * AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet. + * http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public Authentication attemptAuthentication(HttpServletRequest request, - HttpServletResponse response) + public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!request.getMethod().equals("POST")) { - throw new AuthenticationServiceException( - "Authentication method not supported: " + request.getMethod()); + throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } try { @@ -77,8 +77,7 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi } Authentication authRequest = new UsernamePasswordAuthenticationToken( - loginModel.get(usernameKey).getAsString(), - loginModel.get(passwordKey).getAsString()); + loginModel.get(usernameKey).getAsString(), loginModel.get(passwordKey).getAsString()); return this.getAuthenticationManager().authenticate(authRequest); } catch (JsonMappingException | JsonParseException exception) { throw new AuthenticationCredentialsNotFoundException("Bad request"); diff --git a/core/src/main/java/de/bstly/we/security/filter/RestSecondFactorAuthenticationFilter.java b/core/src/main/java/de/bstly/we/security/filter/RestSecondFactorAuthenticationFilter.java index e839875..05e2c14 100644 --- a/core/src/main/java/de/bstly/we/security/filter/RestSecondFactorAuthenticationFilter.java +++ b/core/src/main/java/de/bstly/we/security/filter/RestSecondFactorAuthenticationFilter.java @@ -39,24 +39,22 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen super(defaultFilterProcessesUrl); } - /* - * @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + * @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter# + * attemptAuthentication(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) */ @Override - public Authentication attemptAuthentication(HttpServletRequest request, - HttpServletResponse response) + public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!request.getMethod().equals("POST")) { - throw new AuthenticationServiceException( - "Authentication method not supported: " + request.getMethod()); + throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null - || !(authentication instanceof PreAuthenticatedAuthenticationToken) + if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken) || !(authentication.getPrincipal() instanceof LocalUserDetails)) { throw new InsufficientAuthenticationException("login first!"); } @@ -79,10 +77,8 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen String provider = model2FA.get(SPRING_SECURITY_FORM_2FA_PROVIDER_KEY).getAsString(); String code = model2FA.get(SPRING_SECURITY_FORM_2FA_CODE_KEY).getAsString(); - if (model2FA.has(SecurityConfig.KEEP_PARAM) - && model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) { - request.setAttribute(SecurityConfig.KEEP_PARAM, - model2FA.get(SecurityConfig.KEEP_PARAM).getAsString()); + if (model2FA.has(SecurityConfig.KEEP_PARAM) && model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) { + request.setAttribute(SecurityConfig.KEEP_PARAM, model2FA.get(SecurityConfig.KEEP_PARAM).getAsString()); } LocalUserDetails details = (LocalUserDetails) authentication.getPrincipal(); @@ -93,14 +89,15 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen } } - /* - * @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException) + * @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter# + * unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.AuthenticationException) */ @Override - protected void unsuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, AuthenticationException failed) - throws IOException, ServletException { + protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, + AuthenticationException failed) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication request failed: " + failed.toString(), failed); logger.debug("Updated SecurityContextHolder to contain null Authentication"); diff --git a/core/src/main/java/de/bstly/we/security/handler/FormAuthenticationSuccessHandler.java b/core/src/main/java/de/bstly/we/security/handler/FormAuthenticationSuccessHandler.java index 22db00d..86fafe6 100644 --- a/core/src/main/java/de/bstly/we/security/handler/FormAuthenticationSuccessHandler.java +++ b/core/src/main/java/de/bstly/we/security/handler/FormAuthenticationSuccessHandler.java @@ -7,7 +7,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; @@ -24,13 +23,10 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken; /** * The Class FormAuthenticationSuccessHandler. */ -public class FormAuthenticationSuccessHandler - extends SavedRequestAwareAuthenticationSuccessHandler { +public class FormAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { - @Autowired - protected RememberMeServices rememberMeServices; - @Autowired - protected TokenSessionManager tokenSessionManager; + protected final RememberMeServices rememberMeServices; + protected final TokenSessionManager tokenSessionManager; private String totpRedirectUrl; private String rememberMeParameter; @@ -40,33 +36,44 @@ public class FormAuthenticationSuccessHandler /** * Instantiates a new form authentication success handler. * + * @param rememberMeServices the remember me services + * @param tokenSessionManager the token session manager * @param rememberMeParameter the remember me parameter */ - public FormAuthenticationSuccessHandler(String rememberMeParameter) { + public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices, + TokenSessionManager tokenSessionManager, String rememberMeParameter) { + this.rememberMeServices = rememberMeServices; + this.tokenSessionManager = tokenSessionManager; this.rememberMeParameter = rememberMeParameter; } /** * Instantiates a new form authentication success handler. * - * @param defaultTargetUrl the default target url + * @param rememberMeServices the remember me services + * @param tokenSessionManager the token session manager + * @param defaultTargetUrl the default target url * @param rememberMeParameter the remember me parameter */ - public FormAuthenticationSuccessHandler(String defaultTargetUrl, String rememberMeParameter) { + public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices, + TokenSessionManager tokenSessionManager, String defaultTargetUrl, String rememberMeParameter) { + this.rememberMeServices = rememberMeServices; + this.tokenSessionManager = tokenSessionManager; setDefaultTargetUrl(defaultTargetUrl); this.rememberMeParameter = rememberMeParameter; } - /* - * @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication) + * @see org.springframework.security.web.authentication. + * SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax. + * servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.Authentication) */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { - - if (!authentication.isAuthenticated() - && authentication instanceof PreAuthenticatedAuthenticationToken) { + + if (!authentication.isAuthenticated() && authentication instanceof PreAuthenticatedAuthenticationToken) { rememberMeServices.loginFail(request, response); boolean keep = false; String paramValue = request.getParameter(rememberMeParameter); @@ -77,23 +84,20 @@ public class FormAuthenticationSuccessHandler } } - if (authentication.getAuthorities() != null && authentication.getAuthorities() - .containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) { + if (authentication.getAuthorities() != null + && authentication.getAuthorities().containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) { getRedirectStrategy().sendRedirect(request, response, totpRedirectUrl + "?error" + (keep ? "&keep" : "")); } else { - getRedirectStrategy().sendRedirect(request, response, - totpRedirectUrl + (keep ? "?keep" : "")); + getRedirectStrategy().sendRedirect(request, response, totpRedirectUrl + (keep ? "?keep" : "")); } } else { rememberMeServices.loginSuccess(request, response, authentication); for (RequestMatcher matcher : requestMatchers) { if (matcher.matches(request)) { - getRedirectStrategy().sendRedirect(request, response, - request.getRequestURI() + (request.getQueryString() != null - ? "?" + request.getQueryString() - : "")); + getRedirectStrategy().sendRedirect(request, response, request.getRequestURI() + + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); return; } } diff --git a/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationFailureHandler.java b/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationFailureHandler.java index 624d4b0..b2a50ed 100644 --- a/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationFailureHandler.java +++ b/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationFailureHandler.java @@ -17,9 +17,12 @@ import org.springframework.stereotype.Component; @Component public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler { - /* - * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException) + * @see + * org.springframework.security.web.authentication.AuthenticationFailureHandler# + * onAuthenticationFailure(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.AuthenticationException) */ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, diff --git a/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationSuccessHandler.java b/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationSuccessHandler.java index b1f6dc4..85f17bc 100644 --- a/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationSuccessHandler.java +++ b/core/src/main/java/de/bstly/we/security/handler/RestAuthenticationSuccessHandler.java @@ -8,30 +8,36 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; +import org.springframework.security.web.authentication.RememberMeServices; +import de.bstly.we.controller.support.TokenSessionManager; import de.bstly.we.security.SecurityConfig; /** * The Class RestAuthenticationSuccessHandler. */ -@Component public class RestAuthenticationSuccessHandler extends FormAuthenticationSuccessHandler { /** * Instantiates a new rest authentication success handler. + * + * @param rememberMeServices the remember me services + * @param tokenSessionManager the token session manager */ - public RestAuthenticationSuccessHandler() { - super(SecurityConfig.KEEP_PARAM); + public RestAuthenticationSuccessHandler(RememberMeServices rememberMeServices, + TokenSessionManager tokenSessionManager) { + super(rememberMeServices, tokenSessionManager, SecurityConfig.KEEP_PARAM); } - /* - * @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication) + * @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler# + * onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, + * org.springframework.security.core.Authentication) */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) throws IOException, ServletException { + Authentication authentication) throws IOException, ServletException { if (!authentication.isAuthenticated()) { rememberMeServices.loginFail(request, response); response.sendError(HttpStatus.PRECONDITION_REQUIRED.value(), diff --git a/core/src/main/java/de/bstly/we/security/model/LocalUserDetails.java b/core/src/main/java/de/bstly/we/security/model/LocalUserDetails.java index e5a5e78..68072b4 100755 --- a/core/src/main/java/de/bstly/we/security/model/LocalUserDetails.java +++ b/core/src/main/java/de/bstly/we/security/model/LocalUserDetails.java @@ -22,9 +22,9 @@ public class LocalUserDetails extends User { /** * Instantiates a new local user details. * - * @param userId the user id - * @param username the username - * @param password the password + * @param userId the user id + * @param username the username + * @param password the password * @param authorities the authorities */ public LocalUserDetails(Long userId, String username, String password, diff --git a/core/src/main/java/de/bstly/we/security/token/LocalAnonymousAuthenticationToken.java b/core/src/main/java/de/bstly/we/security/token/LocalAnonymousAuthenticationToken.java index ff883c5..01252fa 100644 --- a/core/src/main/java/de/bstly/we/security/token/LocalAnonymousAuthenticationToken.java +++ b/core/src/main/java/de/bstly/we/security/token/LocalAnonymousAuthenticationToken.java @@ -19,8 +19,7 @@ public class LocalAnonymousAuthenticationToken extends AnonymousAuthenticationTo */ private static final long serialVersionUID = 1L; public static final String ANONYMOUS_USERNAME = "anonymous"; - public static final List AUTHORITIES = AuthorityUtils - .createAuthorityList("ROLE_ANONYMOUS"); + public static final List AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"); /** * Instantiates a new local anonymous authentication token. @@ -34,7 +33,7 @@ public class LocalAnonymousAuthenticationToken extends AnonymousAuthenticationTo /** * Instantiates a new local anonymous authentication token. * - * @param principal the principal + * @param principal the principal * @param authorities the authorities */ public LocalAnonymousAuthenticationToken(Object principal, List authorities) { diff --git a/core/src/main/java/de/bstly/we/security/token/LocalSecondFactorAuthenticationToken.java b/core/src/main/java/de/bstly/we/security/token/LocalSecondFactorAuthenticationToken.java index a899eb5..724d758 100644 --- a/core/src/main/java/de/bstly/we/security/token/LocalSecondFactorAuthenticationToken.java +++ b/core/src/main/java/de/bstly/we/security/token/LocalSecondFactorAuthenticationToken.java @@ -21,8 +21,7 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication */ private static final long serialVersionUID = 1L; public static final String ROLE_REQUIRE_2FA = "ROLE_REQUIRE_2FA"; - public static final List AUTHORITIES = AuthorityUtils - .createAuthorityList(ROLE_REQUIRE_2FA); + public static final List AUTHORITIES = AuthorityUtils.createAuthorityList(ROLE_REQUIRE_2FA); /** * */ @@ -34,11 +33,10 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication * Instantiates a new local second factor authentication token. * * @param principal the principal - * @param provider the provider - * @param code the code + * @param provider the provider + * @param code the code */ - public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, - String code) { + public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, String code) { super(AUTHORITIES); this.principal = principal; this.provider = provider; diff --git a/email/src/main/java/de/bstly/we/email/businesslogic/EmailManager.java b/email/src/main/java/de/bstly/we/email/businesslogic/EmailManager.java index 772cf54..c32bc9f 100644 --- a/email/src/main/java/de/bstly/we/email/businesslogic/EmailManager.java +++ b/email/src/main/java/de/bstly/we/email/businesslogic/EmailManager.java @@ -32,10 +32,10 @@ public class EmailManager { /** * Send text. * - * @param to the to - * @param from the from + * @param to the to + * @param from the from * @param subject the subject - * @param text the text + * @param text the text * @return the mail message */ public MailMessage sendText(String to, String from, String subject, String text) { @@ -52,10 +52,10 @@ public class EmailManager { /** * Send bcc. * - * @param bcc the bcc - * @param from the from + * @param bcc the bcc + * @param from the from * @param subject the subject - * @param text the text + * @param text the text * @return the mail message */ public MailMessage sendBcc(String[] bcc, String from, String subject, String text) { @@ -80,12 +80,10 @@ public class EmailManager { UserProfileField primaryEmailUserProfileField = userProfileFieldManager.get(user.getId(), UserProfileFields.PROFILE_FIELD_EMAIL_PRIMARY); - if (primaryEmailUserProfileField != null - && "true".equals(primaryEmailUserProfileField.getValue())) { + if (primaryEmailUserProfileField != null && "true".equals(primaryEmailUserProfileField.getValue())) { UserProfileField emailUserProfileField = userProfileFieldManager.get(user.getId(), UserProfileFields.PROFILE_FIELD_EMAIL); - if (emailUserProfileField != null - && StringUtils.hasText(emailUserProfileField.getValue())) { + if (emailUserProfileField != null && StringUtils.hasText(emailUserProfileField.getValue())) { email = emailUserProfileField.getValue(); } } diff --git a/email/src/main/java/de/bstly/we/email/controller/EmailController.java b/email/src/main/java/de/bstly/we/email/controller/EmailController.java index 1a08c6d..46af7cb 100644 --- a/email/src/main/java/de/bstly/we/email/controller/EmailController.java +++ b/email/src/main/java/de/bstly/we/email/controller/EmailController.java @@ -54,8 +54,7 @@ public class EmailController extends BaseController { @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/test") public MailMessage sendTest(@RequestBody String to) { - return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email", - "Test from we.bstly"); + return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email", "Test from we.bstly"); } /** @@ -80,8 +79,7 @@ public class EmailController extends BaseController { UserProfileField localeUserProfileField = userProfileFieldManager.get(user.getId(), UserProfileFields.PROFILE_FIELD_LOCALE); - if (localeUserProfileField != null - && StringUtils.hasText(localeUserProfileField.getValue())) { + if (localeUserProfileField != null && StringUtils.hasText(localeUserProfileField.getValue())) { userMailModel.setLocale(localeUserProfileField.getValue()); } @@ -91,6 +89,4 @@ public class EmailController extends BaseController { return result; } - - } diff --git a/email/src/main/java/de/bstly/we/email/controller/model/UserMailModel.java b/email/src/main/java/de/bstly/we/email/controller/model/UserMailModel.java index d56d8fc..87f1e05 100644 --- a/email/src/main/java/de/bstly/we/email/controller/model/UserMailModel.java +++ b/email/src/main/java/de/bstly/we/email/controller/model/UserMailModel.java @@ -16,7 +16,7 @@ public class UserMailModel { * Instantiates a new user mail model. * * @param username the username - * @param email the email + * @param email the email */ public UserMailModel(String username, String email) { super(); diff --git a/i18n/src/main/java/de/bstly/we/i18n/businesslogic/I18nManager.java b/i18n/src/main/java/de/bstly/we/i18n/businesslogic/I18nManager.java index 1e341fd..2dee68a 100644 --- a/i18n/src/main/java/de/bstly/we/i18n/businesslogic/I18nManager.java +++ b/i18n/src/main/java/de/bstly/we/i18n/businesslogic/I18nManager.java @@ -70,7 +70,7 @@ public class I18nManager { * Extend json object. * * @param dest the dest - * @param src the src + * @param src the src */ protected void extendJsonObject(JsonObject dest, JsonObject src) { for (Entry srcEntry : src.entrySet()) { @@ -92,7 +92,7 @@ public class I18nManager { /** * Adds the label. * - * @param locale the locale + * @param locale the locale * @param newLabel the new label * @return the i 18 n */ @@ -116,7 +116,7 @@ public class I18nManager { * Sets the label. * * @param locale the locale - * @param label the label + * @param label the label * @return the i 18 n */ public I18n setLabel(String locale, JsonObject label) { diff --git a/i18n/src/main/java/de/bstly/we/i18n/controller/I18nController.java b/i18n/src/main/java/de/bstly/we/i18n/controller/I18nController.java index d0757b0..7d6ed87 100644 --- a/i18n/src/main/java/de/bstly/we/i18n/controller/I18nController.java +++ b/i18n/src/main/java/de/bstly/we/i18n/controller/I18nController.java @@ -51,11 +51,11 @@ public class I18nController extends BaseController { /** * Gets the label. * - * @param locale the locale + * @param locale the locale * @param response the response * @return the label * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @GetMapping("/{locale}") public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response) @@ -71,7 +71,7 @@ public class I18nController extends BaseController { * Sets the label. * * @param locale the locale - * @param label the label + * @param label the label */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/{locale}") @@ -87,7 +87,7 @@ public class I18nController extends BaseController { * Adds the label. * * @param locale the locale - * @param label the label + * @param label the label */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PutMapping("/{locale}") diff --git a/i18n/src/main/java/de/bstly/we/i18n/repository/I18nRepository.java b/i18n/src/main/java/de/bstly/we/i18n/repository/I18nRepository.java index e5788e5..70a1266 100644 --- a/i18n/src/main/java/de/bstly/we/i18n/repository/I18nRepository.java +++ b/i18n/src/main/java/de/bstly/we/i18n/repository/I18nRepository.java @@ -13,7 +13,6 @@ import de.bstly.we.i18n.model.I18n; * The Interface I18nRepository. */ @Repository -public interface I18nRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface I18nRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteManager.java b/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteManager.java index 6c9337e..7257fe7 100644 --- a/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteManager.java +++ b/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteManager.java @@ -63,15 +63,14 @@ public class InviteManager implements UserDataProvider { /** * Gets the. * - * @param page the page - * @param size the size + * @param page the page + * @param size the size * @param search the search * @return the page */ public Page get(int page, int size, String search) { if (StringUtils.hasText(search)) { - return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search), - PageRequest.of(page, size)); + return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search), PageRequest.of(page, size)); } return inviteRepository.findAll(PageRequest.of(page, size)); } @@ -89,18 +88,18 @@ public class InviteManager implements UserDataProvider { /** * Gets the by owner. * - * @param owner the owner - * @param quota the quota - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param owner the owner + * @param quota the quota + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending - * @param search the search - * @param redeemed the redeemed + * @param search the search + * @param redeemed the redeemed * @return the by owner */ - public Page getByOwner(Long owner, String quota, int page, int size, String sortBy, - boolean descending, String search, String redeemed) { + public Page getByOwner(Long owner, String quota, int page, int size, String sortBy, boolean descending, + String search, String redeemed) { PageRequest pageRequest = PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()); @@ -129,16 +128,15 @@ public class InviteManager implements UserDataProvider { /** * Gets the others. * - * @param owner the owner - * @param quota the quota - * @param page the page - * @param size the size - * @param search the search + * @param owner the owner + * @param quota the quota + * @param page the page + * @param size the size + * @param search the search * @param redeemed the redeemed * @return the others */ - public Page getOthers(Long owner, String quota, int page, int size, String search, - String redeemed) { + public Page getOthers(Long owner, String quota, int page, int size, String search, String redeemed) { BooleanBuilder query = new BooleanBuilder(); query.and(qInvite.owner.ne(owner)); @@ -173,8 +171,7 @@ public class InviteManager implements UserDataProvider { } } - InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(), - invite.getQuota()); + InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota()); Assert.notNull(inviteMapping, "No mapping for item!"); if (StringUtils.hasLength(inviteMapping.getCodeLink())) { invite.setCodeLink(String.format(inviteMapping.getCodeLink(), invite.getCode())); diff --git a/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteMappingManager.java b/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteMappingManager.java index bd66067..2155427 100644 --- a/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteMappingManager.java +++ b/invite/src/main/java/de/bstly/we/invite/businesslogic/InviteMappingManager.java @@ -46,22 +46,21 @@ public class InviteMappingManager { /** * Gets the by item and quota. * - * @param item the item + * @param item the item * @param quota the quota * @return the by item and quota */ public InviteMapping getByItemAndQuota(int item, String quota) { - return inviteMappingRepository - .findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota))) + return inviteMappingRepository.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota))) .orElse(null); } /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ @@ -73,9 +72,9 @@ public class InviteMappingManager { /** * Creates the. * - * @param quota the quota - * @param item the item - * @param starts the starts + * @param quota the quota + * @param item the item + * @param starts the starts * @param expires the expires * @return the invite mapping */ @@ -98,8 +97,8 @@ public class InviteMappingManager { */ public InviteMapping save(InviteMapping inviteMapping) { - for (Invite invite : inviteRepository.findAll(qInvite.item.eq(inviteMapping.getItem()) - .and(qInvite.quota.eq(inviteMapping.getQuota())))) { + for (Invite invite : inviteRepository + .findAll(qInvite.item.eq(inviteMapping.getItem()).and(qInvite.quota.eq(inviteMapping.getQuota())))) { if (StringUtils.hasText(inviteMapping.getCodeLink())) { String codeLink = String.format(inviteMapping.getCodeLink(), invite.getCode()); if (!codeLink.equals(invite.getCodeLink())) { @@ -120,17 +119,17 @@ public class InviteMappingManager { invite.setUrl(null); inviteRepository.save(invite); } - + if (!invite.getStarts().equals(inviteMapping.getStarts())) { invite.setStarts(inviteMapping.getStarts()); inviteRepository.save(invite); } - + if (!invite.getExpires().equals(inviteMapping.getExpires())) { invite.setExpires(inviteMapping.getExpires()); inviteRepository.save(invite); } - + } return inviteMappingRepository.save(inviteMapping); diff --git a/invite/src/main/java/de/bstly/we/invite/controller/InviteController.java b/invite/src/main/java/de/bstly/we/invite/controller/InviteController.java index 764673a..22f840c 100644 --- a/invite/src/main/java/de/bstly/we/invite/controller/InviteController.java +++ b/invite/src/main/java/de/bstly/we/invite/controller/InviteController.java @@ -119,8 +119,8 @@ public class InviteController extends BaseController { throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE); } - return permissionManager.getForItem(null, invite.getItem(), new JsonArray(), - invite.getStarts(), invite.getExpires()); + return permissionManager.getForItem(null, invite.getItem(), new JsonArray(), invite.getStarts(), + invite.getExpires()); } /** @@ -162,15 +162,14 @@ public class InviteController extends BaseController { throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE); } - if (invite.isRedeemed() - || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) { + if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) { throw new EntityResponseStatusException(HttpStatus.GONE); } boolean register = false; - for (Permission permission : permissionManager.getForItem(null, invite.getItem(), - new JsonArray(), invite.getStarts(), invite.getExpires())) { + for (Permission permission : permissionManager.getForItem(null, invite.getItem(), new JsonArray(), + invite.getStarts(), invite.getExpires())) { if (permission.getExpires().isAfter(Instant.now()) && !permission.isAddon()) { register = true; break; @@ -200,8 +199,7 @@ public class InviteController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - User user = userManager.create(userModel.getUsername(), userModel.getPassword(), - userModel.getStatus()); + User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus()); Long userId = user.getId(); @@ -218,8 +216,7 @@ public class InviteController extends BaseController { userProfileField = userProfileFieldManager.save(userProfileField); } - permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), - invite.getExpires()); + permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires()); quotaManager.applyItem(userId, invite.getItem()); invite.setRedeemed(true); @@ -241,15 +238,13 @@ public class InviteController extends BaseController { throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE); } - if (invite.isRedeemed() - || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) { + if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) { throw new EntityResponseStatusException(HttpStatus.GONE); } Long userId = getCurrentUserId(); - permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), - invite.getExpires()); + permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires()); quotaManager.applyItem(userId, invite.getItem()); invite.setRedeemed(true); @@ -260,12 +255,12 @@ public class InviteController extends BaseController { /** * Gets the invites. * - * @param quotaParameter the quota parameter - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParamater the sort paramater - * @param descParameter the desc parameter - * @param searchParameter the search parameter + * @param quotaParameter the quota parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParamater the sort paramater + * @param descParameter the desc parameter + * @param searchParameter the search parameter * @param redeemedParameter the redeemed parameter * @return the invites */ @@ -273,25 +268,23 @@ public class InviteController extends BaseController { @GetMapping public Page getInvites(@RequestParam("quota") Optional quotaParameter, @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParamater, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParamater, @RequestParam("desc") Optional descParameter, @RequestParam("search") Optional searchParameter, @RequestParam("redeemed") Optional redeemedParameter) { - return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""), - pageParameter.orElse(0), sizeParameter.orElse(10), sortParamater.orElse("id"), - descParameter.orElse(false), searchParameter.orElse(null), - redeemedParameter.orElse(null)); + return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""), pageParameter.orElse(0), + sizeParameter.orElse(10), sortParamater.orElse("id"), descParameter.orElse(false), + searchParameter.orElse(null), redeemedParameter.orElse(null)); } /** * Gets the other invites. * - * @param quota the quota - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param searchParameter the search parameter + * @param quota the quota + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param searchParameter the search parameter * @param redeemedParameter the redeemed parameter * @return the other invites */ @@ -304,15 +297,13 @@ public class InviteController extends BaseController { @RequestParam("redeemed") Optional redeemedParameter) { InviteMapping inviteMapping = inviteMappingManager.get(quota); - Quota inviteQuota = quotaManager.get(getCurrentUserId(), - InviteMapping.QUOTA_PREFIX + quota); + Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota); if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } - Page page = inviteManager.getOthers(getCurrentUserId(), quota, - pageParameter.orElse(0), sizeParameter.orElse(10), searchParameter.orElse(null), - redeemedParameter.orElse(null)); + Page page = inviteManager.getOthers(getCurrentUserId(), quota, pageParameter.orElse(0), + sizeParameter.orElse(10), searchParameter.orElse(null), redeemedParameter.orElse(null)); for (Invite invite : page.getContent()) { invite.setCode(null); invite.setCodeLink(null); @@ -327,17 +318,15 @@ public class InviteController extends BaseController { /** * Creates the invite. * - * @param quota the quota + * @param quota the quota * @param inviteModel the invite model * @return the invite */ @PreAuthorize("isAuthenticated()") @PostMapping("/{quota}") - public Invite createInvite(@PathVariable("quota") String quota, - @RequestBody Invite inviteModel) { + public Invite createInvite(@PathVariable("quota") String quota, @RequestBody Invite inviteModel) { InviteMapping inviteMapping = inviteMappingManager.get(quota); - Quota inviteQuota = quotaManager.get(getCurrentUserId(), - InviteMapping.QUOTA_PREFIX + quota); + Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota); if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } @@ -348,10 +337,8 @@ public class InviteController extends BaseController { Invite invite = new Invite(); invite.setOwner(getCurrentUserId()); - invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts() - : inviteModel.getStarts()); - invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires() - : inviteModel.getExpires()); + invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts() : inviteModel.getStarts()); + invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires() : inviteModel.getExpires()); invite.setItem(inviteMapping.getItem()); invite.setQuota(inviteMapping.getQuota()); diff --git a/invite/src/main/java/de/bstly/we/invite/controller/InviteManagingController.java b/invite/src/main/java/de/bstly/we/invite/controller/InviteManagingController.java index cb8f6b4..d5520de 100644 --- a/invite/src/main/java/de/bstly/we/invite/controller/InviteManagingController.java +++ b/invite/src/main/java/de/bstly/we/invite/controller/InviteManagingController.java @@ -44,16 +44,15 @@ public class InviteManagingController extends BaseController { /** * Gets the invites. * - * @param page the page - * @param size the size + * @param page the page + * @param size the size * @param search the search * @return the invites */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping public Page getInvites(@RequestParam("page") Optional page, - @RequestParam("size") Optional size, - @RequestParam("search") Optional search) { + @RequestParam("size") Optional size, @RequestParam("search") Optional search) { return inviteManager.get(page.orElse(0), size.orElse(10), search.orElse(null)); } @@ -66,8 +65,8 @@ public class InviteManagingController extends BaseController { @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping public Invite createOrUpdate(@RequestBody Invite invite) { - if (invite.getItem() == null || inviteMappingManager.getByItemAndQuota(invite.getItem(), - invite.getQuota()) == null) { + if (invite.getItem() == null + || inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota()) == null) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } diff --git a/invite/src/main/java/de/bstly/we/invite/controller/InviteMappingController.java b/invite/src/main/java/de/bstly/we/invite/controller/InviteMappingController.java index 9c61230..a5eecd3 100644 --- a/invite/src/main/java/de/bstly/we/invite/controller/InviteMappingController.java +++ b/invite/src/main/java/de/bstly/we/invite/controller/InviteMappingController.java @@ -47,11 +47,9 @@ public class InviteMappingController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getInviteMappings( - @RequestParam("page") Optional pageParameter, + public Page getInviteMappings(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota", - true); + return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota", true); } /** diff --git a/invite/src/main/java/de/bstly/we/invite/repository/InviteRepository.java b/invite/src/main/java/de/bstly/we/invite/repository/InviteRepository.java index 83ac72f..07c6f3d 100644 --- a/invite/src/main/java/de/bstly/we/invite/repository/InviteRepository.java +++ b/invite/src/main/java/de/bstly/we/invite/repository/InviteRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.invite.model.Invite; * The Interface InviteRepository. */ @Repository -public interface InviteRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface InviteRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/jitsi/pom.xml b/jitsi/pom.xml index 0077d6c..85570a6 100755 --- a/jitsi/pom.xml +++ b/jitsi/pom.xml @@ -26,6 +26,7 @@ com.nimbusds nimbus-jose-jwt + 9.21 diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/JitsiRoomManager.java b/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/JitsiRoomManager.java index 496b65e..cf0a340 100644 --- a/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/JitsiRoomManager.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/JitsiRoomManager.java @@ -117,8 +117,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro * @return the page */ public Page get(int page, int size, String sortBy, boolean descending) { - return jitsiRoomRepository.findAll(PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return jitsiRoomRepository.findAll( + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** @@ -131,14 +131,13 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro * @param descending the descending * @return the for user id */ - public Page getForUserId(Long userId, int page, int size, String sortBy, - boolean descending) { + public Page getForUserId(Long userId, int page, int size, String sortBy, boolean descending) { // delete expired rooms - jitsiRoomRepository.deleteAll(jitsiRoomRepository.findAll( - qJitsiRoom.owner.eq(userId).and(qJitsiRoom.expires.before(Instant.now())))); + jitsiRoomRepository.deleteAll( + jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId).and(qJitsiRoom.expires.before(Instant.now())))); - return jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId), PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId), + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** @@ -152,8 +151,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro * @return the jitsi room * @throws JOSEException the JOSE exception */ - public JitsiRoom create(Long owner, String room, Instant starts, Instant moderationStarts, - Instant expires) throws JOSEException { + public JitsiRoom create(Long owner, String room, Instant starts, Instant moderationStarts, Instant expires) + throws JOSEException { JitsiRoom jitsiRoom = new JitsiRoom(); jitsiRoom.setOwner(owner); jitsiRoom.setRoom(room); @@ -190,8 +189,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro bodyBuilder.notBeforeTime(Date.from(jitsiRoom.getStarts())); } - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT) - .build(); + JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build(); SignedJWT token = new SignedJWT(jwsHeader, bodyBuilder.build()); token.sign(signer); @@ -206,15 +204,13 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro jitsiRoom.setModerationToken(moderationToken.serialize()); jitsiRoom.setUrl(String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getToken())); - jitsiRoom.setModerationUrl( - String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getModerationToken())); + jitsiRoom.setModerationUrl(String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getModerationToken())); if (StringUtils.hasText(jitsiRoom.getCode())) { ShortenedUrl shortenedUrl = shortenedUrlManager.get(jitsiRoom.getCode()); if (shortenedUrl != null) { shortenedUrl.setUrl(jitsiRoom.getUrl()); - shortenedUrl.setNote("JitsiRoom: " - + jitsiRoom.getRoom()); + shortenedUrl.setNote("JitsiRoom: " + jitsiRoom.getRoom()); shortenedUrl.setExpires(jitsiRoom.getExpires()); shortenedUrlManager.save(shortenedUrl); jitsiRoom.setOrgUrl(jitsiRoom.getUrl()); @@ -234,10 +230,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro * @return the jitsi room */ public JitsiRoom createShortenedUrl(JitsiRoom jitsiRoom) { - ShortenedUrl shortenedUrl = shortenedUrlManager.create(jitsiRoom.getOwner(), - jitsiRoom.getUrl(), "JitsiRoom: " - + jitsiRoom.getRoom(), - null, jitsiRoom.getExpires(), null, false, true); + ShortenedUrl shortenedUrl = shortenedUrlManager.create(jitsiRoom.getOwner(), jitsiRoom.getUrl(), + "JitsiRoom: " + jitsiRoom.getRoom(), null, jitsiRoom.getExpires(), null, false, true); jitsiRoom.setOrgUrl(jitsiRoom.getUrl()); jitsiRoom.setCode(shortenedUrl.getCode()); jitsiRoom.setUrl(shortenedUrl.getLink()); @@ -254,8 +248,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro if (quota) { Quota jitsiRoomsQuota = quotaManager.get(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET); if (jitsiRoomsQuota == null) { - jitsiRoomsQuota = quotaManager.create(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET, - 0, "#", true); + jitsiRoomsQuota = quotaManager.create(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET, 0, "#", true); } jitsiRoomsQuota.setValue(jitsiRoomsQuota.getValue() + 1); @@ -263,8 +256,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro } if (StringUtils.hasText(jitsiRoom.getCode())) { - ShortenedUrl shortenedUrl = shortenedUrlRepository - .findOne(qShortenedUrl.code.eq(jitsiRoom.getCode())).orElse(null); + ShortenedUrl shortenedUrl = shortenedUrlRepository.findOne(qShortenedUrl.code.eq(jitsiRoom.getCode())) + .orElse(null); if (shortenedUrl != null) { if (quota) { Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(), @@ -293,8 +286,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro * @param quota the quota */ public void deleteAll(Long owner, boolean quota) { - List jitsiRooms = Lists - .newArrayList(jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(owner))); + List jitsiRooms = Lists.newArrayList(jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(owner))); for (JitsiRoom jitsiRoom : jitsiRooms) { delete(jitsiRoom, quota); @@ -336,7 +328,6 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro */ @Scheduled(cron = "0 */5 * * * *") protected void clearExpiredRooms() { - jitsiRoomRepository - .deleteAll(jitsiRoomRepository.findAll(qJitsiRoom.expires.before(Instant.now()))); + jitsiRoomRepository.deleteAll(jitsiRoomRepository.findAll(qJitsiRoom.expires.before(Instant.now()))); } } diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/support/UrlShortenerSync.java b/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/support/UrlShortenerSync.java index ef9f79f..c2cea76 100644 --- a/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/support/UrlShortenerSync.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/businesslogic/support/UrlShortenerSync.java @@ -25,9 +25,9 @@ public class UrlShortenerSync implements ApplicationListener private JitsiRoomRepository jitsiRoomRepository; private QJitsiRoom qJitsiRoom = QJitsiRoom.jitsiRoom; - /* - * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent) + * @see org.springframework.context.ApplicationListener#onApplicationEvent(org. + * springframework.context.ApplicationEvent) */ @Override public void onApplicationEvent(AbstractModelEvent event) { @@ -35,8 +35,8 @@ public class UrlShortenerSync implements ApplicationListener if (AbstractModelEventType.PRE_REMOVE.equals(event.getType())) { ShortenedUrl shortenedUrl = (ShortenedUrl) event.getModel(); - JitsiRoom jitsiRoom = jitsiRoomRepository - .findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())).orElse(null); + JitsiRoom jitsiRoom = jitsiRoomRepository.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())) + .orElse(null); if (jitsiRoom != null) { jitsiRoom.setUrl(jitsiRoom.getOrgUrl()); jitsiRoom.setCode(null); @@ -45,8 +45,8 @@ public class UrlShortenerSync implements ApplicationListener } } else if (AbstractModelEventType.POST_UPDATE.equals(event.getType())) { ShortenedUrl shortenedUrl = (ShortenedUrl) event.getModel(); - JitsiRoom jitsiRoom = jitsiRoomRepository - .findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())).orElse(null); + JitsiRoom jitsiRoom = jitsiRoomRepository.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())) + .orElse(null); if (jitsiRoom != null) { if (!StringUtils.hasText(jitsiRoom.getOrgUrl())) { jitsiRoom.setOrgUrl(jitsiRoom.getUrl()); diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomController.java b/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomController.java index 5b1e5dc..0b0297e 100644 --- a/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomController.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomController.java @@ -65,16 +65,15 @@ public class JitsiRoomController extends BaseController { @PreAuthorize("isAuthenticated()") @GetMapping public Page getJitsiRooms(@RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter) { if (!permissionManager.hasPermission(getCurrentUserId(), JitsiPermissions.JITSI_MEET)) { jitsiRoomManager.deleteAll(getCurrentUserId(), false); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - return jitsiRoomManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); + return jitsiRoomManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0), sizeParameter.orElse(10), + sortParameter.orElse("id"), descParameter.orElse(false)); } /** @@ -106,7 +105,7 @@ public class JitsiRoomController extends BaseController { } else { jitsiRoomValidator.validate(jitsiRoom, errors); } - + if (errors.hasErrors()) { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } @@ -115,8 +114,8 @@ public class JitsiRoomController extends BaseController { jitsiRoomsQuota = quotaManager.update(jitsiRoomsQuota); try { - return jitsiRoomManager.create(jitsiRoom.getOwner(), jitsiRoom.getRoom(), - jitsiRoom.getStarts(), jitsiRoom.getModerationStarts(), jitsiRoom.getExpires()); + return jitsiRoomManager.create(jitsiRoom.getOwner(), jitsiRoom.getRoom(), jitsiRoom.getStarts(), + jitsiRoom.getModerationStarts(), jitsiRoom.getExpires()); } catch (JOSEException e) { jitsiRoomsQuota.setValue(jitsiRoomsQuota.getValue() - 1); jitsiRoomsQuota = quotaManager.update(jitsiRoomsQuota); @@ -182,14 +181,12 @@ public class JitsiRoomController extends BaseController { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - if (!permissionManager.hasPermission(getCurrentUserId(), - ShortenedUrlPermissions.URL_SHORTENER) + if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER) || !permissionManager.isFullUser(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(), - ShortenedUrlQuotas.URL_SHORTENER); + Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(), ShortenedUrlQuotas.URL_SHORTENER); if (shortenedUrlsQuota == null || shortenedUrlsQuota.getValue() < 1) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomManagementController.java b/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomManagementController.java index 71d765f..28bacd1 100644 --- a/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomManagementController.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/controller/JitsiRoomManagementController.java @@ -80,13 +80,12 @@ public class JitsiRoomManagementController extends BaseController { /** * Delete jitsi room. * - * @param id the id + * @param id the id * @param quota the quota */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/{id}") - public void deleteJitsiRoom(@PathVariable("id") Long id, - @RequestParam("quota") Optional quota) { + public void deleteJitsiRoom(@PathVariable("id") Long id, @RequestParam("quota") Optional quota) { JitsiRoom jitsiRoom = jitsiRoomManager.get(id); if (jitsiRoom == null) { @@ -104,8 +103,7 @@ public class JitsiRoomManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/all/{owner}") - public void deleteAll(@PathVariable("owner") Long owner, - @RequestParam("quota") Optional quota) { + public void deleteAll(@PathVariable("owner") Long owner, @RequestParam("quota") Optional quota) { jitsiRoomManager.deleteAll(owner, quota.isPresent() && quota.get().booleanValue()); } diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/controller/validation/JitsiRoomValidator.java b/jitsi/src/main/java/de/bstly/we/jitsi/controller/validation/JitsiRoomValidator.java index 31e1e36..878a5ab 100644 --- a/jitsi/src/main/java/de/bstly/we/jitsi/controller/validation/JitsiRoomValidator.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/controller/validation/JitsiRoomValidator.java @@ -67,9 +67,9 @@ public class JitsiRoomValidator implements Validator { /** * Validate. * - * @param owner the owner + * @param owner the owner * @param roomName the room name - * @param errors the errors + * @param errors the errors */ public void validate(Long owner, String roomName, Errors errors) { if (owner == null) { @@ -97,14 +97,12 @@ public class JitsiRoomValidator implements Validator { * Validate room. * * @param roomName the room name - * @param errors the errors + * @param errors the errors */ public void validateRoom(String roomName, Errors errors) { - for (String systemRoomName : systemPropertyManager.get(RESERVED_JITSI_ROOMS, "") - .split(",")) { - if (StringUtils.hasText(systemRoomName) - && (roomName.toLowerCase().equals(systemRoomName) - || roomName.toLowerCase().matches(systemRoomName))) { + for (String systemRoomName : systemPropertyManager.get(RESERVED_JITSI_ROOMS, "").split(",")) { + if (StringUtils.hasText(systemRoomName) && (roomName.toLowerCase().equals(systemRoomName) + || roomName.toLowerCase().matches(systemRoomName))) { errors.rejectValue("room", "NOT_VALID"); return; } @@ -115,7 +113,7 @@ public class JitsiRoomValidator implements Validator { * Validate expiry. * * @param jitsiRoom the jitsi room - * @param errors the errors + * @param errors the errors */ public void validateExpiry(JitsiRoom jitsiRoom, Errors errors) { @@ -124,13 +122,11 @@ public class JitsiRoomValidator implements Validator { } if (jitsiRoom.getModerationStarts() != null) { - jitsiRoom.setModerationStarts( - InstantHelper.truncate(jitsiRoom.getModerationStarts(), ChronoUnit.SECONDS)); + jitsiRoom.setModerationStarts(InstantHelper.truncate(jitsiRoom.getModerationStarts(), ChronoUnit.SECONDS)); } if (jitsiRoom.getExpires() != null) { - jitsiRoom - .setExpires(InstantHelper.truncate(jitsiRoom.getExpires(), ChronoUnit.SECONDS)); + jitsiRoom.setExpires(InstantHelper.truncate(jitsiRoom.getExpires(), ChronoUnit.SECONDS)); } // no moderation start without start @@ -151,8 +147,7 @@ public class JitsiRoomValidator implements Validator { // exlude self .and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId())) // expires null or after now - .and(qJitsiRoom.expires.isNull() - .or(qJitsiRoom.expires.after(Instant.now()))))) { + .and(qJitsiRoom.expires.isNull().or(qJitsiRoom.expires.after(Instant.now()))))) { errors.rejectValue("room", "NOT_VALID"); } } else @@ -164,8 +159,7 @@ public class JitsiRoomValidator implements Validator { // expires null or after now .and(qJitsiRoom.expires.isNull().or(qJitsiRoom.expires.after(Instant.now()))) // start null or before expires - .and(qJitsiRoom.starts.isNull() - .or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) { + .and(qJitsiRoom.starts.isNull().or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) { errors.rejectValue("expires", "NOT_VALID"); } } @@ -176,27 +170,27 @@ public class JitsiRoomValidator implements Validator { .and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId())) // expires null or after room start .and(qJitsiRoom.expires.isNull() - .or(qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null - ? jitsiRoom.getModerationStarts() - : jitsiRoom.getStarts()))))) { + .or(qJitsiRoom.expires + .after(jitsiRoom.getModerationStarts() != null ? jitsiRoom.getModerationStarts() + : jitsiRoom.getStarts()))))) { errors.rejectValue("starts", "NOT_VALID"); } } else // expiry + start if (jitsiRoom.getExpires() != null && jitsiRoom.getStarts() != null) { - if (jitsiRoom.getStarts().isAfter(jitsiRoom.getExpires()) - || jitsiRoomRepository.exists(qJitsiRoom.room.eq(jitsiRoom.getRoom()) - // exlude self - .and(qJitsiRoom.id - .ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId())) - // expires null or after room start - .and(qJitsiRoom.expires.isNull().or( - qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null - ? jitsiRoom.getModerationStarts() - : jitsiRoom.getStarts()))) - // start null or before expires - .and(qJitsiRoom.starts.isNull() - .or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) { + if (jitsiRoom.getStarts().isAfter(jitsiRoom + .getExpires()) || jitsiRoomRepository.exists( + qJitsiRoom.room.eq(jitsiRoom.getRoom()) + // exlude self + .and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId())) + // expires null or after room start + .and(qJitsiRoom.expires.isNull() + .or(qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null + ? jitsiRoom.getModerationStarts() + : jitsiRoom.getStarts()))) + // start null or before expires + .and(qJitsiRoom.starts.isNull() + .or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) { errors.rejectValue("starts", "NOT_VALID"); errors.rejectValue("expires", "NOT_VALID"); } diff --git a/jitsi/src/main/java/de/bstly/we/jitsi/repository/JitsiRoomRepository.java b/jitsi/src/main/java/de/bstly/we/jitsi/repository/JitsiRoomRepository.java index 270e490..5bc138f 100755 --- a/jitsi/src/main/java/de/bstly/we/jitsi/repository/JitsiRoomRepository.java +++ b/jitsi/src/main/java/de/bstly/we/jitsi/repository/JitsiRoomRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.jitsi.model.JitsiRoom; * The Interface JitsiRoomRepository. */ @Repository -public interface JitsiRoomRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface JitsiRoomRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxController.java b/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxController.java index 5afbaf9..ef72a3a 100644 --- a/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxController.java +++ b/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxController.java @@ -105,7 +105,7 @@ public class JukeboxController extends BaseController { * * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAuthenticated()") @GetMapping @@ -129,11 +129,11 @@ public class JukeboxController extends BaseController { /** * Search. * - * @param query the query - * @param offset the offset + * @param query the query + * @param offset the offset * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAuthenticated()") @GetMapping("/search") @@ -165,7 +165,7 @@ public class JukeboxController extends BaseController { * * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAuthenticated()") @GetMapping("/current") @@ -197,10 +197,10 @@ public class JukeboxController extends BaseController { /** * Last. * - * @param limit the limit + * @param limit the limit * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAuthenticated()") @GetMapping("/last") diff --git a/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxManagementController.java b/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxManagementController.java index 1a8e1b4..834625c 100644 --- a/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxManagementController.java +++ b/jukebox/src/main/java/de/bstly/we/jukebox/controller/JukeboxManagementController.java @@ -89,7 +89,7 @@ public class JukeboxManagementController extends BaseController { * @param response the response * @return the status * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping() @@ -102,11 +102,11 @@ public class JukeboxManagementController extends BaseController { /** * Search. * - * @param query the query - * @param offset the offset + * @param query the query + * @param offset the offset * @param response the response * @throws JsonIOException the json IO exception - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/search") diff --git a/jwt/pom.xml b/jwt/pom.xml index 230f1d2..dcb7919 100644 --- a/jwt/pom.xml +++ b/jwt/pom.xml @@ -21,6 +21,7 @@ com.nimbusds nimbus-jose-jwt + 9.21 diff --git a/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtKeyManager.java b/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtKeyManager.java index b7a12b7..b54364a 100644 --- a/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtKeyManager.java +++ b/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtKeyManager.java @@ -59,7 +59,7 @@ public class JwtKeyManager { /** * Gets the jwk set. * - * @param name the name + * @param name the name * @param createDefault the create default * @return the jwk set */ @@ -91,14 +91,14 @@ public class JwtKeyManager { /** * Gets the latest. * - * @param name the name + * @param name the name * @param createDefault the create default * @return the latest */ @Transactional public JwtKey getLatest(String name, boolean createDefault) { - List jwtKeys = Lists.newArrayList(jwtKeyRepository.findAll(qJwtKey.name.eq(name), - PageRequest.of(0, 1, Sort.by(Order.desc("created"))))); + List jwtKeys = Lists.newArrayList( + jwtKeyRepository.findAll(qJwtKey.name.eq(name), PageRequest.of(0, 1, Sort.by(Order.desc("created"))))); JwtKey jwtKey = null; @@ -107,8 +107,8 @@ public class JwtKeyManager { } if (jwtKey != null) { - if (jwtKey.getLifetime() == -1L || jwtKey.getExpires() - .isAfter(Instant.now().plus(jwtKey.getLifetime(), ChronoUnit.SECONDS))) { + if (jwtKey.getLifetime() == -1L + || jwtKey.getExpires().isAfter(Instant.now().plus(jwtKey.getLifetime(), ChronoUnit.SECONDS))) { return jwtKey; } @@ -143,16 +143,17 @@ public class JwtKeyManager { /** * Gets the by created. * - * @param name the name + * @param name the name * @param created the created * @return the by created */ @Transactional public JwtKey getByCreated(String name, Instant created) { return jwtKeyRepository - .findOne(qJwtKey.name.eq(name) - .and(qJwtKey.created.before(created) - .and(qJwtKey.lifetime.eq(-1L).or(qJwtKey.expires.after(created))))) + .findOne( + qJwtKey.name.eq(name) + .and(qJwtKey.created.before(created) + .and(qJwtKey.lifetime.eq(-1L).or(qJwtKey.expires.after(created))))) .orElse(null); } @@ -171,8 +172,8 @@ public class JwtKeyManager { try { KeyType keyType = KeyType.parse(jwtKey.getKeyType()); if (KeyType.EC.equals(keyType)) { - jwk = new ECKeyGenerator(Curve.parse(jwtKey.getKeyParameter())) - .keyUse(KeyUse.parse(jwtKey.getKeyUse())).keyID(keyID).generate(); + jwk = new ECKeyGenerator(Curve.parse(jwtKey.getKeyParameter())).keyUse(KeyUse.parse(jwtKey.getKeyUse())) + .keyID(keyID).generate(); } else if (KeyType.OCT.equals(keyType)) { jwk = new OctetKeyPairGenerator(Curve.parse(jwtKey.getKeyParameter())) .keyUse(KeyUse.parse(jwtKey.getKeyUse())).keyID(keyID).generate(); @@ -236,7 +237,7 @@ public class JwtKeyManager { /** * Gets the jws algorithm. * - * @param name the name + * @param name the name * @param createDefault the create default * @return the jws algorithm */ diff --git a/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtUserManager.java b/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtUserManager.java index 5fd08fa..b3dce19 100644 --- a/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtUserManager.java +++ b/jwt/src/main/java/de/bstly/we/jwt/businesslogic/JwtUserManager.java @@ -39,15 +39,14 @@ public class JwtUserManager { /** * Creates the signed jwt. * - * @param userId the user id - * @param data the data - * @param issuer the issuer + * @param userId the user id + * @param data the data + * @param issuer the issuer * @param lifetime the lifetime * @return the signed JWT * @throws JOSEException the JOSE exception */ - public SignedJWT createSignedJwt(Long userId, Object data, String issuer, Long lifetime) - throws JOSEException { + public SignedJWT createSignedJwt(Long userId, Object data, String issuer, Long lifetime) throws JOSEException { User user = userManager.get(userId); if (user == null) { @@ -61,8 +60,7 @@ public class JwtUserManager { claimsSetBuilder.issueTime(new Date()); if (lifetime != null && lifetime > 0) { - claimsSetBuilder - .expirationTime(Date.from(Instant.now().plus(lifetime, ChronoUnit.SECONDS))); + claimsSetBuilder.expirationTime(Date.from(Instant.now().plus(lifetime, ChronoUnit.SECONDS))); } if (data != null) { @@ -71,8 +69,7 @@ public class JwtUserManager { JwtKey jwtKey = jwtKeyManager.getLatest(JWT_USER_DATA_KEY_NAME, true); - JWSHeader.Builder headerBuilder = new JWSHeader.Builder( - jwtKeyManager.getJwsAlgorithm(jwtKey)); + JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey)); headerBuilder.keyID(jwtKey.getKeyID()); headerBuilder.type(JOSEObjectType.JWT); @@ -86,7 +83,7 @@ public class JwtUserManager { * * @param jwt the jwt * @return true, if successful - * @throws JOSEException the JOSE exception + * @throws JOSEException the JOSE exception * @throws ParseException the parse exception */ public boolean verify(SignedJWT jwt) throws JOSEException, ParseException { diff --git a/jwt/src/main/java/de/bstly/we/jwt/controller/JwtUserDataController.java b/jwt/src/main/java/de/bstly/we/jwt/controller/JwtUserDataController.java index 580735b..03fef93 100644 --- a/jwt/src/main/java/de/bstly/we/jwt/controller/JwtUserDataController.java +++ b/jwt/src/main/java/de/bstly/we/jwt/controller/JwtUserDataController.java @@ -50,17 +50,13 @@ public class JwtUserDataController extends BaseController { public String createSignedJwtAuth(HttpServletRequest request) { String issuer = jwtUserIssuer; if (!StringUtils.hasText(issuer)) { - issuer = request.getScheme() - + "://" - + request.getServerName(); + issuer = request.getScheme() + "://" + request.getServerName(); if (request.getServerPort() != 443 && request.getServerPort() != 80) { - issuer += ":" - + request.getServerPort(); + issuer += ":" + request.getServerPort(); } } try { - return jwtUserDataManager.createSignedJwt(getCurrentUserId(), null, issuer, 120L) - .serialize(); + return jwtUserDataManager.createSignedJwt(getCurrentUserId(), null, issuer, 120L).serialize(); } catch (JOSEException e) { e.printStackTrace(); throw new EntityResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR); @@ -70,7 +66,7 @@ public class JwtUserDataController extends BaseController { /** * Creates the signed jwt. * - * @param data the data + * @param data the data * @param request the request * @return the string */ @@ -79,17 +75,13 @@ public class JwtUserDataController extends BaseController { public String createSignedJwt(@RequestBody Object data, HttpServletRequest request) { String issuer = jwtUserIssuer; if (!StringUtils.hasText(issuer)) { - issuer = request.getScheme() - + "://" - + request.getServerName(); + issuer = request.getScheme() + "://" + request.getServerName(); if (request.getServerPort() != 443 && request.getServerPort() != 80) { - issuer += ":" - + request.getServerPort(); + issuer += ":" + request.getServerPort(); } } try { - return jwtUserDataManager.createSignedJwt(getCurrentUserId(), data, issuer, -1L) - .serialize(); + return jwtUserDataManager.createSignedJwt(getCurrentUserId(), data, issuer, -1L).serialize(); } catch (JOSEException e) { e.printStackTrace(); throw new EntityResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR); @@ -100,13 +92,12 @@ public class JwtUserDataController extends BaseController { * Verfiy. * * @param serialized the serialized - * @param request the request - * @param response the response + * @param request the request + * @param response the response * @return the object */ @PostMapping("verify") - public Object verfiy(@RequestBody String serialized, HttpServletRequest request, - HttpServletResponse response) { + public Object verfiy(@RequestBody String serialized, HttpServletRequest request, HttpServletResponse response) { try { SignedJWT signedJwt = SignedJWT.parse(serialized); if (jwtUserDataManager.verify(signedJwt)) { diff --git a/jwt/src/main/java/de/bstly/we/jwt/repository/JwtKeyRepository.java b/jwt/src/main/java/de/bstly/we/jwt/repository/JwtKeyRepository.java index 4be678f..5d68211 100644 --- a/jwt/src/main/java/de/bstly/we/jwt/repository/JwtKeyRepository.java +++ b/jwt/src/main/java/de/bstly/we/jwt/repository/JwtKeyRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.jwt.model.JwtKey; * The Interface JwtKeyRepository. */ @Repository -public interface JwtKeyRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface JwtKeyRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/membership/src/main/java/de/bstly/we/membership/businesslogic/MembershipManager.java b/membership/src/main/java/de/bstly/we/membership/businesslogic/MembershipManager.java index c5f6d19..4abc4be 100644 --- a/membership/src/main/java/de/bstly/we/membership/businesslogic/MembershipManager.java +++ b/membership/src/main/java/de/bstly/we/membership/businesslogic/MembershipManager.java @@ -60,17 +60,15 @@ public class MembershipManager { * Generate membership ids. */ public void generateMembershipIds() { - String membershipItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); + String membershipItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); - int membershipInternalIdQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); + int membershipInternalIdQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); int membershipIdQuestion = systemPropertyManager .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ID_QUESTION, 0); - if (!StringUtils.hasText(membershipItemId) || membershipInternalIdQuestion == 0 - || membershipIdQuestion == 0) { + if (!StringUtils.hasText(membershipItemId) || membershipInternalIdQuestion == 0 || membershipIdQuestion == 0) { logger.warn("Required system properties for 'generateMembershipIds' not set!"); return; } @@ -81,8 +79,8 @@ public class MembershipManager { queryParams.add("order__status", "p"); List orderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryParams, Lists.newArrayList()); Map newMembershipPositions = new TreeMap(); @@ -106,23 +104,20 @@ public class MembershipManager { } if (!hasInternalMembershipId) { - newMembershipPositions.put(pretixManager.getLastPaymentDateForOrder( - orderPosition.get("order").getAsString()), orderPosition); + newMembershipPositions.put( + pretixManager.getLastPaymentDateForOrder(orderPosition.get("order").getAsString()), + orderPosition); } else { boolean writeMembershipId = true; - JsonObject membershipIdAnswer = getAnswerObject(orderPosition, - membershipIdQuestion); + JsonObject membershipIdAnswer = getAnswerObject(orderPosition, membershipIdQuestion); if (membershipIdAnswer != null) { int membershipId = Integer.valueOf(membershipIdAnswer.get("answer").getAsInt()); if (internalMembershipId == membershipId) { writeMembershipId = false; - logger.trace("Order '" - + orderPosition.get("order").getAsString() - + "' already processed, membership id: '" - + membershipId - + "'"); + logger.trace("Order '" + orderPosition.get("order").getAsString() + + "' already processed, membership id: '" + membershipId + "'"); } } @@ -140,22 +135,17 @@ public class MembershipManager { JsonObject payload = new JsonObject(); payload.add("answers", answers); - logger.debug("Write membershipId for '" - + orderPosition.get("order").getAsString() - + "': " + logger.debug("Write membershipId for '" + orderPosition.get("order").getAsString() + "': " + internalMembershipId); - pretixManager.request( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", - pretixManager.getOrganizer(), pretixManager.getEvent(), - orderPosition.get("id").getAsString()), - HttpMethod.PATCH, payload); + pretixManager.request(String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", + pretixManager.getOrganizer(), pretixManager.getEvent(), + orderPosition.get("id").getAsString()), HttpMethod.PATCH, payload); } } } - Iterator> iterator = newMembershipPositions.entrySet() - .iterator(); + Iterator> iterator = newMembershipPositions.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); JsonObject orderPosition = entry.getValue(); @@ -182,17 +172,13 @@ public class MembershipManager { payload.add("answers", answers); - logger.debug("Create membershipId for '" - + orderPosition.get("order").getAsString() - + "': " - + nextMembershipId); + logger.debug( + "Create membershipId for '" + orderPosition.get("order").getAsString() + "': " + nextMembershipId); - pretixManager - .request( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", - pretixManager.getOrganizer(), pretixManager.getEvent(), - orderPosition.get("id").getAsString()), - HttpMethod.PATCH, payload); + pretixManager.request( + String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", pretixManager.getOrganizer(), + pretixManager.getEvent(), orderPosition.get("id").getAsString()), + HttpMethod.PATCH, payload); nextMembershipId++; } @@ -203,17 +189,16 @@ public class MembershipManager { */ public void activeMemberships() { - String membershipItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); + String membershipItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); - String membershipFeeItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, ""); + String membershipFeeItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, + ""); - int membershipInternalIdQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); + int membershipInternalIdQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); - int membershipFeeReferenceQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REFERENCE_QUESTION, 0); + int membershipFeeReferenceQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REFERENCE_QUESTION, 0); int membershipActiveQuestion = systemPropertyManager .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ACTIVE_QUESTION, 0); @@ -231,23 +216,22 @@ public class MembershipManager { queryParams.add("order__status", "p"); List membershipOrderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryParams, Lists.newArrayList()); queryParams.remove("item"); queryParams.add("item", membershipFeeItemId); List membershipfeeOrderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryParams, Lists.newArrayList()); Map> membershipfeeOrderPositionMap = Maps.newHashMap(); for (JsonObject membershipFeeOrderPosition : membershipfeeOrderPositions) { - int membershipReference = getNumberAnswer(membershipFeeOrderPosition, - membershipFeeReferenceQuestion); + int membershipReference = getNumberAnswer(membershipFeeOrderPosition, membershipFeeReferenceQuestion); if (!membershipfeeOrderPositionMap.containsKey(membershipReference)) { membershipfeeOrderPositionMap.put(membershipReference, Lists.newArrayList()); } @@ -260,15 +244,12 @@ public class MembershipManager { answers = membershipOrderPosition.getAsJsonArray("answers"); } - JsonObject membershipActiveAnswer = getAnswerObject(membershipOrderPosition, - membershipActiveQuestion); - int membershipId = getNumberAnswer(membershipOrderPosition, - membershipInternalIdQuestion); + JsonObject membershipActiveAnswer = getAnswerObject(membershipOrderPosition, membershipActiveQuestion); + int membershipId = getNumberAnswer(membershipOrderPosition, membershipInternalIdQuestion); if (membershipId == 0) { - logger.warn("No membership number found for '" - + membershipOrderPosition.get("order").getAsString() - + "'!"); + logger.warn( + "No membership number found for '" + membershipOrderPosition.get("order").getAsString() + "'!"); continue; } @@ -276,9 +257,7 @@ public class MembershipManager { .getLastPaymentDateForOrder(membershipOrderPosition.get("order").getAsString()); if (membershipStart == null) { - logger.warn("No last payment found for '" - + membershipOrderPosition.get("order").getAsString() - + "'!"); + logger.warn("No last payment found for '" + membershipOrderPosition.get("order").getAsString() + "'!"); continue; } @@ -288,8 +267,8 @@ public class MembershipManager { years += membershipfeeOrderPositionMap.get(membershipId).size(); } - Instant active = InstantHelper.truncate( - InstantHelper.plus(membershipStart, years, ChronoUnit.YEARS), ChronoUnit.YEARS); + Instant active = InstantHelper.truncate(InstantHelper.plus(membershipStart, years, ChronoUnit.YEARS), + ChronoUnit.YEARS); String activeAnswer = pretixDateFormat.format(Date.from(active)); @@ -308,21 +287,15 @@ public class MembershipManager { JsonObject payload = new JsonObject(); payload.add("answers", answers); - pretixManager.request( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", - pretixManager.getOrganizer(), pretixManager.getEvent(), - membershipOrderPosition.get("id").getAsString()), - HttpMethod.PATCH, payload); + pretixManager.request(String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", + pretixManager.getOrganizer(), pretixManager.getEvent(), + membershipOrderPosition.get("id").getAsString()), HttpMethod.PATCH, payload); - logger.debug("Write active state for '" - + membershipOrderPosition.get("order").getAsString() - + "': " + logger.debug("Write active state for '" + membershipOrderPosition.get("order").getAsString() + "': " + activeAnswer); } else { - logger.trace("Order active state for '" - + membershipOrderPosition.get("order").getAsString() - + "' already set: " - + activeAnswer); + logger.trace("Order active state for '" + membershipOrderPosition.get("order").getAsString() + + "' already set: " + activeAnswer); } } } @@ -332,17 +305,16 @@ public class MembershipManager { */ public void createMembershipExtension() { - String membershipItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); + String membershipItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, ""); - String membershipFeeItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, ""); + String membershipFeeItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, + ""); - int membershipInternalIdQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); + int membershipInternalIdQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_INTERNAL_ID_QUESTION, 0); - int membershipFeeReferenceQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REFERENCE_QUESTION, 0); + int membershipFeeReferenceQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REFERENCE_QUESTION, 0); int membershipFeeCodeQuestion = systemPropertyManager .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_CODE_QUESTION, 0); @@ -356,20 +328,19 @@ public class MembershipManager { int membershipfeeReminderDays = systemPropertyManager .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REMINDER_DAYS, 0); - int membershipfeeReminderQuestion = systemPropertyManager.getInteger( - PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REMINDER_QUESTION, 0); + int membershipfeeReminderQuestion = systemPropertyManager + .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_REMINDER_QUESTION, 0); - boolean orderSendmail = systemPropertyManager - .getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_SENDMAIL, false); - boolean orderTestmode = systemPropertyManager - .getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_TESTMODE, true); - boolean orderSimulate = systemPropertyManager - .getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_SIMULATE, false); + boolean orderSendmail = systemPropertyManager.getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_SENDMAIL, + false); + boolean orderTestmode = systemPropertyManager.getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_TESTMODE, + true); + boolean orderSimulate = systemPropertyManager.getBoolean(PretixManager.SYSTEM_PROPERTY_PRETIX_ORDER_SIMULATE, + false); if (!StringUtils.hasText(membershipItemId) || !StringUtils.hasText(membershipFeeItemId) || membershipInternalIdQuestion == 0 || membershipFeeReferenceQuestion == 0 - || membershipFeeCodeQuestion == 0 || membershipActiveQuestion == 0 - || membershipfeeOrderDays == 0) { + || membershipFeeCodeQuestion == 0 || membershipActiveQuestion == 0 || membershipfeeOrderDays == 0) { logger.warn("Required system properties for 'createMembershipExtension' not set!"); return; } @@ -380,8 +351,8 @@ public class MembershipManager { queryMembershipParams.add("order__status", "p"); List membershipOrderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryMembershipParams, Lists.newArrayList()); List expireMemberships = Lists.newArrayList(); @@ -389,15 +360,11 @@ public class MembershipManager { for (JsonObject membershipOrderPosition : membershipOrderPositions) { Instant active = getDateAnswer(membershipOrderPosition, membershipActiveQuestion); if (active.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS)) - && InstantHelper.minus(active, membershipfeeOrderDays, ChronoUnit.DAYS) - .isBefore(Instant.now())) { + && InstantHelper.minus(active, membershipfeeOrderDays, ChronoUnit.DAYS).isBefore(Instant.now())) { expireMemberships.add(membershipOrderPosition); } else { - logger.trace("Membership '" - + membershipOrderPosition.get("order").getAsString() - + "' not expiring in next " - + membershipfeeOrderDays - + " days."); + logger.trace("Membership '" + membershipOrderPosition.get("order").getAsString() + + "' not expiring in next " + membershipfeeOrderDays + " days."); } } @@ -407,49 +374,43 @@ public class MembershipManager { queryMembershipFeeParams.add("order__status__in", "n,e,c"); List membershipfeeOrderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryMembershipFeeParams, Lists.newArrayList()); Map> membershipfeeOrderPositionMap = Maps.newHashMap(); for (JsonObject membershipfeeOrderPosition : membershipfeeOrderPositions) { - int membershipReference = getNumberAnswer(membershipfeeOrderPosition, - membershipFeeReferenceQuestion); + int membershipReference = getNumberAnswer(membershipfeeOrderPosition, membershipFeeReferenceQuestion); JsonObject membershipFeeOrder = pretixManager .getOrder(membershipfeeOrderPosition.get("order").getAsString()); - Instant membershipFeeOrderDatetime = OffsetDateTime - .parse(membershipFeeOrder.get("datetime").getAsString()).toInstant(); + Instant membershipFeeOrderDatetime = OffsetDateTime.parse(membershipFeeOrder.get("datetime").getAsString()) + .toInstant(); - if (membershipFeeOrderDatetime - .isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS))) { + if (membershipFeeOrderDatetime.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS))) { if (!membershipfeeOrderPositionMap.containsKey(membershipReference)) { membershipfeeOrderPositionMap.put(membershipReference, Lists.newArrayList()); } - membershipfeeOrderPositionMap.get(membershipReference) - .add(membershipfeeOrderPosition); + membershipfeeOrderPositionMap.get(membershipReference).add(membershipfeeOrderPosition); } } for (JsonObject membershipOrderPosition : expireMemberships) { - int membershipId = getNumberAnswer(membershipOrderPosition, - membershipInternalIdQuestion); + int membershipId = getNumberAnswer(membershipOrderPosition, membershipInternalIdQuestion); Instant active = getDateAnswer(membershipOrderPosition, membershipActiveQuestion); if (membershipId == 0) { - logger.warn("No membership number found for '" - + membershipOrderPosition.get("order").getAsString() - + "'!"); + logger.warn( + "No membership number found for '" + membershipOrderPosition.get("order").getAsString() + "'!"); continue; } if (!membershipfeeOrderPositionMap.containsKey(membershipId) || membershipfeeOrderPositionMap.get(membershipId).isEmpty()) { - JsonObject membershipOrder = pretixManager - .getOrder(membershipOrderPosition.get("order").getAsString()); + JsonObject membershipOrder = pretixManager.getOrder(membershipOrderPosition.get("order").getAsString()); JsonObject membershipFeeOrder = new JsonObject(); membershipFeeOrder.add("email", membershipOrder.get("email")); @@ -462,8 +423,7 @@ public class MembershipManager { JsonArray membershipFeeOrderPositionAnswers = new JsonArray(); JsonObject membershipFeeReferenceAnswer = new JsonObject(); - membershipFeeReferenceAnswer.addProperty("question", - membershipFeeReferenceQuestion); + membershipFeeReferenceAnswer.addProperty("question", membershipFeeReferenceQuestion); membershipFeeReferenceAnswer.add("options", new JsonArray()); membershipFeeReferenceAnswer.add("option_identifiers", new JsonArray()); membershipFeeReferenceAnswer.addProperty("answer", membershipId); @@ -473,8 +433,7 @@ public class MembershipManager { membershipFeeCodeAnswer.addProperty("question", membershipFeeCodeQuestion); membershipFeeCodeAnswer.add("options", new JsonArray()); membershipFeeCodeAnswer.add("option_identifiers", new JsonArray()); - membershipFeeCodeAnswer.addProperty("answer", - membershipOrderPosition.get("order").getAsString()); + membershipFeeCodeAnswer.addProperty("answer", membershipOrderPosition.get("order").getAsString()); membershipFeeOrderPositionAnswers.add(membershipFeeCodeAnswer); membershipFeeOrderPosition.add("answers", membershipFeeOrderPositionAnswers); @@ -484,19 +443,15 @@ public class MembershipManager { membershipFeeOrder.add("locale", membershipOrder.get("locale")); membershipFeeOrder.add("positions", membershipFeeOrderPositions); - if (membershipOrder.has("payments") - && membershipOrder.getAsJsonArray("payments").size() > 0) { - JsonObject payment = membershipOrder.getAsJsonArray("payments").get(0) - .getAsJsonObject(); + if (membershipOrder.has("payments") && membershipOrder.getAsJsonArray("payments").size() > 0) { + JsonObject payment = membershipOrder.getAsJsonArray("payments").get(0).getAsJsonObject(); membershipFeeOrder.add("payment_provider", payment.get("provider")); } Instant expires = InstantHelper.minus(InstantHelper.truncate( - InstantHelper.plus(Instant.now(), 1, ChronoUnit.YEARS), ChronoUnit.YEARS), - 1, ChronoUnit.DAYS); + InstantHelper.plus(Instant.now(), 1, ChronoUnit.YEARS), ChronoUnit.YEARS), 1, ChronoUnit.DAYS); - membershipFeeOrder.addProperty("expires", - pretixDateFormat.format(Date.from(expires))); + membershipFeeOrder.addProperty("expires", pretixDateFormat.format(Date.from(expires))); membershipFeeOrder.addProperty("send_email", orderSendmail); membershipFeeOrder.addProperty("testmode", orderTestmode); membershipFeeOrder.addProperty("simulate", orderSimulate); @@ -505,20 +460,16 @@ public class MembershipManager { JsonObject expire = new JsonObject(); expire.addProperty("expires", pretixDateFormat.format(Date.from(expires))); - membershipFeeOrder = pretixManager - .extendOrder(membershipFeeOrder.get("code").getAsString(), expire); + membershipFeeOrder = pretixManager.extendOrder(membershipFeeOrder.get("code").getAsString(), expire); - logger.debug("Create membership fee order: " - + membershipFeeOrder.toString()); + logger.debug("Create membership fee order: " + membershipFeeOrder.toString()); } else // send reminder mail for membership fee order if (membershipfeeReminderDays > 0 && membershipfeeReminderQuestion > 0 - && active.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS)) - && InstantHelper.minus(active, membershipfeeReminderDays, ChronoUnit.DAYS) - .isBefore(Instant.now())) { + && active.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS)) && InstantHelper + .minus(active, membershipfeeReminderDays, ChronoUnit.DAYS).isBefore(Instant.now())) { - for (JsonObject membershipfeeOrderPosition : membershipfeeOrderPositionMap - .get(membershipId)) { + for (JsonObject membershipfeeOrderPosition : membershipfeeOrderPositionMap.get(membershipId)) { JsonObject membershipFeeOrder = pretixManager .getOrder(membershipfeeOrderPosition.get("order").getAsString()); @@ -526,17 +477,15 @@ public class MembershipManager { if (!"c".equals(membershipFeeOrder.get("status").getAsString())) { JsonArray membershipfeeAnswers = new JsonArray(); if (membershipfeeOrderPosition.has("answers")) { - membershipfeeAnswers = membershipfeeOrderPosition - .getAsJsonArray("answers"); + membershipfeeAnswers = membershipfeeOrderPosition.getAsJsonArray("answers"); } - JsonObject membershipReminderAnswer = getAnswerObject( - membershipfeeOrderPosition, membershipfeeReminderQuestion); + JsonObject membershipReminderAnswer = getAnswerObject(membershipfeeOrderPosition, + membershipfeeReminderQuestion); if (membershipReminderAnswer == null) { membershipReminderAnswer = new JsonObject(); - membershipReminderAnswer.addProperty("question", - membershipfeeReminderQuestion); + membershipReminderAnswer.addProperty("question", membershipfeeReminderQuestion); membershipReminderAnswer.add("options", new JsonArray()); membershipReminderAnswer.add("option_identifiers", new JsonArray()); membershipReminderAnswer.addProperty("answer", "false"); @@ -546,15 +495,13 @@ public class MembershipManager { if (!membershipReminderAnswer.get("answer").getAsBoolean()) { membershipReminderAnswer.addProperty("answer", "true"); - pretixManager.sendEmail( - membershipfeeOrderPosition.get("order").getAsString()); + pretixManager.sendEmail(membershipfeeOrderPosition.get("order").getAsString()); JsonObject payload = new JsonObject(); payload.add("answers", membershipfeeAnswers); pretixManager.request( - String.format( - "/api/v1/organizers/%s/events/%s/orderpositions/%s/", + String.format("/api/v1/organizers/%s/events/%s/orderpositions/%s/", pretixManager.getOrganizer(), pretixManager.getEvent(), membershipfeeOrderPosition.get("id").getAsString()), HttpMethod.PATCH, payload); @@ -563,18 +510,15 @@ public class MembershipManager { + membershipfeeOrderPosition.get("order").getAsString()); } else { logger.debug("Reminder for Membership fee order of'" - + membershipfeeOrderPosition.get("order").getAsString() - + "' already created."); + + membershipfeeOrderPosition.get("order").getAsString() + "' already created."); } } else { - logger.debug("Membership fee order for'" - + membershipfeeOrderPosition.get("order").getAsString() + logger.debug("Membership fee order for'" + membershipfeeOrderPosition.get("order").getAsString() + "' is canceled, no reminder."); } } } else { - logger.debug("Membership fee order for '" - + membershipOrderPosition.get("order").getAsString() + logger.debug("Membership fee order for '" + membershipOrderPosition.get("order").getAsString() + "' already created, no reminder."); } @@ -585,8 +529,8 @@ public class MembershipManager { * Calculate price. */ public void calculatePrice() { - int membershipItemId = systemPropertyManager - .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, 0); + int membershipItemId = systemPropertyManager.getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, + 0); String discountPeriod = systemPropertyManager .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_DISCOUNT_PERIOD, ""); @@ -638,8 +582,7 @@ public class MembershipManager { } if (applyDefault && defaultVariationId > 0) { - pretixManager.updateVariation(membershipItemId, defaultVariationId, - defaultVariation); + pretixManager.updateVariation(membershipItemId, defaultVariationId, defaultVariation); } } catch (DateTimeParseException e) { @@ -650,13 +593,12 @@ public class MembershipManager { /** * Membership csv export. * - * @param writer the writer + * @param writer the writer * @param includeInactive the include inactive * @return the json array */ public JsonArray membershipCsvExport(Writer writer, boolean includeInactive) { - String membershipItemId = systemPropertyManager - .get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"); + String membershipItemId = systemPropertyManager.get(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"); int membershipActiveQuestion = systemPropertyManager .getInteger(PretixManager.SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ACTIVE_QUESTION, 0); @@ -670,18 +612,15 @@ public class MembershipManager { List answerHeaders = Lists.newArrayList(); List orderPositions = fetchAllOrderPositions( - String.format("/api/v1/organizers/%s/events/%s/orderpositions/", - pretixManager.getOrganizer(), pretixManager.getEvent()), + String.format("/api/v1/organizers/%s/events/%s/orderpositions/", pretixManager.getOrganizer(), + pretixManager.getEvent()), queryParams, Lists.newArrayList()); for (JsonObject orderPosition : orderPositions) { - JsonObject order = pretixManager - .request( - String.format("/api/v1/organizers/%s/events/%s/orders/%s/", - pretixManager.getOrganizer(), pretixManager.getEvent(), - orderPosition.get("order").getAsString()), - HttpMethod.GET, queryParams) - .getAsJsonObject(); + JsonObject order = pretixManager.request( + String.format("/api/v1/organizers/%s/events/%s/orders/%s/", pretixManager.getOrganizer(), + pretixManager.getEvent(), orderPosition.get("order").getAsString()), + HttpMethod.GET, queryParams).getAsJsonObject(); JsonObject member = new JsonObject(); @@ -696,24 +635,22 @@ public class MembershipManager { answerHeaders.add(question_identifier); } answers.addProperty(question_identifier, answer.get("answer").getAsString()); - if (membershipActiveQuestion == answer.get("question").getAsInt() - && answer.has("answer")) { + if (membershipActiveQuestion == answer.get("question").getAsInt() && answer.has("answer")) { Date date; try { date = pretixDateFormat.parse(answer.get("answer").getAsString()); active = date.toInstant(); } catch (ParseException e) { - logger.error("Error on parsing active date for '" - + orderPosition.get("order").getAsString() + logger.error("Error on parsing active date for '" + orderPosition.get("order").getAsString() + "'!", e); } } } } member.add("answers", answers); - if (includeInactive || active != null - && active.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS))) { + if (includeInactive + || active != null && active.isAfter(InstantHelper.truncate(Instant.now(), ChronoUnit.YEARS))) { members.add(member); } } @@ -758,15 +695,14 @@ public class MembershipManager { /** * Fetch all order positions. * - * @param path the path + * @param path the path * @param queryParams the query params - * @param result the result + * @param result the result * @return the list */ - protected List fetchAllOrderPositions(String path, - MultiValueMap queryParams, List result) { - JsonObject orderPositions = pretixManager.request(path, HttpMethod.GET, queryParams) - .getAsJsonObject(); + protected List fetchAllOrderPositions(String path, MultiValueMap queryParams, + List result) { + JsonObject orderPositions = pretixManager.request(path, HttpMethod.GET, queryParams).getAsJsonObject(); for (JsonElement element : orderPositions.getAsJsonArray("results")) { JsonObject orderPosition = element.getAsJsonObject(); @@ -774,8 +710,7 @@ public class MembershipManager { } if (orderPositions.has("next") && !orderPositions.get("next").isJsonNull()) { - return fetchAllOrderPositions(orderPositions.get("next").getAsString(), queryParams, - result); + return fetchAllOrderPositions(orderPositions.get("next").getAsString(), queryParams, result); } return result; @@ -785,7 +720,7 @@ public class MembershipManager { * Gets the answer object. * * @param orderPosition the order position - * @param question the question + * @param question the question * @return the answer object */ protected JsonObject getAnswerObject(JsonObject orderPosition, int question) { @@ -804,7 +739,7 @@ public class MembershipManager { * Gets the number answer. * * @param orderPosition the order position - * @param question the question + * @param question the question * @return the number answer */ protected int getNumberAnswer(JsonObject orderPosition, int question) { @@ -819,7 +754,7 @@ public class MembershipManager { * Gets the date answer. * * @param orderPosition the order position - * @param question the question + * @param question the question * @return the date answer */ protected Instant getDateAnswer(JsonObject orderPosition, int question) { @@ -828,11 +763,8 @@ public class MembershipManager { try { return pretixDateFormat.parse(answer.get("answer").getAsString()).toInstant(); } catch (ParseException e) { - logger.error("Error on parsing active date for '" - + orderPosition.get("order").getAsString() - + "' in question '" - + question - + "'!", e); + logger.error("Error on parsing active date for '" + orderPosition.get("order").getAsString() + + "' in question '" + question + "'!", e); } } return null; diff --git a/membership/src/main/java/de/bstly/we/membership/controller/MembershipController.java b/membership/src/main/java/de/bstly/we/membership/controller/MembershipController.java index aad0f3f..fb3f9a1 100644 --- a/membership/src/main/java/de/bstly/we/membership/controller/MembershipController.java +++ b/membership/src/main/java/de/bstly/we/membership/controller/MembershipController.java @@ -101,14 +101,13 @@ public class MembershipController extends BaseController { * Gets the member mail list. * * @param includeInactive the include inactive - * @param response the response + * @param response the response * @return the member mail list * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/export") - public void getMemberMailList( - @RequestParam("includeInactive") Optional includeInactive, + public void getMemberMailList(@RequestParam("includeInactive") Optional includeInactive, HttpServletResponse response) throws IOException { response.setContentType("text/csv"); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); @@ -120,7 +119,7 @@ public class MembershipController extends BaseController { * Webhook. * * @param webhookKey the webhook key - * @param payload the payload + * @param payload the payload */ @PostMapping("/pretix/webhook") public void webhook(@RequestParam("key") String webhookKey, @RequestBody String payload) { @@ -130,8 +129,7 @@ public class MembershipController extends BaseController { JsonObject event = JsonParser.parseString(payload).getAsJsonObject(); - if (event.has("action") - && "pretix.event.order.paid".equals(event.get("action").getAsString())) { + if (event.has("action") && "pretix.event.order.paid".equals(event.get("action").getAsString())) { membershipManager.generateMembershipIds(); membershipManager.activeMemberships(); } else { diff --git a/minetest/src/main/java/de/bstly/we/minetest/businesslogic/MinetestAccountManager.java b/minetest/src/main/java/de/bstly/we/minetest/businesslogic/MinetestAccountManager.java index 87e36a3..6f365ad 100644 --- a/minetest/src/main/java/de/bstly/we/minetest/businesslogic/MinetestAccountManager.java +++ b/minetest/src/main/java/de/bstly/we/minetest/businesslogic/MinetestAccountManager.java @@ -51,29 +51,28 @@ public class MinetestAccountManager implements UserDataProvider { * @return the all by owner */ public List getAllByOwner(Long userId) { - return Lists - .newArrayList(minetestAccountRepository.findAll(qMinetestAccount.owner.eq(userId))); + return Lists.newArrayList(minetestAccountRepository.findAll(qMinetestAccount.owner.eq(userId))); } /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ public Page get(int page, int size, String sortBy, boolean descending) { - return minetestAccountRepository.findAll(PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return minetestAccountRepository.findAll( + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Creates the. * * @param owner the owner - * @param name the name + * @param name the name * @param quota the quota * @return the minetest account */ @@ -113,7 +112,7 @@ public class MinetestAccountManager implements UserDataProvider { * Delete. * * @param minetestAccount the minetest account - * @param quota the quota + * @param quota the quota */ public void delete(MinetestAccount minetestAccount, boolean quota) { if (quota) { @@ -146,7 +145,6 @@ public class MinetestAccountManager implements UserDataProvider { } } - /* * @see de.bstly.we.businesslogic.UserDataProvider#getId() */ @@ -155,7 +153,6 @@ public class MinetestAccountManager implements UserDataProvider { return "minetest-accounts"; } - /* * @see de.bstly.we.businesslogic.UserDataProvider#getUserData(java.lang.Long) */ @@ -168,7 +165,6 @@ public class MinetestAccountManager implements UserDataProvider { return result; } - /* * @see de.bstly.we.businesslogic.UserDataProvider#purgeUserData(java.lang.Long) */ diff --git a/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountController.java b/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountController.java index 2f4bb90..c307813 100644 --- a/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountController.java +++ b/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountController.java @@ -76,8 +76,7 @@ public class MinetestAccountController extends BaseController { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - Quota minetestAccountsQuota = quotaManager.get(getCurrentUserId(), - MinetestQuotas.MINETEST_ACCOUNTS); + Quota minetestAccountsQuota = quotaManager.get(getCurrentUserId(), MinetestQuotas.MINETEST_ACCOUNTS); if (minetestAccountsQuota == null || minetestAccountsQuota.getValue() < 1) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } diff --git a/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountManagementController.java b/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountManagementController.java index fadccea..f019566 100644 --- a/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountManagementController.java +++ b/minetest/src/main/java/de/bstly/we/minetest/controller/MinetestAccountManagementController.java @@ -47,11 +47,9 @@ public class MinetestAccountManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getMinetestAccounts( - @RequestParam("page") Optional pageParameter, + public Page getMinetestAccounts(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return minetestAccountManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", - true); + return minetestAccountManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true); } /** @@ -62,8 +60,7 @@ public class MinetestAccountManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping - public MinetestAccount createOrUpdateMinetestAccount( - @RequestBody MinetestAccount minetestAccount) { + public MinetestAccount createOrUpdateMinetestAccount(@RequestBody MinetestAccount minetestAccount) { Errors errors = new RequestBodyErrors(minetestAccount); @@ -78,7 +75,7 @@ public class MinetestAccountManagementController extends BaseController { /** * Delete minetest account. * - * @param name the name + * @param name the name * @param quota the quota */ @PreAuthorize("hasRole('ROLE_ADMIN')") @@ -91,8 +88,7 @@ public class MinetestAccountManagementController extends BaseController { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } - minetestAccountManager.delete(minetestAccount, - quota.isPresent() && quota.get().booleanValue()); + minetestAccountManager.delete(minetestAccount, quota.isPresent() && quota.get().booleanValue()); } /** @@ -103,8 +99,7 @@ public class MinetestAccountManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/all/{owner}") - public void deleteAll(@PathVariable("owner") Long owner, - @RequestParam("quota") Optional quota) { + public void deleteAll(@PathVariable("owner") Long owner, @RequestParam("quota") Optional quota) { minetestAccountManager.deleteAll(owner, quota.isPresent() && quota.get().booleanValue()); } diff --git a/minetest/src/main/java/de/bstly/we/minetest/controller/validation/MinetestAccountValidator.java b/minetest/src/main/java/de/bstly/we/minetest/controller/validation/MinetestAccountValidator.java index 0fe6b17..daee3bf 100644 --- a/minetest/src/main/java/de/bstly/we/minetest/controller/validation/MinetestAccountValidator.java +++ b/minetest/src/main/java/de/bstly/we/minetest/controller/validation/MinetestAccountValidator.java @@ -26,7 +26,6 @@ public class MinetestAccountValidator implements Validator { private SystemPropertyManager systemPropertyManager; protected static final String NAME_REGEX = "^([-_a-zA-Z0-9]+)$"; - /* * @see org.springframework.validation.Validator#supports(java.lang.Class) */ @@ -34,9 +33,9 @@ public class MinetestAccountValidator implements Validator { return clazz.isAssignableFrom(MinetestAccount.class); } - /* - * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) + * @see org.springframework.validation.Validator#validate(java.lang.Object, + * org.springframework.validation.Errors) */ public void validate(Object target, Errors errors) { validateMinetestName(target, errors); @@ -79,11 +78,11 @@ public class MinetestAccountValidator implements Validator { public void validateReservedNames(Object target, Errors errors) { MinetestAccount minetestAccount = (MinetestAccount) target; if (StringUtils.hasText(minetestAccount.getName())) { - for (String systemUsername : systemPropertyManager - .get(UserModelValidator.RESERVED_USERNAMES, "").split(",")) { - if (StringUtils.hasText(systemUsername) && (minetestAccount.getName().toLowerCase() - .equals(systemUsername) - || minetestAccount.getName().toLowerCase().matches(systemUsername))) { + for (String systemUsername : systemPropertyManager.get(UserModelValidator.RESERVED_USERNAMES, "") + .split(",")) { + if (StringUtils.hasText(systemUsername) + && (minetestAccount.getName().toLowerCase().equals(systemUsername) + || minetestAccount.getName().toLowerCase().matches(systemUsername))) { errors.rejectValue("name", "NOT_VALID"); break; } diff --git a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcAuthorizationCodeManager.java b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcAuthorizationCodeManager.java index 33dd83e..caa0478 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcAuthorizationCodeManager.java +++ b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcAuthorizationCodeManager.java @@ -27,11 +27,11 @@ public class OidcAuthorizationCodeManager { /** * Creates the. * - * @param clientId the client id + * @param clientId the client id * @param redirectUri the redirect uri - * @param scopes the scopes - * @param userId the user id - * @param nonce the nonce + * @param scopes the scopes + * @param userId the user id + * @param nonce the nonce * @return the oidc authorization code */ public OidcAuthorizationCode create(String clientId, URI redirectUri, Set scopes, Long userId, diff --git a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcClientManager.java b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcClientManager.java index ce0f7b6..d4eb15e 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcClientManager.java +++ b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcClientManager.java @@ -38,34 +38,32 @@ public class OidcClientManager { /** * Creates the client. * - * @param clientName the client name + * @param clientName the client name * @param redirectUris the redirect uris * @return the oidc client */ public OidcClient createClient(String clientName, Set redirectUris) { return createClient(clientName, - Sets.newHashSet(OidcClientAuthenticationMethod.basic, - OidcClientAuthenticationMethod.basic), - Sets.newHashSet(OidcAuthorizationGrantType.authorization_code), redirectUris, - Sets.newHashSet("openid"), null, false); + Sets.newHashSet(OidcClientAuthenticationMethod.basic, OidcClientAuthenticationMethod.basic), + Sets.newHashSet(OidcAuthorizationGrantType.authorization_code), redirectUris, Sets.newHashSet("openid"), + null, false); } /** * Creates the client. * - * @param clientName the client name + * @param clientName the client name * @param clientAuthenticationMethods the client authentication methods - * @param authorizationGrantTypes the authorization grant types - * @param redirectUris the redirect uris - * @param scopes the scopes - * @param loginUrl the login url - * @param alwaysPermitted the always permitted + * @param authorizationGrantTypes the authorization grant types + * @param redirectUris the redirect uris + * @param scopes the scopes + * @param loginUrl the login url + * @param alwaysPermitted the always permitted * @return the oidc client */ - public OidcClient createClient(String clientName, - Set clientAuthenticationMethods, - Set authorizationGrantTypes, Set redirectUris, - Set scopes, String loginUrl, boolean alwaysPermitted) { + public OidcClient createClient(String clientName, Set clientAuthenticationMethods, + Set authorizationGrantTypes, Set redirectUris, Set scopes, + String loginUrl, boolean alwaysPermitted) { OidcClient oidcClient = new OidcClient(); @@ -85,8 +83,7 @@ public class OidcClientManager { } oidcClient.setClientId(clientId); - oidcClient.setClientSecret( - RandomStringUtils.random(OIDC_CLIENT_CLIENT_SECRET_LENGTH, true, true)); + oidcClient.setClientSecret(RandomStringUtils.random(OIDC_CLIENT_CLIENT_SECRET_LENGTH, true, true)); return oidcClientRepository.save(oidcClient); } @@ -110,8 +107,7 @@ public class OidcClientManager { public OidcClient createNewSecretByClientName(String clientName) { OidcClient oidcClient = getByClientName(clientName); Assert.notNull(oidcClient, "No client found for name '" + clientName + "'"); - oidcClient.setClientSecret( - RandomStringUtils.random(OIDC_CLIENT_CLIENT_SECRET_LENGTH, true, true)); + oidcClient.setClientSecret(RandomStringUtils.random(OIDC_CLIENT_CLIENT_SECRET_LENGTH, true, true)); return oidcClientRepository.save(oidcClient); } @@ -139,14 +135,13 @@ public class OidcClientManager { /** * Gets the by client id and secret. * - * @param clientId the client id + * @param clientId the client id * @param clientSecret the client secret * @return the by client id and secret */ public OidcClient getByClientIdAndSecret(String clientId, String clientSecret) { - return oidcClientRepository.findOne( - qOidcClient.clientId.eq(clientId).and(qOidcClient.clientSecret.eq(clientSecret))) - .orElse(null); + return oidcClientRepository + .findOne(qOidcClient.clientId.eq(clientId).and(qOidcClient.clientSecret.eq(clientSecret))).orElse(null); } /** @@ -175,9 +170,9 @@ public class OidcClientManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcTokenManager.java b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcTokenManager.java index e3b0c40..2e088e0 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcTokenManager.java +++ b/oidc/src/main/java/de/bstly/we/oidc/businesslogic/OidcTokenManager.java @@ -69,13 +69,7 @@ public class OidcTokenManager implements SmartInitializingSingleton { private QOidcToken qOidcToken = QOidcToken.oidcToken; /* - * @see org.springframework.beans.factory.SmartInitializingSingleton# - * afterSingletonsInstantiated() - */ - /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() - */ - /* + * * @see org.springframework.beans.factory.SmartInitializingSingleton# * afterSingletonsInstantiated() */ @@ -122,14 +116,14 @@ public class OidcTokenManager implements SmartInitializingSingleton { * * @param client the client * @param userId the user id - * @param nonce the nonce + * @param nonce the nonce * @param scopes the scopes * @param issuer the issuer * @return the oidc token * @throws JOSEException the JOSE exception */ - public OidcToken createTokenWithIdToken(OidcClient client, Long userId, String nonce, - Set scopes, String issuer) throws JOSEException { + public OidcToken createTokenWithIdToken(OidcClient client, Long userId, String nonce, Set scopes, + String issuer) throws JOSEException { OidcToken token = new OidcToken(); token.setClient(client.getId()); @@ -145,9 +139,8 @@ public class OidcTokenManager implements SmartInitializingSingleton { claimsSetBuilder.issuer(issuer); claimsSetBuilder.audience(client.getClientId()); - claimsSetBuilder.expirationTime( - Date.from(Instant.now().plus(client.getTokenLifetime(), ChronoUnit.SECONDS) - .atZone(ZoneId.systemDefault()).toInstant())); + claimsSetBuilder.expirationTime(Date.from(Instant.now().plus(client.getTokenLifetime(), ChronoUnit.SECONDS) + .atZone(ZoneId.systemDefault()).toInstant())); claimsSetBuilder.issueTime(new Date()); if (StringUtils.hasText(nonce)) { @@ -160,8 +153,7 @@ public class OidcTokenManager implements SmartInitializingSingleton { jwtKey = createDefaultJwtKey(); } - JWSHeader.Builder headerBuilder = new JWSHeader.Builder( - jwtKeyManager.getJwsAlgorithm(jwtKey)); + JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey)); headerBuilder.keyID(jwtKey.getKeyID()); headerBuilder.type(JOSEObjectType.JWT); @@ -200,7 +192,7 @@ public class OidcTokenManager implements SmartInitializingSingleton { } else { claimsSetBuilder.claim("email_verified", true); } - + claimsSetBuilder.claim("email", email.toLowerCase()); UserProfileField localeProfileField = userProfileFieldManager.get(user.getId(), @@ -210,8 +202,7 @@ public class OidcTokenManager implements SmartInitializingSingleton { if ("de-informal".equals(localeProfileField.getValue())) { claimsSetBuilder.claim(UserProfileFields.PROFILE_FIELD_LOCALE, "de"); } else if (StringUtils.hasText(localeProfileField.getValue())) { - claimsSetBuilder.claim(UserProfileFields.PROFILE_FIELD_LOCALE, - localeProfileField.getValue()); + claimsSetBuilder.claim(UserProfileFields.PROFILE_FIELD_LOCALE, localeProfileField.getValue()); } } diff --git a/oidc/src/main/java/de/bstly/we/oidc/controller/OIDCClientController.java b/oidc/src/main/java/de/bstly/we/oidc/controller/OIDCClientController.java index 8b3fc1f..dbce434 100755 --- a/oidc/src/main/java/de/bstly/we/oidc/controller/OIDCClientController.java +++ b/oidc/src/main/java/de/bstly/we/oidc/controller/OIDCClientController.java @@ -53,8 +53,7 @@ public class OIDCClientController extends BaseController { @GetMapping public Page getClients(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter) { - return registeredClientService.get(pageParameter.orElse(0), sizeParameter.orElse(10), - "clientName", true); + return registeredClientService.get(pageParameter.orElse(0), sizeParameter.orElse(10), "clientName", true); } /** @@ -106,21 +105,19 @@ public class OIDCClientController extends BaseController { if (oidcClientModel.getClientAuthenticationMethods() == null || oidcClientModel.getClientAuthenticationMethods().isEmpty()) { - oidcClientModel.setClientAuthenticationMethods(Sets.newHashSet( - OidcClientAuthenticationMethod.basic, OidcClientAuthenticationMethod.post)); + oidcClientModel.setClientAuthenticationMethods( + Sets.newHashSet(OidcClientAuthenticationMethod.basic, OidcClientAuthenticationMethod.post)); } if (oidcClientModel.getAuthorizationGrantTypes() == null || oidcClientModel.getAuthorizationGrantTypes().isEmpty()) { - oidcClientModel.setAuthorizationGrantTypes( - Sets.newHashSet(OidcAuthorizationGrantType.authorization_code)); + oidcClientModel.setAuthorizationGrantTypes(Sets.newHashSet(OidcAuthorizationGrantType.authorization_code)); } return registeredClientService.createClient(oidcClientModel.getName(), - oidcClientModel.getClientAuthenticationMethods(), - oidcClientModel.getAuthorizationGrantTypes(), - oidcClientModel.getRegisteredRedirectUris(), oidcClientModel.getScopes(), - oidcClientModel.getLoginUrl(), oidcClientModel.isAlwaysPermitted()); + oidcClientModel.getClientAuthenticationMethods(), oidcClientModel.getAuthorizationGrantTypes(), + oidcClientModel.getRegisteredRedirectUris(), oidcClientModel.getScopes(), oidcClientModel.getLoginUrl(), + oidcClientModel.isAlwaysPermitted()); } /** diff --git a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcAuthorizationController.java b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcAuthorizationController.java index b0f8112..6f20b5b 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcAuthorizationController.java +++ b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcAuthorizationController.java @@ -54,15 +54,15 @@ public class OidcAuthorizationController { /** * Authorization request. * - * @param scope the scope + * @param scope the scope * @param responseType the response type - * @param clientId the client id - * @param redirectUri the redirect uri - * @param state the state - * @param nonce the nonce - * @param principal the principal - * @param request the request - * @param response the response + * @param clientId the client id + * @param redirectUri the redirect uri + * @param state the state + * @param nonce the nonce + * @param principal the principal + * @param request the request + * @param response the response * @throws IOException Signals that an I/O exception has occurred. */ @PreAuthorize("isAuthenticated()") @@ -89,43 +89,37 @@ public class OidcAuthorizationController { if (!StringUtils.hasText(clientId)) { logger.debug("missing client_id"); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.INVALID_REQUEST, "missing client_id", state); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.INVALID_REQUEST, + "missing client_id", state); } OidcClient client = oidcClientManager.getByClientId(clientId); if (client == null) { logger.debug("invalid client_id: " + clientId); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.INVALID_REQUEST, "invalid client_id", state); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.INVALID_REQUEST, + "invalid client_id", state); } if (!client.getRedirectUris().contains(redirectUri.toString())) { - logger.debug("invalid redirect_uri: " + redirectUri + " allowed: " - + client.getRedirectUris()); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.INVALID_REQUEST, "invalid redirect_uri", state); + logger.debug("invalid redirect_uri: " + redirectUri + " allowed: " + client.getRedirectUris()); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.INVALID_REQUEST, + "invalid redirect_uri", state); } if (!client.isAlwaysPermitted() && !permissionManager.hasPermission(principal.getUserId(), client.getClientName()) - && !permissionManager.hasPermission(principal.getUserId(), - Permissions.ROLE_ADMIN)) { - logger.debug( - "user not allowed: " + principal.getUserId() + " - " + client.getClientName()); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.ACCESS_DENIED, "user not allowed", state); + && !permissionManager.hasPermission(principal.getUserId(), Permissions.ROLE_ADMIN)) { + logger.debug("user not allowed: " + principal.getUserId() + " - " + client.getClientName()); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.ACCESS_DENIED, + "user not allowed", state); } - if (!client.getAuthorizationGrantTypes() - .contains(OidcAuthorizationGrantType.authorization_code)) { - logger.debug("authorization grant type not allowed: " - + OidcAuthorizationGrantType.authorization_code + " - " - + client.getClientName()); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.UNAUTHORIZED_CLIENT, + if (!client.getAuthorizationGrantTypes().contains(OidcAuthorizationGrantType.authorization_code)) { + logger.debug("authorization grant type not allowed: " + OidcAuthorizationGrantType.authorization_code + + " - " + client.getClientName()); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.UNAUTHORIZED_CLIENT, "authorization grant type not allowed", state); } @@ -135,8 +129,7 @@ public class OidcAuthorizationController { + " - " + client.getClientName()); throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.UNSUPPORTED_RESPONSE_TYPE, - "response type not allowed", state); + OidcAuthorizationErrorCode.UNSUPPORTED_RESPONSE_TYPE, "response type not allowed", state); } @@ -144,13 +137,13 @@ public class OidcAuthorizationController { if (!scopes.contains("openid")) { logger.debug("missing openid scope: " + scopes + " - " + client.getClientName()); - throw new InvalidAuthorizationRequestError(redirectUri, - OidcAuthorizationErrorCode.INVALID_SCOPE, "missing openid scope", state); + throw new InvalidAuthorizationRequestError(redirectUri, OidcAuthorizationErrorCode.INVALID_SCOPE, + "missing openid scope", state); } - OidcAuthorizationCode authorizationCode = oidcAuthorizationCodeManager.create(clientId, - redirectUri, scopes, principal.getUserId(), nonce); + OidcAuthorizationCode authorizationCode = oidcAuthorizationCodeManager.create(clientId, redirectUri, scopes, + principal.getUserId(), nonce); String uri = redirectUri.toString(); @@ -171,12 +164,11 @@ public class OidcAuthorizationController { * Handle. * * @param exception the exception - * @param response the response + * @param response the response * @throws IOException Signals that an I/O exception has occurred. */ @ExceptionHandler(InvalidAuthorizationRequestError.class) - public void handle(InvalidAuthorizationRequestError exception, HttpServletResponse response) - throws IOException { + public void handle(InvalidAuthorizationRequestError exception, HttpServletResponse response) throws IOException { String uri = exception.getRedirectUri().toString(); uri += "?error=" + exception.getErrorCode().getAuthorizationErrorCode(); @@ -209,13 +201,13 @@ public class OidcAuthorizationController { /** * Instantiates a new invalid authorization request error. * - * @param redirectUri the redirect uri - * @param errorCode the error code + * @param redirectUri the redirect uri + * @param errorCode the error code * @param errorDescription the error description - * @param state the state + * @param state the state */ - InvalidAuthorizationRequestError(URI redirectUri, OidcAuthorizationErrorCode errorCode, - String errorDescription, String state) { + InvalidAuthorizationRequestError(URI redirectUri, OidcAuthorizationErrorCode errorCode, String errorDescription, + String state) { super(errorDescription); this.redirectUri = redirectUri; this.errorCode = errorCode; diff --git a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcDiscoveryController.java b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcDiscoveryController.java index 210ea3c..0ccd18a 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcDiscoveryController.java +++ b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcDiscoveryController.java @@ -34,13 +34,12 @@ public class OidcDiscoveryController { /** * Gets the configuration. * - * @param request the request + * @param request the request * @param response the response * @return the configuration */ @GetMapping - public OidcConfiguration getConfiguration(HttpServletRequest request, - HttpServletResponse response) { + public OidcConfiguration getConfiguration(HttpServletRequest request, HttpServletResponse response) { OidcConfiguration config = new OidcConfiguration(); String issuer = oidcIssuer; @@ -56,8 +55,7 @@ public class OidcDiscoveryController { config.setScopes_supported(Sets.newHashSet("openid")); config.setResponse_types_supported(Sets.newHashSet("code")); config.setGrant_types_supported(Sets.newHashSet("authorization_code")); - config.setToken_endpoint_auth_methods_supported( - Sets.newHashSet("client_secret_post", "client_secret_basic")); + config.setToken_endpoint_auth_methods_supported(Sets.newHashSet("client_secret_post", "client_secret_basic")); config.setSubject_types_supported(Sets.newHashSet("public")); try { diff --git a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcTokenController.java b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcTokenController.java index 405c98d..343a835 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/controller/OidcTokenController.java +++ b/oidc/src/main/java/de/bstly/we/oidc/controller/OidcTokenController.java @@ -68,9 +68,9 @@ public class OidcTokenController { * Gets the token. * * @param authorizationHeader the authorization header - * @param tokenRequest the token request - * @param request the request - * @param response the response + * @param tokenRequest the token request + * @param request the request + * @param response the response * @return the token */ @PostMapping @@ -91,8 +91,9 @@ public class OidcTokenController { if (StringUtils.hasText(authorizationHeader) && StringUtils.startsWithIgnoreCase(authorizationHeader, BASIC_AUTH)) { - String decoded = new String(Base64.getDecoder().decode(authorizationHeader - .replaceFirst(BASIC_AUTH, "").trim().getBytes(StandardCharsets.UTF_8)), + String decoded = new String( + Base64.getDecoder().decode( + authorizationHeader.replaceFirst(BASIC_AUTH, "").trim().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); if (decoded.indexOf(":") != -1) { tokenRequest.setClient_id(decoded.split(":")[0]); @@ -100,8 +101,7 @@ public class OidcTokenController { clientAuthenticationMethod = OidcClientAuthenticationMethod.basic; } else { logger.debug("invalid_basic_authentication: " + decoded); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_CLIENT, - "invalid_basic_authentication"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_CLIENT, "invalid_basic_authentication"); } } @@ -115,45 +115,38 @@ public class OidcTokenController { if (!client.getClientAuthenticationMethods().contains(clientAuthenticationMethod)) { logger.debug("invalid_authentication_method: " + clientAuthenticationMethod); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_REQUEST, - "invalid_authentication_method"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_REQUEST, "invalid_authentication_method"); } if (!client.getAuthorizationGrantTypes().contains(tokenRequest.getGrant_type())) { logger.debug("invalid_grant_type: " + tokenRequest.getGrant_type()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.UNAUTHORIZED_CLIENT, - "invalid_grant_type"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.UNAUTHORIZED_CLIENT, "invalid_grant_type"); } if (tokenRequest.getRedirect_uri() != null && !client.getRedirectUris().contains(tokenRequest.getRedirect_uri().toString())) { - logger.debug("invalid redirect_uri: " + tokenRequest.getRedirect_uri().toString() - + " allowed: " + client.getRedirectUris()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_REQUEST, - "invalid_redirect_uri"); + logger.debug("invalid redirect_uri: " + tokenRequest.getRedirect_uri().toString() + " allowed: " + + client.getRedirectUris()); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_REQUEST, "invalid_redirect_uri"); } OidcToken token = null; switch (tokenRequest.getGrant_type()) { case authorization_code: - OidcAuthorizationCode authorizationCode = oidcAuthorizationCodeManager - .getByCode(tokenRequest.getCode()); + OidcAuthorizationCode authorizationCode = oidcAuthorizationCodeManager.getByCode(tokenRequest.getCode()); if (authorizationCode == null) { logger.debug("invalid authorization code: " + tokenRequest.getCode()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_GRANT, - "invalid_authorization_code"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_GRANT, "invalid_authorization_code"); } if (Instant.now().isAfter(authorizationCode.getExpiry())) { logger.debug("authorization code expired: " + authorizationCode.getExpiry()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_GRANT, - "invalid_authorization_code"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_GRANT, "invalid_authorization_code"); } if (!tokenRequest.getClient_id().equals(authorizationCode.getClientId())) { - logger.debug("invalid client for authorization code, expected: " - + authorizationCode.getClientId() + " got: " + tokenRequest.getClient_id()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_CLIENT, - "invalid_client"); + logger.debug("invalid client for authorization code, expected: " + authorizationCode.getClientId() + + " got: " + tokenRequest.getClient_id()); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_CLIENT, "invalid_client"); } Set scopes = StringUtils.hasText(tokenRequest.getScope()) @@ -162,8 +155,7 @@ public class OidcTokenController { if (!scopes.contains("openid") || !client.getScopes().containsAll(scopes)) { logger.debug("missing openid scope: " + scopes + " - " + client.getClientName()); - throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_SCOPE, - "invalid scopes"); + throw new InvalidTokenRequestError(OidcTokenErrorCode.INVALID_SCOPE, "invalid scopes"); } String issuer = oidcIssuer; @@ -176,9 +168,8 @@ public class OidcTokenController { } try { - token = oidcTokenManager.createTokenWithIdToken(client, - authorizationCode.getUserId(), authorizationCode.getNonce(), scopes, - issuer); + token = oidcTokenManager.createTokenWithIdToken(client, authorizationCode.getUserId(), + authorizationCode.getNonce(), scopes, issuer); } catch (JOSEException e) { logger.error("error creating token", client, authorizationCode); e.printStackTrace(); @@ -208,13 +199,13 @@ public class OidcTokenController { * Handle. * * @param exception the exception - * @param response the response + * @param response the response * @return the response entity * @throws IOException Signals that an I/O exception has occurred. */ @ExceptionHandler(InvalidTokenRequestError.class) - public ResponseEntity handle(InvalidTokenRequestError exception, - HttpServletResponse response) throws IOException { + public ResponseEntity handle(InvalidTokenRequestError exception, HttpServletResponse response) + throws IOException { // response.sendError(400, "redirect uri mismatch"); return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON) .body(" {\"error\": \"" + exception.getMessage() + "\"}"); @@ -236,7 +227,7 @@ public class OidcTokenController { /** * Instantiates a new invalid token request error. * - * @param errorCode the error code + * @param errorCode the error code * @param errorDescription the error description */ InvalidTokenRequestError(OidcTokenErrorCode errorCode, String errorDescription) { diff --git a/oidc/src/main/java/de/bstly/we/oidc/controller/model/OidcClientModel.java b/oidc/src/main/java/de/bstly/we/oidc/controller/model/OidcClientModel.java index 6390487..2cc8874 100755 --- a/oidc/src/main/java/de/bstly/we/oidc/controller/model/OidcClientModel.java +++ b/oidc/src/main/java/de/bstly/we/oidc/controller/model/OidcClientModel.java @@ -71,8 +71,7 @@ public class OidcClientModel { * * @param clientAuthenticationMethods the new client authentication methods */ - public void setClientAuthenticationMethods( - Set clientAuthenticationMethods) { + public void setClientAuthenticationMethods(Set clientAuthenticationMethods) { this.clientAuthenticationMethods = clientAuthenticationMethods; } @@ -90,8 +89,7 @@ public class OidcClientModel { * * @param authorizationGrantTypes the new authorization grant types */ - public void setAuthorizationGrantTypes( - Set authorizationGrantTypes) { + public void setAuthorizationGrantTypes(Set authorizationGrantTypes) { this.authorizationGrantTypes = authorizationGrantTypes; } diff --git a/oidc/src/main/java/de/bstly/we/oidc/model/OidcAuthorizationCode.java b/oidc/src/main/java/de/bstly/we/oidc/model/OidcAuthorizationCode.java index 0674752..7ccb383 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/model/OidcAuthorizationCode.java +++ b/oidc/src/main/java/de/bstly/we/oidc/model/OidcAuthorizationCode.java @@ -29,14 +29,13 @@ public class OidcAuthorizationCode { /** * Instantiates a new oidc authorization code. * - * @param clientId the client id + * @param clientId the client id * @param redirectUri the redirect uri - * @param scopes the scopes - * @param userId the user id - * @param nonce the nonce + * @param scopes the scopes + * @param userId the user id + * @param nonce the nonce */ - public OidcAuthorizationCode(String clientId, URI redirectUri, Set scopes, Long userId, - String nonce) { + public OidcAuthorizationCode(String clientId, URI redirectUri, Set scopes, Long userId, String nonce) { this.clientId = clientId; this.redirectUri = redirectUri; this.scopes = scopes; diff --git a/oidc/src/main/java/de/bstly/we/oidc/model/OidcClient.java b/oidc/src/main/java/de/bstly/we/oidc/model/OidcClient.java index 00eef99..28d01c4 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/model/OidcClient.java +++ b/oidc/src/main/java/de/bstly/we/oidc/model/OidcClient.java @@ -149,8 +149,7 @@ public class OidcClient { * * @param clientAuthenticationMethods the new client authentication methods */ - public void setClientAuthenticationMethods( - Set clientAuthenticationMethods) { + public void setClientAuthenticationMethods(Set clientAuthenticationMethods) { this.clientAuthenticationMethods = clientAuthenticationMethods; } @@ -168,8 +167,7 @@ public class OidcClient { * * @param authorizationGrantTypes the new authorization grant types */ - public void setAuthorizationGrantTypes( - Set authorizationGrantTypes) { + public void setAuthorizationGrantTypes(Set authorizationGrantTypes) { this.authorizationGrantTypes = authorizationGrantTypes; } diff --git a/oidc/src/main/java/de/bstly/we/oidc/model/OidcConfiguration.java b/oidc/src/main/java/de/bstly/we/oidc/model/OidcConfiguration.java index 4736189..28b9fb1 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/model/OidcConfiguration.java +++ b/oidc/src/main/java/de/bstly/we/oidc/model/OidcConfiguration.java @@ -196,10 +196,10 @@ public class OidcConfiguration { /** * Sets the token endpoint auth methods supported. * - * @param token_endpoint_auth_methods_supported the new token endpoint auth methods supported + * @param token_endpoint_auth_methods_supported the new token endpoint auth + * methods supported */ - public void setToken_endpoint_auth_methods_supported( - Set token_endpoint_auth_methods_supported) { + public void setToken_endpoint_auth_methods_supported(Set token_endpoint_auth_methods_supported) { this.token_endpoint_auth_methods_supported = token_endpoint_auth_methods_supported; } diff --git a/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenErrorCode.java b/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenErrorCode.java index 590575a..917915a 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenErrorCode.java +++ b/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenErrorCode.java @@ -7,9 +7,9 @@ package de.bstly.we.oidc.model; * The Enum OidcTokenErrorCode. */ public enum OidcTokenErrorCode { - INVALID_REQUEST("invalid_request"), INVALID_CLIENT("invalid_client"), - INVALID_GRANT("invalid_grant"), UNAUTHORIZED_CLIENT("unauthorized_client"), - UNSUPPORTED_GRANT_TYPE("unsupported_grant_type"), INVALID_SCOPE("invalid_scope"); + INVALID_REQUEST("invalid_request"), INVALID_CLIENT("invalid_client"), INVALID_GRANT("invalid_grant"), + UNAUTHORIZED_CLIENT("unauthorized_client"), UNSUPPORTED_GRANT_TYPE("unsupported_grant_type"), + INVALID_SCOPE("invalid_scope"); private final String tokenErrorCode; diff --git a/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenRequest.java b/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenRequest.java index 7f00547..93d75a6 100644 --- a/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenRequest.java +++ b/oidc/src/main/java/de/bstly/we/oidc/model/OidcTokenRequest.java @@ -20,15 +20,15 @@ public class OidcTokenRequest { /** * Instantiates a new oidc token request. * - * @param code the code - * @param grant_type the grant type - * @param client_id the client id + * @param code the code + * @param grant_type the grant type + * @param client_id the client id * @param client_secret the client secret - * @param redirect_uri the redirect uri - * @param scope the scope + * @param redirect_uri the redirect uri + * @param scope the scope */ - public OidcTokenRequest(String code, OidcAuthorizationGrantType grant_type, String client_id, - String client_secret, URI redirect_uri, String scope) { + public OidcTokenRequest(String code, OidcAuthorizationGrantType grant_type, String client_id, String client_secret, + URI redirect_uri, String scope) { super(); this.code = code; this.grant_type = grant_type; diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/DebugController.java b/partey/src/main/java/de/bstly/we/partey/api/controller/DebugController.java index 789f28e..218186c 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/DebugController.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/DebugController.java @@ -29,13 +29,12 @@ public class DebugController extends DebugLogger { /** * Debug. * - * @param payload the payload - * @param request the request + * @param payload the payload + * @param request the request * @param response the response */ @RequestMapping("/**") - public void debug(@RequestBody Optional payload, HttpServletRequest request, - HttpServletResponse response) { + public void debug(@RequestBody Optional payload, HttpServletRequest request, HttpServletResponse response) { parteyApiAuthentication.authenticateRequest(request); debugPrintRequest(request, payload); diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/MapController.java b/partey/src/main/java/de/bstly/we/partey/api/controller/MapController.java index ea37c9e..e50e606 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/MapController.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/MapController.java @@ -38,8 +38,8 @@ public class MapController extends DebugLogger { /** * Gets the map data. * - * @param playUri the play uri - * @param request the request + * @param playUri the play uri + * @param request the request * @param response the response * @return the map data */ @@ -56,7 +56,7 @@ public class MapController extends DebugLogger { Room room = parteyMapManager.parseRoom(playUri, request); mapData.setMapUrl(room.getMapUrl()); - + if (room.getTags() != null) { mapData.setTags(room.getTags()); } diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/ReportController.java b/partey/src/main/java/de/bstly/we/partey/api/controller/ReportController.java index 4cc3183..56513d0 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/ReportController.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/ReportController.java @@ -32,7 +32,7 @@ public class ReportController extends DebugLogger { * Report. * * @param userReport the user report - * @param request the request + * @param request the request */ @PostMapping("") public void report(@RequestBody UserReport userReport, HttpServletRequest request) { diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/RoomController.java b/partey/src/main/java/de/bstly/we/partey/api/controller/RoomController.java index 8283284..9984331 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/RoomController.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/RoomController.java @@ -64,11 +64,11 @@ public class RoomController extends DebugLogger { /** * Access. * - * @param userIdentifier the user identifier - * @param roomId the room id + * @param userIdentifier the user identifier + * @param roomId the room id * @param characterLayers the character layers - * @param ipAddress the ip address - * @param request the request + * @param ipAddress the ip address + * @param request the request * @return the member data */ @GetMapping("/access") @@ -110,8 +110,7 @@ public class RoomController extends DebugLogger { if (user != null && permissionManager.isFullUser(user.getId()) && permissionManager.hasPermission(user.getId(), ParteyPermissions.PARTEY)) { - ParteyUserTextures parteyUserTextures = parteyUserTexturesManager - .getByTarget(user.getId()); + ParteyUserTextures parteyUserTextures = parteyUserTexturesManager.getByTarget(user.getId()); if (characterLayers.isPresent()) { if (parteyUserTextures == null) { @@ -125,9 +124,8 @@ public class RoomController extends DebugLogger { parteyUserTextures.setTextures(Lists.newArrayList()); } - if (parteyUserTextures.getTextures().size() != characterLayers.get().length - || !parteyUserTextures.getTextures() - .containsAll(Lists.newArrayList(characterLayers.get()))) { + if (parteyUserTextures.getTextures().size() != characterLayers.get().length || !parteyUserTextures + .getTextures().containsAll(Lists.newArrayList(characterLayers.get()))) { parteyUserTextures.setTextures(Lists.newArrayList(characterLayers.get())); parteyUserTextures = parteyUserTexturesManager.save(parteyUserTextures); } @@ -151,8 +149,7 @@ public class RoomController extends DebugLogger { } } - for (ParteyUserTag parteyUserTag : parteyUserTagManager - .getNonExpiredForUsername(user.getUsername())) { + for (ParteyUserTag parteyUserTag : parteyUserTagManager.getNonExpiredForUsername(user.getUsername())) { memberData.getTags().add(parteyUserTag.getTag()); } } @@ -179,8 +176,7 @@ public class RoomController extends DebugLogger { * @return the list */ @GetMapping("/sameWorld") - public List sameWorld(@RequestParam("roomUrl") String roomUrl, - HttpServletRequest request) { + public List sameWorld(@RequestParam("roomUrl") String roomUrl, HttpServletRequest request) { parteyApiAuthentication.authenticateRequest(request); debugPrintRequest(request); diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/WokaController.java b/partey/src/main/java/de/bstly/we/partey/api/controller/WokaController.java index 505dbed..a77a5c3 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/WokaController.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/WokaController.java @@ -39,8 +39,7 @@ public class WokaController extends DebugLogger { * @return the woka list */ @GetMapping("list") - public Map getWokaList(@RequestParam("roomUrl") String roomUrl, - HttpServletRequest request) { + public Map getWokaList(@RequestParam("roomUrl") String roomUrl, HttpServletRequest request) { parteyApiAuthentication.authenticateRequest(request); debugPrintRequest(request); diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/support/DebugLogger.java b/partey/src/main/java/de/bstly/we/partey/api/controller/support/DebugLogger.java index 9c5569d..5b9b59b 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/support/DebugLogger.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/support/DebugLogger.java @@ -37,19 +37,13 @@ public class DebugLogger { * @param payload the payload */ public void debugPrintRequest(HttpServletRequest request, Optional payload) { - logger.debug("Request: " - + request.getMethod().toUpperCase() - + " " - + request.getRequestURI()); + logger.debug("Request: " + request.getMethod().toUpperCase() + " " + request.getRequestURI()); logger.debug("Headers:"); for (Iterator it = request.getHeaderNames().asIterator(); it.hasNext();) { String headerName = it.next(); - logger.debug("\t" - + headerName - + ": " - + request.getHeader(headerName)); + logger.debug("\t" + headerName + ": " + request.getHeader(headerName)); } if (!request.getParameterMap().isEmpty()) { @@ -57,10 +51,7 @@ public class DebugLogger { for (Iterator it = request.getParameterNames().asIterator(); it.hasNext();) { String parameterName = it.next(); for (String value : request.getParameterValues(parameterName)) { - logger.debug("\t" - + parameterName - + ": " - + value); + logger.debug("\t" + parameterName + ": " + value); } } } @@ -77,12 +68,11 @@ public class DebugLogger { * Debug print response. * * @param response the response - * @param payload the payload + * @param payload the payload */ public void debugPrintResponse(HttpServletRequest response, Optional payload) { if (payload.isPresent()) { - logger.debug("Response: " - + response.getRequestURI()); + logger.debug("Response: " + response.getRequestURI()); logger.debug("Body:"); logger.debug(gson.toJson(payload.get())); logger.debug(""); diff --git a/partey/src/main/java/de/bstly/we/partey/api/controller/support/WokaListManager.java b/partey/src/main/java/de/bstly/we/partey/api/controller/support/WokaListManager.java index e866384..1b75f2d 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/controller/support/WokaListManager.java +++ b/partey/src/main/java/de/bstly/we/partey/api/controller/support/WokaListManager.java @@ -42,9 +42,7 @@ public class WokaListManager implements SmartInitializingSingleton { }.getType(); /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() - */ - /* + * * @see org.springframework.beans.factory.SmartInitializingSingleton# * afterSingletonsInstantiated() */ @@ -55,8 +53,7 @@ public class WokaListManager implements SmartInitializingSingleton { Resource resource = resourceLoader.getResource("classpath:woka.json"); if (resource.exists()) { - wokaList = gson.fromJson(new InputStreamReader(resource.getInputStream()), - wokaListType); + wokaList = gson.fromJson(new InputStreamReader(resource.getInputStream()), wokaListType); systemPropertyManager.add("partey.woka.list", gson.toJson(wokaList)); } diff --git a/partey/src/main/java/de/bstly/we/partey/api/security/ParteyApiAuthentication.java b/partey/src/main/java/de/bstly/we/partey/api/security/ParteyApiAuthentication.java index 58a4401..3066877 100644 --- a/partey/src/main/java/de/bstly/we/partey/api/security/ParteyApiAuthentication.java +++ b/partey/src/main/java/de/bstly/we/partey/api/security/ParteyApiAuthentication.java @@ -38,8 +38,7 @@ public class ParteyApiAuthentication { */ public void authenticateRequest(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth != null && auth.isAuthenticated() - && auth.getPrincipal() instanceof LocalUserDetails) { + if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof LocalUserDetails) { LocalUserDetails details = (LocalUserDetails) auth.getPrincipal(); if (!permissionManager.hasPermission(details.getUserId(), Permissions.ROLE_ADMIN)) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); diff --git a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyMapManager.java b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyMapManager.java index 2ae9672..5138967 100644 --- a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyMapManager.java +++ b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyMapManager.java @@ -55,9 +55,9 @@ public class ParteyMapManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ @@ -90,7 +90,7 @@ public class ParteyMapManager { /** * Parses the room. * - * @param url the url + * @param url the url * @param request the request * @return the room */ diff --git a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportManager.java b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportManager.java index ede302f..f471d2d 100644 --- a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportManager.java +++ b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportManager.java @@ -31,9 +31,9 @@ public class ParteyUserReportManager { * Creates the. * * @param reporter the reporter - * @param user the user - * @param comment the comment - * @param world the world + * @param user the user + * @param comment the comment + * @param world the world * @return the partey user report */ public ParteyUserReport create(Long reporter, Long user, String comment, String world) { @@ -55,9 +55,9 @@ public class ParteyUserReportManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ @@ -100,8 +100,8 @@ public class ParteyUserReportManager { * @param before the before */ public void deleteAllBefore(Instant before) { - parteyUserReportRepository.deleteAll( - parteyUserReportRepository.findAll(qParteyUserReport.created.before(before))); + parteyUserReportRepository + .deleteAll(parteyUserReportRepository.findAll(qParteyUserReport.created.before(before))); } } diff --git a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportModeratorManager.java b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportModeratorManager.java index 7edb463..608760f 100644 --- a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportModeratorManager.java +++ b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserReportModeratorManager.java @@ -42,14 +42,13 @@ public class ParteyUserReportModeratorManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ - public Page get(int page, int size, String sortBy, - boolean descending) { + public Page get(int page, int size, String sortBy, boolean descending) { PageRequest pageRequest = PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()); @@ -79,8 +78,7 @@ public class ParteyUserReportModeratorManager { User user = userManager.get(parteyUserReport.getUser()); String text = String.format(textTemplate, reporter.getUsername(), user.getUsername(), - parteyUserReport.getWorld(), parteyUserReport.getCreated(), - parteyUserReport.getComment()); + parteyUserReport.getWorld(), parteyUserReport.getCreated(), parteyUserReport.getComment()); List bcc = Lists.newArrayList(); for (ParteyUserReportModerator parteyUserReportModerator : parteyUserReportModeratorRepository diff --git a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTagManager.java b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTagManager.java index 8caed21..b907809 100644 --- a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTagManager.java +++ b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTagManager.java @@ -40,9 +40,9 @@ public class ParteyUserTagManager implements UserDataProvider { /** * Gets the all. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the all */ @@ -60,8 +60,7 @@ public class ParteyUserTagManager implements UserDataProvider { * @return the all by user id */ public List getAllByUserId(Long userId) { - return Lists - .newArrayList(parteyUserTagRepository.findAll(qParteyUserTag.target.eq(userId))); + return Lists.newArrayList(parteyUserTagRepository.findAll(qParteyUserTag.target.eq(userId))); } /** @@ -77,7 +76,7 @@ public class ParteyUserTagManager implements UserDataProvider { /** * Gets the non expired by user id. * - * @param userId the user id + * @param userId the user id * @param upcoming the upcoming * @return the non expired by user id */ @@ -88,8 +87,7 @@ public class ParteyUserTagManager implements UserDataProvider { query.and(qParteyUserTag.expires.isNull().or(qParteyUserTag.expires.after(Instant.now()))); if (!upcoming) { - query.and( - qParteyUserTag.starts.isNull().or(qParteyUserTag.starts.before(Instant.now()))); + query.and(qParteyUserTag.starts.isNull().or(qParteyUserTag.starts.before(Instant.now()))); } return Lists.newArrayList(parteyUserTagRepository.findAll(query.getValue())); @@ -103,9 +101,7 @@ public class ParteyUserTagManager implements UserDataProvider { */ public List getAllForUsername(String username) { User user = userManager.getByUsername(username); - Assert.notNull(user, "invalid username: '" - + username - + "'!"); + Assert.notNull(user, "invalid username: '" + username + "'!"); return getAllByUserId(user.getId()); } @@ -129,9 +125,7 @@ public class ParteyUserTagManager implements UserDataProvider { */ public List getNonExpiredForUsername(String username, boolean upcoming) { User user = userManager.getByUsername(username); - Assert.notNull(user, "invalid username: '" - + username - + "'!"); + Assert.notNull(user, "invalid username: '" + username + "'!"); return getNonExpiredByUserId(user.getId(), upcoming); } @@ -151,8 +145,7 @@ public class ParteyUserTagManager implements UserDataProvider { * @param parteyUserTag the partey user tag */ public void delete(ParteyUserTag parteyUserTag) { - parteyUserTagRepository - .deleteById(new ParteyUserTagId(parteyUserTag.getTarget(), parteyUserTag.getTag())); + parteyUserTagRepository.deleteById(new ParteyUserTagId(parteyUserTag.getTarget(), parteyUserTag.getTag())); } /** @@ -161,8 +154,7 @@ public class ParteyUserTagManager implements UserDataProvider { * @param target the target */ public void deleteAllForTarget(Long target) { - parteyUserTagRepository - .deleteAll(parteyUserTagRepository.findAll(qParteyUserTag.target.eq(target))); + parteyUserTagRepository.deleteAll(parteyUserTagRepository.findAll(qParteyUserTag.target.eq(target))); } /* diff --git a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTexturesManager.java b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTexturesManager.java index 30769c5..884401d 100644 --- a/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTexturesManager.java +++ b/partey/src/main/java/de/bstly/we/partey/businesslogic/ParteyUserTexturesManager.java @@ -32,9 +32,9 @@ public class ParteyUserTexturesManager implements UserDataProvider { /** * Gets the all. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the all */ @@ -52,8 +52,7 @@ public class ParteyUserTexturesManager implements UserDataProvider { * @return the by target */ public ParteyUserTextures getByTarget(Long userId) { - return parteyUserTexturesRepository.findOne(qParteyUserTextures.target.eq(userId)) - .orElse(null); + return parteyUserTexturesRepository.findOne(qParteyUserTextures.target.eq(userId)).orElse(null); } /** @@ -63,8 +62,7 @@ public class ParteyUserTexturesManager implements UserDataProvider { * @return the by username */ public ParteyUserTextures getByUsername(String username) { - return parteyUserTexturesRepository.findOne(qParteyUserTextures.username.eq(username)) - .orElse(null); + return parteyUserTexturesRepository.findOne(qParteyUserTextures.username.eq(username)).orElse(null); } /** diff --git a/partey/src/main/java/de/bstly/we/partey/controller/MapManagementController.java b/partey/src/main/java/de/bstly/we/partey/controller/MapManagementController.java index ec97e57..3ea7f75 100644 --- a/partey/src/main/java/de/bstly/we/partey/controller/MapManagementController.java +++ b/partey/src/main/java/de/bstly/we/partey/controller/MapManagementController.java @@ -46,12 +46,11 @@ public class MapManagementController extends BaseController { @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping public Page getParteyMaps(@RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter) { - Page page = parteyMapManager.get(pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); + Page page = parteyMapManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), + sortParameter.orElse("id"), descParameter.orElse(false)); return page; diff --git a/partey/src/main/java/de/bstly/we/partey/controller/UserReportManagementController.java b/partey/src/main/java/de/bstly/we/partey/controller/UserReportManagementController.java index 3aa35a0..c7a5c8f 100644 --- a/partey/src/main/java/de/bstly/we/partey/controller/UserReportManagementController.java +++ b/partey/src/main/java/de/bstly/we/partey/controller/UserReportManagementController.java @@ -43,14 +43,12 @@ public class UserReportManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getParteyUserReports( - @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + public Page getParteyUserReports(@RequestParam("page") Optional pageParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter) { - Page page = parteyUserReportManager.get(pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); + Page page = parteyUserReportManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), + sortParameter.orElse("id"), descParameter.orElse(false)); return page; @@ -64,8 +62,7 @@ public class UserReportManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping - public ParteyUserReport createOrUpdateParteyUserReport( - @RequestBody ParteyUserReport parteyUserReport) { + public ParteyUserReport createOrUpdateParteyUserReport(@RequestBody ParteyUserReport parteyUserReport) { return parteyUserReportManager.save(parteyUserReport); } @@ -87,8 +84,7 @@ public class UserReportManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping() - public void deleteAllParteyUserReport( - @RequestParam("before") Optional beforeParameter) { + public void deleteAllParteyUserReport(@RequestParam("before") Optional beforeParameter) { if (beforeParameter.isPresent()) { parteyUserReportManager.deleteAllBefore(beforeParameter.get()); } else { diff --git a/partey/src/main/java/de/bstly/we/partey/controller/UserReportModeratorManagementController.java b/partey/src/main/java/de/bstly/we/partey/controller/UserReportModeratorManagementController.java index ba2c60f..f4a8721 100644 --- a/partey/src/main/java/de/bstly/we/partey/controller/UserReportModeratorManagementController.java +++ b/partey/src/main/java/de/bstly/we/partey/controller/UserReportModeratorManagementController.java @@ -44,13 +44,11 @@ public class UserReportModeratorManagementController extends BaseController { @GetMapping public Page getParteyUserReportModerators( @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter) { - Page page = parteyUserReportModeratorManager.get( - pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"), - descParameter.orElse(false)); + Page page = parteyUserReportModeratorManager.get(pageParameter.orElse(0), + sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); return page; diff --git a/partey/src/main/java/de/bstly/we/partey/controller/UserTagManagementController.java b/partey/src/main/java/de/bstly/we/partey/controller/UserTagManagementController.java index 46b491c..dae8fb0 100644 --- a/partey/src/main/java/de/bstly/we/partey/controller/UserTagManagementController.java +++ b/partey/src/main/java/de/bstly/we/partey/controller/UserTagManagementController.java @@ -50,15 +50,12 @@ public class UserTagManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getParteyUserTags( - @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + public Page getParteyUserTags(@RequestParam("page") Optional pageParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter) { - Page page = parteyUserTagManager.getAll(pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("target"), - descParameter.orElse(false)); + Page page = parteyUserTagManager.getAll(pageParameter.orElse(0), sizeParameter.orElse(10), + sortParameter.orElse("target"), descParameter.orElse(false)); return page; } @@ -71,8 +68,7 @@ public class UserTagManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("{username}") - public List getParteyUserTagsForTarget( - @PathVariable("username") String username) { + public List getParteyUserTagsForTarget(@PathVariable("username") String username) { User user = userManager.getByUsername(username); if (user == null) { @@ -90,8 +86,7 @@ public class UserTagManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("{username}/active") - public List getNonExpiredParteyUserTagsForTarget( - @PathVariable("username") String username) { + public List getNonExpiredParteyUserTagsForTarget(@PathVariable("username") String username) { User user = userManager.getByUsername(username); if (user == null) { @@ -109,8 +104,7 @@ public class UserTagManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("{username}/upcoming") - public List getUpcomingParteyUserTagsForTarget( - @PathVariable("username") String username) { + public List getUpcomingParteyUserTagsForTarget(@PathVariable("username") String username) { User user = userManager.getByUsername(username); if (user == null) { diff --git a/partey/src/main/java/de/bstly/we/partey/model/ParteyUserTag.java b/partey/src/main/java/de/bstly/we/partey/model/ParteyUserTag.java index 5ba7181..238852c 100644 --- a/partey/src/main/java/de/bstly/we/partey/model/ParteyUserTag.java +++ b/partey/src/main/java/de/bstly/we/partey/model/ParteyUserTag.java @@ -145,7 +145,7 @@ public class ParteyUserTag implements UserData { * Instantiates a new partey user tag id. * * @param target the target - * @param tag the tag + * @param tag the tag */ public ParteyUserTagId(Long target, String tag) { super(); diff --git a/partey/src/main/java/de/bstly/we/partey/repository/ParteyMapRepository.java b/partey/src/main/java/de/bstly/we/partey/repository/ParteyMapRepository.java index 69153b5..2cb7b56 100755 --- a/partey/src/main/java/de/bstly/we/partey/repository/ParteyMapRepository.java +++ b/partey/src/main/java/de/bstly/we/partey/repository/ParteyMapRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.partey.model.ParteyMap; * The Interface ParteyMapRepository. */ @Repository -public interface ParteyMapRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface ParteyMapRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserReportModeratorRepository.java b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserReportModeratorRepository.java index 6a1add0..7adff03 100644 --- a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserReportModeratorRepository.java +++ b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserReportModeratorRepository.java @@ -14,6 +14,5 @@ import de.bstly.we.partey.model.ParteyUserReportModerator; */ @Repository public interface ParteyUserReportModeratorRepository - extends JpaRepository, - QuerydslPredicateExecutor { + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTagRepository.java b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTagRepository.java index 54c779d..b7ef6a5 100644 --- a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTagRepository.java +++ b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTagRepository.java @@ -14,6 +14,6 @@ import de.bstly.we.partey.model.ParteyUserTag.ParteyUserTagId; * The Interface ParteyUserTagRepository. */ @Repository -public interface ParteyUserTagRepository extends JpaRepository, - QuerydslPredicateExecutor { +public interface ParteyUserTagRepository + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTexturesRepository.java b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTexturesRepository.java index e10a009..b7cbc8d 100644 --- a/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTexturesRepository.java +++ b/partey/src/main/java/de/bstly/we/partey/repository/ParteyUserTexturesRepository.java @@ -13,6 +13,6 @@ import de.bstly.we.partey.model.ParteyUserTextures; * The Interface ParteyUserTexturesRepository. */ @Repository -public interface ParteyUserTexturesRepository extends JpaRepository, - QuerydslPredicateExecutor { +public interface ParteyUserTexturesRepository + extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/partey/src/main/java/de/bstly/we/partey/timeslot/businesslogic/TimeslotManager.java b/partey/src/main/java/de/bstly/we/partey/timeslot/businesslogic/TimeslotManager.java index 525bb18..04d181a 100644 --- a/partey/src/main/java/de/bstly/we/partey/timeslot/businesslogic/TimeslotManager.java +++ b/partey/src/main/java/de/bstly/we/partey/timeslot/businesslogic/TimeslotManager.java @@ -64,21 +64,20 @@ public class TimeslotManager implements UserDataProvider { /** * Gets the. * - * @param owner the owner + * @param owner the owner * @param invertOwner the invert owner - * @param after the after - * @param type the type - * @param visibility the visibility - * @param search the search - * @param page the page - * @param size the size - * @param sortBy the sort by - * @param descending the descending + * @param after the after + * @param type the type + * @param visibility the visibility + * @param search the search + * @param page the page + * @param size the size + * @param sortBy the sort by + * @param descending the descending * @return the page */ - public Page get(Long owner, boolean invertOwner, Instant after, TimeslotType type, - Visibility visibility, String search, int page, int size, String sortBy, - boolean descending) { + public Page get(Long owner, boolean invertOwner, Instant after, TimeslotType type, Visibility visibility, + String search, int page, int size, String sortBy, boolean descending) { PageRequest pageRequest = PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()); @@ -106,8 +105,7 @@ public class TimeslotManager implements UserDataProvider { } if (StringUtils.hasText(search)) { - query.and(qTimeslot.title.containsIgnoreCase(search) - .or(qTimeslot.description.containsIgnoreCase(search))); + query.and(qTimeslot.title.containsIgnoreCase(search).or(qTimeslot.description.containsIgnoreCase(search))); } if (query.hasValue()) { @@ -124,8 +122,8 @@ public class TimeslotManager implements UserDataProvider { * @return the long */ public long quota(Long owner) { - return timeslotRepository.count(qTimeslot.owner.eq(owner).and( - qTimeslot.starts.after(Instant.now()).or(qTimeslot.ends.after(Instant.now())))); + return timeslotRepository.count(qTimeslot.owner.eq(owner) + .and(qTimeslot.starts.after(Instant.now()).or(qTimeslot.ends.after(Instant.now())))); } /** @@ -135,8 +133,7 @@ public class TimeslotManager implements UserDataProvider { * @return the timeslot */ public Timeslot save(Timeslot timeslot) { - Assert.isTrue(timeslot.getStarts().isBefore(timeslot.getEnds()), - "starts must be before ends."); + Assert.isTrue(timeslot.getStarts().isBefore(timeslot.getEnds()), "starts must be before ends."); return timeslotRepository.save(timeslot); } @@ -181,8 +178,8 @@ public class TimeslotManager implements UserDataProvider { */ @Scheduled(cron = "0 */5 * * * *") protected void clearEndedTimeslots() { - timeslotRepository.deleteAll(timeslotRepository - .findAll(qTimeslot.clearAfter.isTrue().and(qTimeslot.ends.before(Instant.now())))); + timeslotRepository.deleteAll( + timeslotRepository.findAll(qTimeslot.clearAfter.isTrue().and(qTimeslot.ends.before(Instant.now())))); } } diff --git a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotController.java b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotController.java index 64140d1..0a7a058 100644 --- a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotController.java +++ b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotController.java @@ -57,22 +57,21 @@ public class TimeslotController extends BaseController { /** * Gets the timeslots. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParameter the sort parameter - * @param descParameter the desc parameter - * @param ownerParameter the owner parameter - * @param afterParameter the after parameter - * @param typeParameter the type parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParameter the sort parameter + * @param descParameter the desc parameter + * @param ownerParameter the owner parameter + * @param afterParameter the after parameter + * @param typeParameter the type parameter * @param visibilityParameter the visibility parameter - * @param searchParameter the search parameter + * @param searchParameter the search parameter * @return the timeslots */ @PreAuthorize("isAuthenticated()") @GetMapping public Page getTimeslots(@RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter, @RequestParam("owner") Optional ownerParameter, @RequestParam("after") Optional afterParameter, @@ -92,9 +91,8 @@ public class TimeslotController extends BaseController { } Page page = timeslotManager.get(ownerId, - ownerParameter.isPresent() && "others".equals(ownerParameter.get()), - afterParameter.orElse(null), typeParameter.orElse(null), - visibilityParameter.orElse(null), searchParameter.orElse(null), + ownerParameter.isPresent() && "others".equals(ownerParameter.get()), afterParameter.orElse(null), + typeParameter.orElse(null), visibilityParameter.orElse(null), searchParameter.orElse(null), pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); @@ -131,8 +129,7 @@ public class TimeslotController extends BaseController { @GetMapping("/quota") public long quota() { Quota timeslotQuota = quotaManager.get(getCurrentUserId(), ParteyQuotas.PARTEY_TIMESLOT); - return timeslotQuota == null ? 0 - : timeslotQuota.getValue() - timeslotManager.quota(getCurrentUserId()); + return timeslotQuota == null ? 0 : timeslotQuota.getValue() - timeslotManager.quota(getCurrentUserId()); } /** @@ -150,8 +147,7 @@ public class TimeslotController extends BaseController { } Quota timeslotQuota = quotaManager.get(getCurrentUserId(), ParteyQuotas.PARTEY_TIMESLOT); - if (timeslotQuota == null - || timeslotQuota.getValue() < timeslotManager.quota(getCurrentUserId())) { + if (timeslotQuota == null || timeslotQuota.getValue() < timeslotManager.quota(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } @@ -201,12 +197,9 @@ public class TimeslotController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - if (timeslot.getStarts().isAfter(Instant.now()) - || timeslot.getEnds().isAfter(Instant.now())) { - Quota timeslotQuota = quotaManager.get(getCurrentUserId(), - ParteyQuotas.PARTEY_TIMESLOT); - if (timeslotQuota == null - || timeslotQuota.getValue() < timeslotManager.quota(getCurrentUserId())) { + if (timeslot.getStarts().isAfter(Instant.now()) || timeslot.getEnds().isAfter(Instant.now())) { + Quota timeslotQuota = quotaManager.get(getCurrentUserId(), ParteyQuotas.PARTEY_TIMESLOT); + if (timeslotQuota == null || timeslotQuota.getValue() < timeslotManager.quota(getCurrentUserId())) { throw new EntityResponseStatusException(HttpStatus.CONFLICT); } } diff --git a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotManagementController.java b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotManagementController.java index 6282b2a..9f80f97 100644 --- a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotManagementController.java +++ b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/TimeslotManagementController.java @@ -44,25 +44,23 @@ public class TimeslotManagementController extends BaseController { /** * Gets the timeslots. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParameter the sort parameter - * @param descParameter the desc parameter - * @param ownerParameter the owner parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParameter the sort parameter + * @param descParameter the desc parameter + * @param ownerParameter the owner parameter * @param invertOwnerParameter the invert owner parameter - * @param afterParameter the after parameter - * @param typeParameter the type parameter - * @param visibilityParameter the visibility parameter - * @param searchParameter the search parameter + * @param afterParameter the after parameter + * @param typeParameter the type parameter + * @param visibilityParameter the visibility parameter + * @param searchParameter the search parameter * @return the timeslots */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping public Page getTimeslots(@RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, - @RequestParam("desc") Optional descParameter, - @RequestParam("owner") Optional ownerParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, + @RequestParam("desc") Optional descParameter, @RequestParam("owner") Optional ownerParameter, @RequestParam("owner-invert") Optional invertOwnerParameter, @RequestParam("after") Optional afterParameter, @RequestParam("type") Optional typeParameter, @@ -70,9 +68,8 @@ public class TimeslotManagementController extends BaseController { @RequestParam("search") Optional searchParameter) { Page page = timeslotManager.get(ownerParameter.orElse(null), - invertOwnerParameter.isPresent() && invertOwnerParameter.get(), - afterParameter.orElse(null), typeParameter.orElse(null), - visibilityParameter.orElse(null), searchParameter.orElse(null), + invertOwnerParameter.isPresent() && invertOwnerParameter.get(), afterParameter.orElse(null), + typeParameter.orElse(null), visibilityParameter.orElse(null), searchParameter.orElse(null), pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false)); diff --git a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/validation/TimeslotValidator.java b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/validation/TimeslotValidator.java index 70bda75..92c3549 100644 --- a/partey/src/main/java/de/bstly/we/partey/timeslot/controller/validation/TimeslotValidator.java +++ b/partey/src/main/java/de/bstly/we/partey/timeslot/controller/validation/TimeslotValidator.java @@ -61,7 +61,7 @@ public class TimeslotValidator implements Validator { * Validate time. * * @param timeslot the timeslot - * @param errors the errors + * @param errors the errors */ public void validateTime(Timeslot timeslot, Errors errors) { if (timeslot.getStarts() == null) { @@ -89,29 +89,23 @@ public class TimeslotValidator implements Validator { switch (timeslot.getType()) { case AUDIO: case AUDIO_STREAM: - timeQuery.and(qTimeslot.type - .in(Lists.newArrayList(TimeslotType.AUDIO, TimeslotType.AUDIO_STREAM))); + timeQuery.and(qTimeslot.type.in(Lists.newArrayList(TimeslotType.AUDIO, TimeslotType.AUDIO_STREAM))); break; case VIDEO: case VIDEO_STREAM: - timeQuery.and(qTimeslot.type - .in(Lists.newArrayList(TimeslotType.VIDEO, TimeslotType.VIDEO_STREAM))); + timeQuery.and(qTimeslot.type.in(Lists.newArrayList(TimeslotType.VIDEO, TimeslotType.VIDEO_STREAM))); break; } // ends after start - timeQuery - .and(qTimeslot.ends.after(timeslot.getStarts() - .minus(systemPropertyManager.getLong(TimeslotManager.TIMESLOT_TOLERANCE, - TimeslotManager.TIMESLOT_TOLERANCE_DEFAULT), - ChronoUnit.MINUTES))); + timeQuery.and(qTimeslot.ends + .after(timeslot.getStarts().minus(systemPropertyManager.getLong(TimeslotManager.TIMESLOT_TOLERANCE, + TimeslotManager.TIMESLOT_TOLERANCE_DEFAULT), ChronoUnit.MINUTES))); // starts before end - timeQuery - .and(qTimeslot.starts.before(timeslot.getEnds() - .plus(systemPropertyManager.getLong(TimeslotManager.TIMESLOT_TOLERANCE, - TimeslotManager.TIMESLOT_TOLERANCE_DEFAULT), - ChronoUnit.MINUTES))); + timeQuery.and(qTimeslot.starts + .before(timeslot.getEnds().plus(systemPropertyManager.getLong(TimeslotManager.TIMESLOT_TOLERANCE, + TimeslotManager.TIMESLOT_TOLERANCE_DEFAULT), ChronoUnit.MINUTES))); if (timeslot.getId() != null && timeslotRepository.existsById(timeslot.getId())) { timeQuery.and(qTimeslot.id.ne(timeslot.getId())); @@ -120,14 +114,11 @@ public class TimeslotValidator implements Validator { if (timeslotRepository.exists(timeQuery.getValue())) { errors.rejectValue("starts", "ALREADY_EXISTS"); errors.rejectValue("ends", "ALREADY_EXISTS"); - } else if (((timeslot.getEnds().getEpochSecond() - - timeslot.getStarts().getEpochSecond()) / 60) > systemPropertyManager.getLong( - TimeslotManager.TIMESLOT_MINUTES, + } else if (((timeslot.getEnds().getEpochSecond() - timeslot.getStarts().getEpochSecond()) + / 60) > systemPropertyManager.getLong(TimeslotManager.TIMESLOT_MINUTES, TimeslotManager.TIMESLOT_MINUTES_DEFAULT)) { - errors.rejectValue("ends", "TOO_LONG", - String.valueOf( - systemPropertyManager.getLong(TimeslotManager.TIMESLOT_MINUTES, - TimeslotManager.TIMESLOT_MINUTES_DEFAULT))); + errors.rejectValue("ends", "TOO_LONG", String.valueOf(systemPropertyManager + .getLong(TimeslotManager.TIMESLOT_MINUTES, TimeslotManager.TIMESLOT_MINUTES_DEFAULT))); } } } @@ -136,7 +127,7 @@ public class TimeslotValidator implements Validator { * Validate type. * * @param timeslot the timeslot - * @param errors the errors + * @param errors the errors */ public void validateType(Timeslot timeslot, Errors errors) { if (timeslot.getId() != null && timeslotRepository.existsById(timeslot.getId())) { @@ -165,7 +156,7 @@ public class TimeslotValidator implements Validator { * Validate share. * * @param timeslot the timeslot - * @param errors the errors + * @param errors the errors */ public void validateShare(Timeslot timeslot, Errors errors) { timeslot.setStream(null); @@ -180,7 +171,7 @@ public class TimeslotValidator implements Validator { * Validate type audio stream. * * @param timeslot the timeslot - * @param errors the errors + * @param errors the errors */ public void validateTypeAudioStream(Timeslot timeslot, Errors errors) { timeslot.setStream(null); @@ -199,7 +190,7 @@ public class TimeslotValidator implements Validator { * Validate type video stream. * * @param timeslot the timeslot - * @param errors the errors + * @param errors the errors */ public void validateTypeVideoStream(Timeslot timeslot, Errors errors) { timeslot.setSecret(null); diff --git a/partey/src/main/java/de/bstly/we/partey/timeslot/repository/TimeslotRepository.java b/partey/src/main/java/de/bstly/we/partey/timeslot/repository/TimeslotRepository.java index b1ccd52..9f2b6a0 100755 --- a/partey/src/main/java/de/bstly/we/partey/timeslot/repository/TimeslotRepository.java +++ b/partey/src/main/java/de/bstly/we/partey/timeslot/repository/TimeslotRepository.java @@ -13,6 +13,5 @@ import de.bstly.we.partey.timeslot.model.Timeslot; * The Interface TimeslotRepository. */ @Repository -public interface TimeslotRepository - extends JpaRepository, QuerydslPredicateExecutor { +public interface TimeslotRepository extends JpaRepository, QuerydslPredicateExecutor { } diff --git a/pom.xml b/pom.xml index d88cd1f..a4149fb 100755 --- a/pom.xml +++ b/pom.xml @@ -12,14 +12,14 @@ UTF-8 11 - 2.17.1 - 1.6.5-SNAPSHOT + 2.17.2 + 1.8.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent - 2.5.5 + 2.6.6 diff --git a/services/src/main/java/de/bstly/we/services/businesslogic/ServiceManager.java b/services/src/main/java/de/bstly/we/services/businesslogic/ServiceManager.java index 65b32e0..202849c 100644 --- a/services/src/main/java/de/bstly/we/services/businesslogic/ServiceManager.java +++ b/services/src/main/java/de/bstly/we/services/businesslogic/ServiceManager.java @@ -73,8 +73,7 @@ public class ServiceManager { if (permissionManager.hasPermission(target, Permissions.ROLE_ADMIN)) { services.addAll(serviceRepository.findAll()); - for (OidcClient client : oidcClientRepository - .findAll(qOidcClient.loginUrl.isNotNull())) { + for (OidcClient client : oidcClientRepository.findAll(qOidcClient.loginUrl.isNotNull())) { Service service = new Service(client.getClientName(), client.getLoginUrl()); service.setCategory(client.getCategory()); services.add(service); @@ -85,17 +84,15 @@ public class ServiceManager { for (Permission permission : permissionManager.getNotExpiresByTarget(target)) { if (serviceRepository.existsById(permission.getName())) { services.add(get(permission.getName())); - } else if (oidcClientRepository.exists(qOidcClient.clientName.eq(permission.getName()) - .and(qOidcClient.loginUrl.isNotNull()))) { - OidcClient client = oidcClientRepository - .findOne(qOidcClient.clientName.eq(permission.getName())).get(); + } else if (oidcClientRepository + .exists(qOidcClient.clientName.eq(permission.getName()).and(qOidcClient.loginUrl.isNotNull()))) { + OidcClient client = oidcClientRepository.findOne(qOidcClient.clientName.eq(permission.getName())).get(); Service service = new Service(client.getClientName(), client.getLoginUrl()); service.setCategory(client.getCategory()); services.add(service); } - for (Service service : serviceRepository - .findAll(qService.permission.eq(permission.getName()))) { + for (Service service : serviceRepository.findAll(qService.permission.eq(permission.getName()))) { services.add(service); } } @@ -105,8 +102,7 @@ public class ServiceManager { services.add(service); } - for (OidcClient client : oidcClientRepository - .findAll(qOidcClient.alwaysPermitted.isTrue())) { + for (OidcClient client : oidcClientRepository.findAll(qOidcClient.alwaysPermitted.isTrue())) { Service service = new Service(client.getClientName(), client.getLoginUrl()); service.setCategory(client.getCategory()); services.add(service); @@ -128,9 +124,9 @@ public class ServiceManager { /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending * @return the page */ diff --git a/services/src/main/java/de/bstly/we/services/model/Service.java b/services/src/main/java/de/bstly/we/services/model/Service.java index 9b8142e..f41f450 100644 --- a/services/src/main/java/de/bstly/we/services/model/Service.java +++ b/services/src/main/java/de/bstly/we/services/model/Service.java @@ -41,7 +41,7 @@ public class Service { * Instantiates a new service. * * @param name the name - * @param url the url + * @param url the url */ public Service(String name, String url) { super(); diff --git a/urlshortener/src/main/java/de/bstly/we/urlshortener/businesslogic/ShortenedUrlManager.java b/urlshortener/src/main/java/de/bstly/we/urlshortener/businesslogic/ShortenedUrlManager.java index 73a1841..71f57b1 100644 --- a/urlshortener/src/main/java/de/bstly/we/urlshortener/businesslogic/ShortenedUrlManager.java +++ b/urlshortener/src/main/java/de/bstly/we/urlshortener/businesslogic/ShortenedUrlManager.java @@ -56,9 +56,9 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData public static final String SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND = "urlShortener.notFoundRedirect"; public static final String SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD = "urlShortener.passwordRedirect"; - /* - * @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() + * @see org.springframework.beans.factory.SmartInitializingSingleton# + * afterSingletonsInstantiated() */ @Override public void afterSingletonsInstantiated() { @@ -105,74 +105,71 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData /** * Gets the. * - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending - * @param search the search + * @param search the search * @return the page */ - public Page get(int page, int size, String sortBy, boolean descending, - String search) { + public Page get(int page, int size, String sortBy, boolean descending, String search) { if (StringUtils.hasText(search)) { return shortenedUrlRepository.findAll( - qShortenedUrl.note.containsIgnoreCase(search) - .or(qShortenedUrl.url.containsIgnoreCase(search)) + qShortenedUrl.note.containsIgnoreCase(search).or(qShortenedUrl.url.containsIgnoreCase(search)) .or(qShortenedUrl.link.containsIgnoreCase(search)), - PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() - : Sort.by(sortBy).ascending())); + PageRequest.of(page, size, + descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } - return shortenedUrlRepository.findAll(PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return shortenedUrlRepository.findAll( + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Gets the for user id. * - * @param userId the user id - * @param page the page - * @param size the size - * @param sortBy the sort by + * @param userId the user id + * @param page the page + * @param size the size + * @param sortBy the sort by * @param descending the descending - * @param search the search + * @param search the search * @return the for user id */ - public Page getForUserId(Long userId, int page, int size, String sortBy, - boolean descending, String search) { + public Page getForUserId(Long userId, int page, int size, String sortBy, boolean descending, + String search) { // delete expired urls - shortenedUrlRepository.deleteAll(shortenedUrlRepository.findAll( - qShortenedUrl.owner.eq(userId).and(qShortenedUrl.expires.before(Instant.now())))); + shortenedUrlRepository.deleteAll(shortenedUrlRepository + .findAll(qShortenedUrl.owner.eq(userId).and(qShortenedUrl.expires.before(Instant.now())))); BooleanBuilder query = new BooleanBuilder(); query.and(qShortenedUrl.owner.eq(userId)); if (StringUtils.hasText(search)) { - query.and(qShortenedUrl.note.containsIgnoreCase(search) - .or(qShortenedUrl.url.containsIgnoreCase(search)) + query.and(qShortenedUrl.note.containsIgnoreCase(search).or(qShortenedUrl.url.containsIgnoreCase(search)) .or(qShortenedUrl.link.containsIgnoreCase(search))); } - return shortenedUrlRepository.findAll(query.getValue(), PageRequest.of(page, size, - descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); + return shortenedUrlRepository.findAll(query.getValue(), + PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); } /** * Creates the. * - * @param owner the owner - * @param url the url - * @param note the note - * @param code the code - * @param expires the expires - * @param password the password + * @param owner the owner + * @param url the url + * @param note the note + * @param code the code + * @param expires the expires + * @param password the password * @param queryParameters the query parameters - * @param quota the quota + * @param quota the quota * @return the shortened url */ - public ShortenedUrl create(Long owner, String url, String note, String code, Instant expires, - String password, boolean queryParameters, boolean quota) { + public ShortenedUrl create(Long owner, String url, String note, String code, Instant expires, String password, + boolean queryParameters, boolean quota) { ShortenedUrl shortenedUrl = new ShortenedUrl(); shortenedUrl.setOwner(owner); @@ -204,8 +201,7 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData shortenedUrl = shortenedUrlRepository.save(shortenedUrl); if (quota) { - Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(), - ShortenedUrlQuotas.URL_SHORTENER); + Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(), ShortenedUrlQuotas.URL_SHORTENER); if (shortenedUrlsQuota != null) { shortenedUrlsQuota.setValue(shortenedUrlsQuota.getValue() - 1); quotaManager.update(shortenedUrlsQuota); @@ -235,15 +231,14 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData * Delete. * * @param shortenedUrl the shortened url - * @param quota the quota + * @param quota the quota */ public void delete(ShortenedUrl shortenedUrl, boolean quota) { if (quota) { - Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(), - ShortenedUrlQuotas.URL_SHORTENER); + Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(), ShortenedUrlQuotas.URL_SHORTENER); if (shortenedUrlsQuota == null) { - shortenedUrlsQuota = quotaManager.create(shortenedUrl.getOwner(), - ShortenedUrlQuotas.URL_SHORTENER, 0, "#", true); + shortenedUrlsQuota = quotaManager.create(shortenedUrl.getOwner(), ShortenedUrlQuotas.URL_SHORTENER, 0, + "#", true); } shortenedUrlsQuota.setValue(shortenedUrlsQuota.getValue() + 1); @@ -268,7 +263,6 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData } } - /* * @see de.bstly.we.businesslogic.UserDataProvider#getId() */ @@ -277,7 +271,6 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData return "shortend-urls"; } - /* * @see de.bstly.we.businesslogic.UserDataProvider#getUserData(java.lang.Long) */ @@ -290,7 +283,6 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData return result; } - /* * @see de.bstly.we.businesslogic.UserDataProvider#purgeUserData(java.lang.Long) */ @@ -306,8 +298,7 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData */ @Scheduled(cron = "0 */5 * * * *") public void clearOrUpdateShortenedUrls() { - shortenedUrlRepository.deleteAll( - shortenedUrlRepository.findAll(qShortenedUrl.expires.before(Instant.now()))); + shortenedUrlRepository.deleteAll(shortenedUrlRepository.findAll(qShortenedUrl.expires.before(Instant.now()))); String link = systemPropertyManager.get(SYSTEM_PROPERTY_URL_SHORTENER_LINK); String linkRegex = ""; @@ -316,9 +307,8 @@ public class ShortenedUrlManager implements SmartInitializingSingleton, UserData } if (StringUtils.hasText(linkRegex)) { - for (ShortenedUrl shortenedUrl : shortenedUrlRepository - .findAll(qShortenedUrl.link.isNull().or(qShortenedUrl.link.isEmpty() - .or(qShortenedUrl.link.matches(linkRegex).not())))) { + for (ShortenedUrl shortenedUrl : shortenedUrlRepository.findAll(qShortenedUrl.link.isNull() + .or(qShortenedUrl.link.isEmpty().or(qShortenedUrl.link.matches(linkRegex).not())))) { shortenedUrl.setLink(String.format(link, shortenedUrl.getCode())); shortenedUrl = shortenedUrlRepository.save(shortenedUrl); } diff --git a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlController.java b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlController.java index d38cb82..efd925a 100644 --- a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlController.java +++ b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlController.java @@ -66,8 +66,8 @@ public class ShortenedUrlController extends BaseController { /** * Gets the shortened url link. * - * @param code the code - * @param request the request + * @param code the code + * @param request the request * @param response the response * @return the shortened url link * @throws IOException Signals that an I/O exception has occurred. @@ -79,19 +79,18 @@ public class ShortenedUrlController extends BaseController { try { if (shortenedUrl == null) { - if (StringUtils.hasText(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND))) { - response.sendRedirect(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND)); + if (StringUtils.hasText( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND))) { + response.sendRedirect( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND)); } else { response.sendError(404, "code not found"); } } else if (StringUtils.hasText(shortenedUrl.getPasswordHash())) { - if (StringUtils.hasText(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD))) { + if (StringUtils.hasText( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD))) { response.sendRedirect(String.format( - systemPropertyManager.get( - ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD), + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD), shortenedUrl.getCode())); } else { response.sendError(401, "password protected"); @@ -107,25 +106,25 @@ public class ShortenedUrlController extends BaseController { /** * Gets the protected shortened url link. * - * @param code the code + * @param code the code * @param password the password - * @param request the request + * @param request the request * @param response the response * @return the protected shortened url link * @throws IOException Signals that an I/O exception has occurred. */ @PostMapping("/{code}") public void getProtectedShortenedUrlLink(@PathVariable("code") String code, - @ModelAttribute("password") String password, HttpServletRequest request, - HttpServletResponse response) throws IOException { + @ModelAttribute("password") String password, HttpServletRequest request, HttpServletResponse response) + throws IOException { ShortenedUrl shortenedUrl = shortenedUrlManager.get(code); try { if (shortenedUrl == null) { - if (StringUtils.hasText(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND))) { - response.sendRedirect(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND)); + if (StringUtils.hasText( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND))) { + response.sendRedirect( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_NOT_FOUND)); } else { response.sendError(404, "code not found"); } @@ -133,11 +132,10 @@ public class ShortenedUrlController extends BaseController { || passwordEncoder.matches(password, shortenedUrl.getPasswordHash())) { sendValidRedirect(shortenedUrl, request, response); } else { - if (StringUtils.hasText(systemPropertyManager - .get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD))) { + if (StringUtils.hasText( + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD))) { String passwordErrorUrl = String.format( - systemPropertyManager.get( - ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD), + systemPropertyManager.get(ShortenedUrlManager.SYSTEM_PROPERTY_URL_SHORTENER_PASSWORD), shortenedUrl.getCode()); URI passwordErrorUri; try { @@ -165,8 +163,8 @@ public class ShortenedUrlController extends BaseController { * Send valid redirect. * * @param shortenedUrl the shortened url - * @param request the request - * @param response the response + * @param request the request + * @param response the response * @throws IOException Signals that an I/O exception has occurred. */ protected void sendValidRedirect(ShortenedUrl shortenedUrl, HttpServletRequest request, @@ -218,30 +216,26 @@ public class ShortenedUrlController extends BaseController { /** * Gets the shortened urls. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter - * @param sortParameter the sort parameter - * @param descParameter the desc parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter + * @param sortParameter the sort parameter + * @param descParameter the desc parameter * @param searchParameter the search parameter * @return the shortened urls */ @PreAuthorize("isAuthenticated()") @GetMapping - public Page getShortenedUrls( - @RequestParam("page") Optional pageParameter, - @RequestParam("size") Optional sizeParameter, - @RequestParam("sort") Optional sortParameter, + public Page getShortenedUrls(@RequestParam("page") Optional pageParameter, + @RequestParam("size") Optional sizeParameter, @RequestParam("sort") Optional sortParameter, @RequestParam("desc") Optional descParameter, @RequestParam("search") Optional searchParameter) { - if (!permissionManager.hasPermission(getCurrentUserId(), - ShortenedUrlPermissions.URL_SHORTENER)) { + if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER)) { shortenedUrlManager.deleteAll(getCurrentUserId(), true); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - return shortenedUrlManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0), - sizeParameter.orElse(10), sortParameter.orElse("code"), descParameter.orElse(false), - searchParameter.orElse("")); + return shortenedUrlManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0), sizeParameter.orElse(10), + sortParameter.orElse("code"), descParameter.orElse(false), searchParameter.orElse("")); } /** @@ -253,15 +247,13 @@ public class ShortenedUrlController extends BaseController { @PreAuthorize("isAuthenticated()") @PostMapping public ShortenedUrl createShortenedUrl(@RequestBody ShortenedUrlModel shortenedUrlModel) { - if (!permissionManager.hasPermission(getCurrentUserId(), - ShortenedUrlPermissions.URL_SHORTENER) + if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER) || !permissionManager.isFullUser(getCurrentUserId())) { shortenedUrlManager.deleteAll(getCurrentUserId(), true); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } - Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(), - ShortenedUrlQuotas.URL_SHORTENER); + Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(), ShortenedUrlQuotas.URL_SHORTENER); if (shortenedUrlsQuota == null || shortenedUrlsQuota.getValue() < 1) { throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } @@ -273,9 +265,8 @@ public class ShortenedUrlController extends BaseController { throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT); } - return shortenedUrlManager.create(getCurrentUserId(), shortenedUrlModel.getUrl(), - shortenedUrlModel.getNote(), shortenedUrlModel.getCode(), - shortenedUrlModel.getExpires(), shortenedUrlModel.getPassword(), + return shortenedUrlManager.create(getCurrentUserId(), shortenedUrlModel.getUrl(), shortenedUrlModel.getNote(), + shortenedUrlModel.getCode(), shortenedUrlModel.getExpires(), shortenedUrlModel.getPassword(), shortenedUrlModel.isQueryParameters(), true); } @@ -288,8 +279,7 @@ public class ShortenedUrlController extends BaseController { @PreAuthorize("isAuthenticated()") @PatchMapping public ShortenedUrl updateShortenedUrl(@RequestBody ShortenedUrlModel shortenedUrlModel) { - if (!permissionManager.hasPermission(getCurrentUserId(), - ShortenedUrlPermissions.URL_SHORTENER) + if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER) || !permissionManager.isFullUser(getCurrentUserId())) { shortenedUrlManager.deleteAll(getCurrentUserId(), true); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); @@ -306,8 +296,7 @@ public class ShortenedUrlController extends BaseController { Errors errors = new RequestBodyErrors(shortenedUrlModel); - if (StringUtils.hasText(shortenedUrlModel.getNewCode()) - && !shortenedUrlModel.getNewCode().equals(code)) { + if (StringUtils.hasText(shortenedUrlModel.getNewCode()) && !shortenedUrlModel.getNewCode().equals(code)) { shortenedUrlModel.setCode(shortenedUrlModel.getNewCode()); newShortenedUrl = true; } else { @@ -335,8 +324,7 @@ public class ShortenedUrlController extends BaseController { if (shortenedUrlModel.isNewPassword()) { if (StringUtils.hasText(shortenedUrlModel.getPassword())) { - shortenedUrl - .setPasswordHash(passwordEncoder.encode(shortenedUrlModel.getPassword())); + shortenedUrl.setPasswordHash(passwordEncoder.encode(shortenedUrlModel.getPassword())); } else { shortenedUrl.setPasswordHash(null); } @@ -353,8 +341,7 @@ public class ShortenedUrlController extends BaseController { @PreAuthorize("isAuthenticated()") @DeleteMapping("/{code}") public void deleteShortenedUrl(@PathVariable("code") String code) { - if (!permissionManager.hasPermission(getCurrentUserId(), - ShortenedUrlPermissions.URL_SHORTENER)) { + if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER)) { shortenedUrlManager.deleteAll(getCurrentUserId(), true); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); } diff --git a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlManagementController.java b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlManagementController.java index 11aa1a7..326626f 100644 --- a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlManagementController.java +++ b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/ShortenedUrlManagementController.java @@ -36,19 +36,18 @@ public class ShortenedUrlManagementController extends BaseController { /** * Gets the shortened urls. * - * @param pageParameter the page parameter - * @param sizeParameter the size parameter + * @param pageParameter the page parameter + * @param sizeParameter the size parameter * @param searchParameter the search parameter * @return the shortened urls */ @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping - public Page getShortenedUrls( - @RequestParam("page") Optional pageParameter, + public Page getShortenedUrls(@RequestParam("page") Optional pageParameter, @RequestParam("size") Optional sizeParameter, @RequestParam("search") Optional searchParameter) { - return shortenedUrlManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "code", - true, searchParameter.orElse("")); + return shortenedUrlManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "code", true, + searchParameter.orElse("")); } /** @@ -66,13 +65,12 @@ public class ShortenedUrlManagementController extends BaseController { /** * Delete shortened url. * - * @param code the code + * @param code the code * @param quota the quota */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/{code}") - public void deleteShortenedUrl(@PathVariable("code") String code, - @RequestParam("quota") Optional quota) { + public void deleteShortenedUrl(@PathVariable("code") String code, @RequestParam("quota") Optional quota) { ShortenedUrl shortenedUrl = shortenedUrlManager.get(code); if (shortenedUrl == null) { @@ -90,8 +88,7 @@ public class ShortenedUrlManagementController extends BaseController { */ @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/all/{owner}") - public void deleteAll(@PathVariable("owner") Long owner, - @RequestParam("quota") Optional quota) { + public void deleteAll(@PathVariable("owner") Long owner, @RequestParam("quota") Optional quota) { shortenedUrlManager.deleteAll(owner, quota.isPresent() && quota.get().booleanValue()); } diff --git a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/validation/ShortenedUrlModelValidator.java b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/validation/ShortenedUrlModelValidator.java index 8a37cc5..8d9a60a 100644 --- a/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/validation/ShortenedUrlModelValidator.java +++ b/urlshortener/src/main/java/de/bstly/we/urlshortener/controller/validation/ShortenedUrlModelValidator.java @@ -26,7 +26,6 @@ public class ShortenedUrlModelValidator implements Validator { private UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES); protected static final String codePart = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\\\.[A-Z0-9_!#$%&'*+/=?`{|}~^-]+)*$"; - /* * @see org.springframework.validation.Validator#supports(java.lang.Class) */ @@ -35,9 +34,9 @@ public class ShortenedUrlModelValidator implements Validator { return clazz.isAssignableFrom(ShortenedUrlModel.class); } - /* - * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) + * @see org.springframework.validation.Validator#validate(java.lang.Object, + * org.springframework.validation.Errors) */ @Override public void validate(Object target, Errors errors) { @@ -55,8 +54,7 @@ public class ShortenedUrlModelValidator implements Validator { } } - if (shortenedUrlModel.getExpires() != null - && shortenedUrlModel.getExpires().isBefore(Instant.now())) { + if (shortenedUrlModel.getExpires() != null && shortenedUrlModel.getExpires().isBefore(Instant.now())) { errors.rejectValue("expires", "NOT_VALID"); }