From 0ee1996d0f9d14d82feecc25aa0d8692634787bd Mon Sep 17 00:00:00 2001 From: Marthym Date: Sun, 7 Jan 2024 16:02:04 +0100 Subject: [PATCH] chore(sandside): #194 refactor entity clas into record --- .../baywatch/common/api/model/Entity.java | 28 ++++----- .../infra/adapters/IndexableDataAdapter.java | 2 +- .../notify/domain/NotifyServiceImpl.java | 14 ++--- .../notify/infra/NotificationController.java | 4 +- .../NotificationPersistenceAdapter.java | 12 ++-- .../baywatch/opml/domain/OpmlServiceImpl.java | 10 +-- .../domain/ScrapEnrichmentServiceImpl.java | 18 +++--- .../actions/DeleteOrphanFeedHandler.java | 4 +- .../domain/actions/PurgeNewsHandler.java | 3 +- .../adapters/NewsMaintenanceAdapter.java | 2 +- .../domain/AuthenticationServiceImpl.java | 2 +- ...JwtBaywatchAuthenticationProviderImpl.java | 12 ++-- .../security/domain/PasswordServiceImpl.java | 6 +- .../security/domain/UserServiceImpl.java | 40 ++++++------ .../infra/JwtTokenAuthenticationFilter.java | 4 +- .../adapters/SpringAuthenticationContext.java | 5 +- .../infra/adapters/UserServiceAdapter.java | 2 +- .../controllers/AuthenticationController.java | 2 +- .../AuthenticationGqlController.java | 2 +- .../infra/model/BaywatchUserDetails.java | 6 +- .../teams/domain/TeamServiceImpl.java | 52 ++++++++-------- .../controllers/TeamMembersController.java | 4 +- .../infra/controllers/TeamsController.java | 4 +- .../controllers/UserMappingController.java | 4 +- .../teams/infra/mappers/TeamsMapper.java | 6 +- .../techwatch/domain/FeedServiceImpl.java | 16 ++--- .../techwatch/domain/NewsServiceImpl.java | 16 ++--- .../domain/PopularNewsServiceImpl.java | 9 +-- .../domain/SystemMaintenanceServiceImpl.java | 13 ++-- .../infra/adapters/TeamServiceAdapter.java | 7 ++- .../infra/controllers/FeedController.java | 6 +- .../controllers/GraphQLFeedsController.java | 6 +- .../infra/controllers/TagsController.java | 2 +- .../mappers/RecordToFeedConverterTest.java | 10 +-- .../notify/domain/NotifyServiceImplTest.java | 8 +-- .../NotificationPersistenceAdapterTest.java | 6 +- .../samples/NotificationsRecordSamples.java | 6 +- .../scraper/domain/RssAtomParserImplTest.java | 16 ++--- .../infra/FeedScraperIntegrationTest.java | 2 +- .../security/api/model/RoleUtilsTest.java | 6 +- .../security/domain/UserServiceImplTest.java | 61 +++++++++---------- .../infra/persistence/UserRepositoryTest.java | 34 +++++------ .../teams/domain/TeamServiceImplTest.java | 52 ++++++++-------- .../samples/TeamsMembersRecordSamples.java | 8 +-- .../techwatch/domain/FeedServiceImplTest.java | 16 ++--- .../techwatch/domain/NewsServiceImplTest.java | 18 +++--- .../SystemMaintenanceServiceImplTest.java | 6 +- .../infra/controllers/FeedControllerTest.java | 4 +- .../GraphQLFeedsControllerTest.java | 2 +- .../infra/persistence/FeedRepositoryTest.java | 30 ++++----- .../baywatch/tests/samples/NewsSamples.java | 2 +- .../samples/infra/UsersRecordSamples.java | 26 ++++---- .../samples/infra/UsersRolesSamples.java | 10 +-- 53 files changed, 322 insertions(+), 324 deletions(-) diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/common/api/model/Entity.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/common/api/model/Entity.java index 69afdc47..349fa927 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/common/api/model/Entity.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/common/api/model/Entity.java @@ -1,10 +1,7 @@ package fr.ght1pc9kc.baywatch.common.api.model; import lombok.Builder; -import lombok.EqualsAndHashCode; import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.ToString; import org.jetbrains.annotations.NotNull; import java.time.Instant; @@ -12,26 +9,23 @@ /** * Hold the standard Persistence information * - * @param The type of the persisted object + * @param self The Persisted Entity + * @param The type of the persisted object */ @Builder -@ToString -@EqualsAndHashCode -@RequiredArgsConstructor -public final class Entity { +public record Entity( + @NonNull String id, + @NonNull String createdBy, + @NonNull Instant createdAt, + @NonNull T self +) { public static final String IDENTIFIER = "_id"; public static final String CREATED_AT = "_createdAt"; public static final String CREATED_BY = "_createdBy"; + public static final String LOGIN_AT = "_loginAt"; + public static final String LOGIN_IP = "_loginIp"; public static final String NO_ONE = "_"; - public final @NonNull String id; - public final @NonNull String createdBy; - public final @NonNull Instant createdAt; - - /** - * The Persisted Entity - */ - public final @NonNull T self; /** * Utility method to give an ID and a creation date to a persistable object @@ -43,7 +37,7 @@ public final class Entity { * @return An identified Object with ID */ public static Entity identify(String id, Instant createdAt, T entity) { - return new Entity<>(id, NO_ONE, createdAt, entity); + return new Entity(id, NO_ONE, createdAt, entity); } /** diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/indexer/infra/adapters/IndexableDataAdapter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/indexer/infra/adapters/IndexableDataAdapter.java index 1f6edb8c..a4522c41 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/indexer/infra/adapters/IndexableDataAdapter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/indexer/infra/adapters/IndexableDataAdapter.java @@ -19,7 +19,7 @@ public class IndexableDataAdapter implements IndexableDataPort { @Override public Flux listFeed() { return systemMaintenanceService.feedList() - .map(f -> mapper.getIndexableFromFeed(f.self)); + .map(f -> mapper.getIndexableFromFeed(f.self())); } @Override diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImpl.java index 76eff5dd..d3aa1758 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImpl.java @@ -68,21 +68,21 @@ public Flux subscribe() { return Flux.error(() -> new IllegalStateException("Publisher was closed !")); } return authFacade.getConnectedUser().flatMapMany(u -> - Objects.requireNonNull(cache.get(u.id, id -> { + Objects.requireNonNull(cache.get(u.id(), id -> { Sinks.Many sink = Sinks.many().multicast().onBackpressureBuffer(); AtomicReference subscription = new AtomicReference<>(); Flux multicastFlux = this.multicast.asFlux() .doOnSubscribe(subscription::set); - log.atDebug().addArgument(u.id) + log.atDebug().addArgument(u.id()) .log("Subscribe notification for {}"); Flux eventPublisher = Flux.merge( - notificationPersistence.consume(u.id), + notificationPersistence.consume(u.id()), sink.asFlux(), multicastFlux ) .takeWhile(e -> cache.asMap().containsKey(id)) .map(e -> { - log.atDebug().addArgument(u.id).addArgument(e).log("{} receive Event: {}"); + log.atDebug().addArgument(u.id()).addArgument(e).log("{} receive Event: {}"); return e; }).cache(0); return new ByUserEventPublisherCacheEntry(subscription, sink, eventPublisher); @@ -92,10 +92,10 @@ public Flux subscribe() { @Override public Mono unsubscribe() { return authFacade.getConnectedUser() - .filter(u -> cache.asMap().containsKey(u.id)) + .filter(u -> cache.asMap().containsKey(u.id())) .map(u -> { - log.atDebug().addArgument(u.id).log("Dispose SSE Subscription for {}"); - cache.invalidate(u.id); + log.atDebug().addArgument(u.id()).log("Dispose SSE Subscription for {}"); + cache.invalidate(u.id()); return true; }); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/NotificationController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/NotificationController.java index 7e20f70e..4e27d828 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/NotificationController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/NotificationController.java @@ -60,8 +60,8 @@ public Mono> disposeSse() { @PreAuthorize("hasRole('ADMIN')") public Mono test(@RequestParam("msg") String msg) { return facade.getConnectedUser().map(user -> { - notifyManager.broadcast(EventType.NEWS_UPDATE, "UPDATE"); - notifyManager.send(user.id, EventType.USER_NOTIFICATION, "PERSO"); + notifyManager.broadcast(EventType.NEWS_UPDATE, "UPDATE " + msg); + notifyManager.send(user.id(), EventType.USER_NOTIFICATION, "PERSO " + msg); return user; }).then(); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapter.java index 3ecbbcd3..007a8449 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapter.java @@ -36,7 +36,7 @@ public class NotificationPersistenceAdapter implements NotificationPersistencePo @Override public Mono persist(Entity event) { - Mono notificationsRecord = event.self.accept(new ServerEventVisitor<>() { + Mono notificationsRecord = event.self().accept(new ServerEventVisitor<>() { @Override public Mono visit(BasicEvent event) { return Mono.just(NOTIFICATIONS.newRecord() @@ -50,14 +50,14 @@ public Mono visit(ReactiveEvent event) { } }); return notificationsRecord.map(r -> - r.setNotiCreatedAt(DateUtils.toLocalDateTime(event.createdAt)) - .setNotiEventType(event.self.type().getName()) - .setNotiId(event.id) - .setNotiUserId(event.createdBy)) + r.setNotiCreatedAt(DateUtils.toLocalDateTime(event.createdAt())) + .setNotiEventType(event.self().type().getName()) + .setNotiId(event.id()) + .setNotiUserId(event.createdBy())) .flatMap(r -> Mono.fromCompletionStage(dsl.insertInto(NOTIFICATIONS).set(r).executeAsync()) .subscribeOn(databaseScheduler)) - .thenReturn(event.self); + .thenReturn(event.self()); } @Override diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/opml/domain/OpmlServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/opml/domain/OpmlServiceImpl.java index 988c9608..63c79b7a 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/opml/domain/OpmlServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/opml/domain/OpmlServiceImpl.java @@ -64,19 +64,19 @@ public Mono opmlImport(Flux data) { .then(Mono.empty()); return Flux.merge(db, feeds) .buffer(100) - .flatMap(f -> feedRepository.persist(f).map(e -> e.self).collectList()) - .flatMap(f -> feedRepository.persistUserRelation(f, owner.id)); + .flatMap(f -> feedRepository.persist(f).map(Entity::self).collectList()) + .flatMap(f -> feedRepository.persistUserRelation(f, owner.id())); })).then(); } private Mono writeOpml(OutputStream out, Entity owner) { OpmlWriter opmlWriter = writerFactory.apply(out); - return feedRepository.list(QueryContext.empty().withUserId(owner.id)) - .doFirst(() -> opmlWriter.startOpmlDocument(owner.self)) + return feedRepository.list(QueryContext.empty().withUserId(owner.id())) + .doFirst(() -> opmlWriter.startOpmlDocument(owner.self())) .doOnEach(signal -> { Entity feed = signal.get(); if (feed != null) { - opmlWriter.writeOutline(feed.self); + opmlWriter.writeOutline(feed.self()); } }) .doOnComplete(opmlWriter::endOmplDocument) diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/ScrapEnrichmentServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/ScrapEnrichmentServiceImpl.java index b628222f..9ecd8c64 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/ScrapEnrichmentServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/ScrapEnrichmentServiceImpl.java @@ -71,11 +71,11 @@ public Mono scrapSingleNews(URI uri) { .switchIfEmpty(Mono.fromCallable(t::get))) .contextWrite(context) .subscribeOn(scraperScheduler) - .subscribe(n -> notifyService.send(user.id, EventType.USER_NOTIFICATION, + .subscribe(n -> notifyService.send(user.id(), EventType.USER_NOTIFICATION, DEFAULT_NOTIFICATION.toBuilder() .title(n.title()) .target(n.id()).build()), - t -> notifyService.send(user.id, EventType.USER_NOTIFICATION, + t -> notifyService.send(user.id(), EventType.USER_NOTIFICATION, UserNotification.error(t.getLocalizedMessage()))) )) .then(); @@ -84,7 +84,7 @@ public Mono scrapSingleNews(URI uri) { @Override public Mono buildStandaloneNews(URI link) { return authFacade.getConnectedUser() - .filter(u -> RoleUtils.hasRole(u.self, Role.USER)) + .filter(u -> RoleUtils.hasRole(u.self(), Role.USER)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(OPERATION_NOT_PERMITTED))) .map(u -> News.builder() .raw(RawNews.builder() @@ -92,7 +92,7 @@ public Mono buildStandaloneNews(URI link) { .link(link) .publication(clock.instant()) .build()) - .feeds(Set.of(u.id)) + .feeds(Set.of(u.id())) .state(State.NONE) .build()); } @@ -100,7 +100,7 @@ public Mono buildStandaloneNews(URI link) { @Override public Mono> applyNewsFilters(News news) { Mono raw = authFacade.getConnectedUser() - .filter(u -> RoleUtils.hasRole(u.self, Role.USER)) + .filter(u -> RoleUtils.hasRole(u.self(), Role.USER)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(OPERATION_NOT_PERMITTED))) .then(Mono.just(news.getRaw())); @@ -118,14 +118,14 @@ public Mono> applyNewsFilters(News news) { private Mono notAlreadyExists(News news) { return authFacade.getConnectedUser() - .filter(u -> RoleUtils.hasRole(u.self, Role.USER)) + .filter(u -> RoleUtils.hasRole(u.self(), Role.USER)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(OPERATION_NOT_PERMITTED))) .flatMapMany(u -> systemMaintenanceService.newsList(PageRequest.one(Criteria.property(ID).eq(news.id()))) .map(News::getFeeds) .flatMap(feeds -> systemMaintenanceService.feedList(PageRequest.all(Criteria.property(ID).in(feeds) - .and(Criteria.property(USER_ID).eq(u.id))))) + .and(Criteria.property(USER_ID).eq(u.id()))))) .contextWrite(AuthenticationFacade.withSystemAuthentication())) .hasElements().map(b -> !b); @@ -134,7 +134,7 @@ private Mono notAlreadyExists(News news) { @Override public Mono saveAndShare(News news) { return authFacade.getConnectedUser() - .filter(u -> RoleUtils.hasRole(u.self, Role.USER)) + .filter(u -> RoleUtils.hasRole(u.self(), Role.USER)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(OPERATION_NOT_PERMITTED))) .flatMap(u -> @@ -150,7 +150,7 @@ public Mono saveAndShare(News news) { @Override public Mono applyFeedsFilters(AtomFeed feed) { Mono raw = authFacade.getConnectedUser() - .filter(u -> RoleUtils.hasRole(u.self, Role.USER)) + .filter(u -> RoleUtils.hasRole(u.self(), Role.USER)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(OPERATION_NOT_PERMITTED))) .then(Mono.just(feed)); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/DeleteOrphanFeedHandler.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/DeleteOrphanFeedHandler.java index 7a5c00be..ed076e67 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/DeleteOrphanFeedHandler.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/DeleteOrphanFeedHandler.java @@ -49,9 +49,9 @@ public Mono before() { .then(); return maintenanceService.feedList(PageRequest.all(Criteria.property(COUNT).eq(0))) - .doOnNext(feed -> feeds.tryEmitNext(feed.id)) + .doOnNext(feed -> feeds.tryEmitNext(feed.id())) .doOnComplete(feeds::tryEmitComplete) - .flatMap(feed -> maintenanceService.newsList(PageRequest.all(Criteria.property(FEED_ID).eq(feed.id)))) + .flatMap(feed -> maintenanceService.newsList(PageRequest.all(Criteria.property(FEED_ID).eq(feed.id())))) .doOnComplete(newsSink::tryEmitComplete) .doOnNext(news -> newsSink.tryEmitNext(news.id())) .then(deleted) diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/PurgeNewsHandler.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/PurgeNewsHandler.java index 267e8bbc..bc5739c5 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/PurgeNewsHandler.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/domain/actions/PurgeNewsHandler.java @@ -1,6 +1,7 @@ package fr.ght1pc9kc.baywatch.scraper.domain.actions; import fr.ght1pc9kc.baywatch.common.api.ScrapingEventHandler; +import fr.ght1pc9kc.baywatch.common.api.model.Entity; import fr.ght1pc9kc.baywatch.scraper.infra.config.ScraperApplicationProperties; import fr.ght1pc9kc.baywatch.techwatch.domain.model.QueryContext; import fr.ght1pc9kc.baywatch.techwatch.domain.ports.NewsPersistencePort; @@ -55,7 +56,7 @@ private Flux keepStaredNewsIds(Collection newsIds) { Criteria isStaredCriteria = Criteria.property(NEWS_ID).in(newsIds) .and(Criteria.property(SHARED).eq(true)); return statePersistence.list(QueryContext.all(isStaredCriteria)) - .map(e -> e.id) + .map(Entity::id) .collectList() .flatMapMany(stareds -> { Collection toBeDeleted = new ArrayList<>(newsIds); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/infra/adapters/NewsMaintenanceAdapter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/infra/adapters/NewsMaintenanceAdapter.java index 3c1c8647..76367cb6 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/infra/adapters/NewsMaintenanceAdapter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/scraper/infra/adapters/NewsMaintenanceAdapter.java @@ -25,7 +25,7 @@ public Flux listAllNewsId() { @Override public Flux feedList() { return systemMaintenanceService.feedList(PageRequest.all()) - .map(f -> new ScrapedFeed(f.id, f.self.location())); + .map(f -> new ScrapedFeed(f.id(), f.self().location())); } @Override diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/AuthenticationServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/AuthenticationServiceImpl.java index bfcf35bf..66c931d2 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/AuthenticationServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/AuthenticationServiceImpl.java @@ -17,7 +17,7 @@ public class AuthenticationServiceImpl implements AuthenticationService { @Override public Mono refresh(String token) { return Mono.fromCallable(() -> tokenProvider.getAuthentication(token)) - .flatMap(auth -> userService.get(auth.user().id) + .flatMap(auth -> userService.get(auth.user().id()) .map(user -> tokenProvider.createToken(user, auth.rememberMe(), Collections.emptyList()))); } } \ No newline at end of file diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/JwtBaywatchAuthenticationProviderImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/JwtBaywatchAuthenticationProviderImpl.java index fa5e6e07..0beb1812 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/JwtBaywatchAuthenticationProviderImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/JwtBaywatchAuthenticationProviderImpl.java @@ -54,7 +54,7 @@ public JwtBaywatchAuthenticationProviderImpl(byte[] secretKey, Duration validity @Override public BaywatchAuthentication createToken(Entity user, boolean remember, Collection authorities) { List auth = new ArrayList<>(authorities); - auth.addAll(user.self.roles.stream().map(RoleUtils::toSpringAuthority).toList()); + auth.addAll(user.self().roles.stream().map(RoleUtils::toSpringAuthority).toList()); String auths = String.join(",", auth); try { @@ -62,14 +62,14 @@ public BaywatchAuthentication createToken(Entity user, boolean remember, C Instant now = clock.instant(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() - .subject(user.id) + .subject(user.id()) .issuer(ISSUER) .issueTime(Date.from(now)) .expirationTime(Date.from(now.plus(validity))) - .claim(LOGIN_KEY, user.self.login) - .claim(NAME_KEY, user.self.name) - .claim(MAIL_KEY, user.self.mail) - .claim(CREATED_AT_KEY, Date.from(user.createdAt)) + .claim(LOGIN_KEY, user.self().login) + .claim(NAME_KEY, user.self().name) + .claim(MAIL_KEY, user.self().mail) + .claim(CREATED_AT_KEY, Date.from(user.createdAt())) .claim(REMEMBER_ME_KEY, remember) .claim(AUTHORITIES_KEY, auths) .build(); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/PasswordServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/PasswordServiceImpl.java index 7c2b23a0..7c9df9eb 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/PasswordServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/PasswordServiceImpl.java @@ -26,9 +26,9 @@ public Mono checkPasswordStrength(String password) { .flatMap(user -> localeFacade.getLocale().map(l -> Tuples.of(user, l))) .map(context -> passwordChecker.estimate(password, context.getT2(), List.of( - context.getT1().self.name, - context.getT1().self.login, - context.getT1().self.mail)) + context.getT1().self().name, + context.getT1().self().login, + context.getT1().self().mail)) ); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImpl.java index 8d2d9c54..08b12fd1 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImpl.java @@ -63,7 +63,7 @@ public Mono> get(String userId) { @Override public Flux> list(PageRequest pageRequest) { return authFacade.getConnectedUser() - .map(u -> QueryContext.from(pageRequest).withUserId(u.id)) + .map(u -> QueryContext.from(pageRequest).withUserId(u.id())) .flatMapMany(userRepository::list) .flatMap(this::filterPublicData); } @@ -71,7 +71,7 @@ public Flux> list(PageRequest pageRequest) { @Override public Mono count(PageRequest pageRequest) { return authFacade.getConnectedUser() - .map(u -> QueryContext.all(pageRequest.filter()).withUserId(u.id)) + .map(u -> QueryContext.all(pageRequest.filter()).withUserId(u.id())) .flatMap(userRepository::count); } @@ -88,9 +88,9 @@ public Mono> create(User user) { private Mono> notifyAdmins(Entity newUser) { return this.list(PageRequest.all(Criteria.property(ROLES).eq(Role.ADMIN.toString()))) - .filter(not(admin -> admin.id.equals(newUser.createdBy))) - .map(admin -> notificationPort.send(admin.id, USER_NOTIFICATION, - String.format("New user %s created by %s.", newUser.self.login, newUser.createdBy))) + .filter(not(admin -> admin.id().equals(newUser.createdBy()))) + .map(admin -> notificationPort.send(admin.id(), USER_NOTIFICATION, + String.format("New user %s created by %s.", newUser.self().login, newUser.createdBy()))) .then(Mono.just(newUser)); } @@ -110,13 +110,13 @@ public Mono> update(String id, UpdatableUser user, String currentPa throw new IllegalArgumentException("Password must be stronger !"); } return authorizeSelfData(id) - .flatMap(u -> get(u.id)) + .flatMap(u -> get(u.id())) .handle((u, sink) -> { - if (hasRole(u.self, Role.ADMIN)) { + if (hasRole(u.self(), Role.ADMIN)) { sink.next(u); - } else if (id.equals(u.id) + } else if (id.equals(u.id()) && Objects.nonNull(currentPassword) - && passwordEncoder.matches(currentPassword, u.self.password)) { + && passwordEncoder.matches(currentPassword, u.self().password)) { sink.next(u); } else { sink.error(new UnauthorizedOperation(UNAUTHORIZED_USER)); @@ -137,7 +137,7 @@ public Flux> delete(Collection ids) { .switchIfEmpty(Flux.error(new NoSuchElementException(String.format("Unable to find users %s :", ids)))) .collectList() .flatMapMany(users -> Flux.fromIterable(users) - .map(u -> u.id) + .map(Entity::id) .collectList() .flatMap(userRepository::delete) .thenMany(Flux.fromIterable(users))); @@ -147,10 +147,10 @@ public Flux> delete(Collection ids) { public Mono> grants(String grantedUserId, Collection permissions) { return authFacade.getConnectedUser().flatMap(currentUser -> { var tobeVerified = new ArrayList(); - boolean selfGrant = currentUser.id.equals(grantedUserId); + boolean selfGrant = currentUser.id().equals(grantedUserId); for (Permission perm : permissions) { - if (!RoleUtils.hasPermission(currentUser.self, perm)) { + if (!RoleUtils.hasPermission(currentUser.self(), perm)) { if (perm.entity().isPresent() && selfGrant) { tobeVerified.add(perm.toString()); } else { @@ -171,7 +171,7 @@ public Mono> grants(String grantedUserId, Collection pe @Override public Mono revokes(Permission permission, Collection userIds) { return authFacade.getConnectedUser().flatMap(currentUser -> { - if ((userIds.size() == 1 && userIds.contains(currentUser.id)) || RoleUtils.hasRole(currentUser.self, Role.ADMIN)) { + if ((userIds.size() == 1 && userIds.contains(currentUser.id())) || RoleUtils.hasRole(currentUser.self(), Role.ADMIN)) { return Mono.just(currentUser); } else { return Mono.error(() -> new UnauthorizedOperation("Unauthorized revoke operation !")); @@ -195,14 +195,14 @@ public Flux listGrantedUsers(Permission permission) { private Mono> filterPublicData(Entity original) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .filter(u -> (hasRole(u.self, Role.ADMIN) - || (hasRole(u.self, Role.USER) && original.id.equals(u.id)))) + .filter(u -> (hasRole(u.self(), Role.ADMIN) + || (hasRole(u.self(), Role.USER) && original.id().equals(u.id())))) .map(u -> original) .switchIfEmpty(Mono.just(Entity.builder() - .id(original.id) + .id(original.id()) .createdBy(Entity.NO_ONE) .createdAt(Instant.EPOCH) - .self(original.self.toBuilder() + .self(original.self().toBuilder() .clearRoles() .password(null) .mail(null) @@ -218,8 +218,8 @@ private Mono> authorizeSelfData(Collection ids) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) .handle((u, sink) -> { - if (hasRole(u.self, Role.ADMIN) - || (hasRole(u.self, Role.USER) && ids.size() == 1 && ids.contains(u.id))) { + if (hasRole(u.self(), Role.ADMIN) + || (hasRole(u.self(), Role.USER) && ids.size() == 1 && ids.contains(u.id()))) { sink.next(u); return; } @@ -231,7 +231,7 @@ private Mono> authorizeAllData() { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) .handle((u, sink) -> { - if (hasRole(u.self, Role.ADMIN)) { + if (hasRole(u.self(), Role.ADMIN)) { sink.next(u); return; } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/JwtTokenAuthenticationFilter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/JwtTokenAuthenticationFilter.java index 7c4a6fec..17abaa09 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/JwtTokenAuthenticationFilter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/JwtTokenAuthenticationFilter.java @@ -41,9 +41,9 @@ public class JwtTokenAuthenticationFilter implements WebFilter { return Mono.just(!this.tokenProvider.validateToken(token, true)) .filter(Predicate.isEqual(true)) - .flatMap(x -> userService.findByUsername(bwAuth.user().self.login)) + .flatMap(x -> userService.findByUsername(bwAuth.user().self().login)) .map(updated -> { - log.debug("Refresh valid expired token for {}", bwAuth.user().self.login); + log.debug("Refresh valid expired token for {}", bwAuth.user().self().login); BaywatchAuthentication freshBaywatchAuth = this.tokenProvider.createToken(bwAuth.user(), bwAuth.rememberMe(), Collections.emptyList()); refreshCookieOrHeader(freshBaywatchAuth, exchange.getRequest(), exchange.getResponse()); return exchange; diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/SpringAuthenticationContext.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/SpringAuthenticationContext.java index 0de857f5..ff8decdb 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/SpringAuthenticationContext.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/SpringAuthenticationContext.java @@ -2,6 +2,7 @@ import fr.ght1pc9kc.baywatch.common.api.model.Entity; import fr.ght1pc9kc.baywatch.security.api.AuthenticationFacade; +import fr.ght1pc9kc.baywatch.security.api.model.Permission; import fr.ght1pc9kc.baywatch.security.api.model.User; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; @@ -31,7 +32,9 @@ public Mono> getConnectedUser() { @Override public Context withAuthentication(Entity user) { Authentication authentication = new PreAuthenticatedAuthenticationToken(user, null, - AuthorityUtils.createAuthorityList(user.self.roles.toArray(String[]::new))); + AuthorityUtils.createAuthorityList(user.self().roles.stream() + .map(Permission::toString) + .toArray(String[]::new))); return ReactiveSecurityContextHolder.withAuthentication(authentication); } } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/UserServiceAdapter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/UserServiceAdapter.java index c7c04663..17e77204 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/UserServiceAdapter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/adapters/UserServiceAdapter.java @@ -40,7 +40,7 @@ public UserServiceAdapter(UserPersistencePort userPersistencePort, PasswordEncoder passwordEncoder) { this.delegate = new UserServiceImpl( userPersistencePort, authorizationRepository, notificationPort, authFacade, passwordEncoder, - Clock.systemUTC(), UlidFactory.newInstance()); + Clock.systemUTC(), UlidFactory.newMonotonicInstance()); this.delegateA = (UserServiceImpl) this.delegate; } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationController.java index 7c10439a..a1f1d616 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationController.java @@ -84,7 +84,7 @@ public Mono logout(ServerWebExchange exchange) { String user = cookieManager.getTokenCookie(exchange.getRequest()) .map(HttpCookie::getValue) .map(tokenProvider::getAuthentication) - .map(a -> String.format("%s (%s)", a.user().self.login, a.user().id)) + .map(a -> String.format("%s (%s)", a.user().self().login, a.user().id())) .orElse("Unknown User"); log.debug("Logout for {}.", user); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationGqlController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationGqlController.java index dd81f9b4..fd610c9b 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationGqlController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/controllers/AuthenticationGqlController.java @@ -96,7 +96,7 @@ public Mono logout(GraphQLContext env) { String user = cookieManager.getTokenCookie(exchange.getRequest()) .map(HttpCookie::getValue) .map(tokenProvider::getAuthentication) - .map(a -> String.format("%s (%s)", a.user().self.login, a.user().id)) + .map(a -> String.format("%s (%s)", a.user().self().login, a.user().id())) .orElse("Unknown User"); log.debug("Logout for {}.", user); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/model/BaywatchUserDetails.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/model/BaywatchUserDetails.java index 8b78da77..57b54ef1 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/model/BaywatchUserDetails.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/security/infra/model/BaywatchUserDetails.java @@ -14,19 +14,19 @@ public record BaywatchUserDetails( ) implements UserDetails { @Override public Collection getAuthorities() { - return AuthorityUtils.createAuthorityList(entity.self.roles.stream() + return AuthorityUtils.createAuthorityList(entity.self().roles.stream() .map(RoleUtils::toSpringAuthority) .toArray(String[]::new)); } @Override public String getPassword() { - return entity.self.password; + return entity.self().password; } @Override public String getUsername() { - return entity.self.login; + return entity.self().login; } @Override diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImpl.java index 453cd3fa..17f35e48 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImpl.java @@ -59,11 +59,11 @@ public Flux> list(PageRequest pageRequest) { return authFacade.getConnectedUser().flatMapMany(member -> { QueryContext qCtx = QueryContext.builder() .filter(pageRequest.filter()) - .userId(member.id) + .userId(member.id()) .build(); return teamMemberPersistence.list(qCtx) - .map(e -> e.id) - .concatWith(Flux.fromIterable(RoleUtils.getEntitiesFor(member.self, Role.MANAGER))); + .map(Entity::id) + .concatWith(Flux.fromIterable(RoleUtils.getEntitiesFor(member.self(), Role.MANAGER))); }).collectList().flatMapMany(ids -> { QueryContext qCtx2 = QueryContext.builder() @@ -79,11 +79,11 @@ public Mono count(PageRequest pageRequest) { return authFacade.getConnectedUser().flatMapMany(member -> { QueryContext qCtx = QueryContext.builder() .filter(pageRequest.filter()) - .userId(member.id) + .userId(member.id()) .build(); return teamMemberPersistence.list(qCtx) - .map(e -> e.id) - .concatWith(Flux.fromIterable(RoleUtils.getEntitiesFor(member.self, Role.MANAGER))); + .map(Entity::id) + .concatWith(Flux.fromIterable(RoleUtils.getEntitiesFor(member.self(), Role.MANAGER))); }).collectList().flatMap(ids -> { QueryContext qCtx2 = QueryContext.builder() @@ -103,14 +103,14 @@ public Mono> create(String name, String topic) { .id(id) .self(new Team(name, topic)) .createdAt(now) - .createdBy(manager.id) + .createdBy(manager.id()) .build()) .then(teamMemberPersistence.add(List.of(Entity.builder().id(id) - .self(new TeamMember(manager.id, PendingFor.NONE)) - .createdBy(manager.id) + .self(new TeamMember(manager.id(), PendingFor.NONE)) + .createdBy(manager.id()) .createdAt(now) .build()))) - .then(authFacade.grantAuthorization(manager.id, List.of(Permission.manager(id).toString()))) + .then(authFacade.grantAuthorization(manager.id(), List.of(Permission.manager(id).toString()))) .thenReturn(id); }).flatMap(this::get); } @@ -118,7 +118,7 @@ public Mono> create(String name, String topic) { @Override public Mono> update(String id, String name, String topic) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasPermission(user.self, Permission.manager(id))) + .filter(user -> RoleUtils.hasPermission(user.self(), Permission.manager(id))) .switchIfEmpty(Mono.error(() -> new TeamPermissionDenied( "You must be manager of the team to update it ! Try refresh to update permissions."))) .flatMap(manager -> @@ -126,7 +126,7 @@ public Mono> update(String id, String name, String topic) { .id(id) .self(new Team(name, topic)) .createdAt(clock().instant()) - .createdBy(manager.id) + .createdBy(manager.id()) .build())) .then(teamPersistence.list(QueryContext.id(id)).next()); } @@ -142,8 +142,8 @@ public Flux> addMembers(String id, Collection members Instant now = clock().instant(); return authFacade.getConnectedUser() .flatMapMany(user -> { - boolean hasPermission = RoleUtils.hasPermission(user.self, Permission.manager(id)); - boolean addHimself = membersIds.size() == 1 && membersIds.iterator().next().equals(user.id); + boolean hasPermission = RoleUtils.hasPermission(user.self(), Permission.manager(id)); + boolean addHimself = membersIds.size() == 1 && membersIds.iterator().next().equals(user.id()); if (!hasPermission && !addHimself) { return Flux.error(() -> new UnauthorizedException("You haven't any permission for this operation !")); } @@ -151,7 +151,7 @@ public Flux> addMembers(String id, Collection members return Flux.fromStream(membersIds.stream() .map(mId -> Entity.builder().id(id) .self(new TeamMember(mId, pending)) - .createdBy(user.id) + .createdBy(user.id()) .createdAt(now) .build())); }).collectList() @@ -162,12 +162,12 @@ public Flux> addMembers(String id, Collection members @Override public Flux> removeMembers(String teamId, Collection membersIds) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasPermission(user.self, Permission.manager(teamId)) || (membersIds.stream().allMatch(user.id::equals))) + .filter(user -> RoleUtils.hasPermission(user.self(), Permission.manager(teamId)) || (membersIds.stream().allMatch(user.id()::equals))) .switchIfEmpty(Mono.error(() -> new TeamPermissionDenied("You must be manager of the team to remove users !"))) - .flatMapMany(manager -> ensureTeamKeepManager(manager.id, teamId, membersIds)) + .flatMapMany(manager -> ensureTeamKeepManager(manager.id(), teamId, membersIds)) // If no more team members, just remove the team and leave .flatMap(ignore -> teamMemberPersistence.list(QueryContext.all(Criteria.property(ID).eq(teamId)))) - .filter(not(e -> membersIds.contains(e.id))) + .filter(not(e -> membersIds.contains(e.id()))) .switchIfEmpty(delete(List.of(teamId)).thenMany(Flux.empty())) // else remove required members .then(authFacade.revokeAuthorization(Permission.manager(teamId).toString(), membersIds)) @@ -201,19 +201,19 @@ public Mono promoteMember(String id, String memberId, boolean isManager) { return Mono.error(() -> new IllegalArgumentException(id + "is not a team ID !")); } return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasPermission(user.self, Permission.manager(id))) + .filter(user -> RoleUtils.hasPermission(user.self(), Permission.manager(id))) .switchIfEmpty(Mono.error(() -> new TeamPermissionDenied("You must be manager of the team promote user !"))) .flatMap(manager -> { if (isManager) { return authFacade.grantAuthorization(memberId, List.of(Permission.manager(id).toString())) - .contextWrite(TeamAuthFacade.withSystemAuthentication(manager.id)); + .contextWrite(TeamAuthFacade.withSystemAuthentication(manager.id())); } else { - return Mono.just(manager.id.equals(memberId)) + return Mono.just(manager.id().equals(memberId)) .flatMapMany(isRevokeMe -> Boolean.TRUE.equals(isRevokeMe) ? - ensureTeamKeepManager(manager.id, id, List.of(memberId)) : - Flux.just(manager.id)).collectList() + ensureTeamKeepManager(manager.id(), id, List.of(memberId)) : + Flux.just(manager.id())).collectList() .flatMap(ignore -> authFacade.revokeAuthorization(Permission.manager(id).toString(), List.of(memberId)) - .contextWrite(TeamAuthFacade.withSystemAuthentication(manager.id))); + .contextWrite(TeamAuthFacade.withSystemAuthentication(manager.id()))); } }); } @@ -221,7 +221,7 @@ public Mono promoteMember(String id, String memberId, boolean isManager) { @Override public Flux delete(Collection ids) { return authFacade.getConnectedUser() - .flatMapMany(user -> Flux.fromIterable(ids).filter(id -> RoleUtils.hasPermission(user.self, Permission.manager(id))) + .flatMapMany(user -> Flux.fromIterable(ids).filter(id -> RoleUtils.hasPermission(user.self(), Permission.manager(id))) .switchIfEmpty(Mono.error(() -> new TeamPermissionDenied("You must be manager of the team to delete it !"))) .collectList() .flatMap(teamsIds -> @@ -231,7 +231,7 @@ public Flux delete(Collection ids) { teamsIds.stream() .map(id -> Permission.manager(id).toString()) .collect(Collectors.toUnmodifiableSet()) - ).contextWrite(TeamAuthFacade.withSystemAuthentication(user.id)) + ).contextWrite(TeamAuthFacade.withSystemAuthentication(user.id())) ).thenReturn(teamsIds)) .flatMapMany(Flux::fromIterable)); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamMembersController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamMembersController.java index 629f050a..dde97aa1 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamMembersController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamMembersController.java @@ -70,8 +70,8 @@ public Mono, Map>> currentUserAsMember(L MapType gqlType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return authFacade.getConnectedUser() - .flatMapMany(userEntity -> teamsService.members(PageRequest.all(Criteria.property(USER_ID).eq(userEntity.id)))) - .collectMap(e -> e.id, Function.identity()) + .flatMapMany(userEntity -> teamsService.members(PageRequest.all(Criteria.property(USER_ID).eq(userEntity.id())))) + .collectMap(Entity::id, Function.identity()) .map(currentUsers -> teams.stream().map(t -> { String teamId = Optional.ofNullable(t.get("_id")).map(Object::toString).orElse(""); Entity meForTeam = currentUsers.get(teamId); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamsController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamsController.java index f22ca137..b93843a7 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamsController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/TeamsController.java @@ -68,7 +68,7 @@ public Flux> teamDelete(@Argument("id") List teamIds MapType gqlType = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return teamsService.list(PageRequest.all(Criteria.property(ID).in(teamIds))) .collectList() - .flatMapMany(teams -> teamsService.delete(teams.stream().map(e -> e.id).toList()) + .flatMapMany(teams -> teamsService.delete(teams.stream().map(Entity::id).toList()) .thenMany(Flux.fromIterable(teams))) .map(e -> mapper.convertValue(e, gqlType)); } @@ -83,7 +83,7 @@ public Flux> entities(Page> searchNewsResponse) @SchemaMapping(typeName = "SearchTeamsResponse") public Mono totalCount(Page> searchNewsResponse) { return Mono.justOrEmpty(searchNewsResponse.getHeaders().get("X-Total-Count")) - .map(h -> h.get(0)) + .map(List::getFirst) .map(Integer::parseInt) .switchIfEmpty(Mono.just(0)); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/UserMappingController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/UserMappingController.java index 7c54cf3d..3dfa771c 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/UserMappingController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/teams/infra/controllers/UserMappingController.java @@ -48,7 +48,7 @@ public Mono, Map>> teamMembers(List userIds = members.stream().map(m -> m.get("userId").toString()).toList(); return userService.list(PageRequest.all(Criteria.property(ID).in(userIds))).collectList() - .map(users -> users.stream().collect(Collectors.toUnmodifiableMap(e -> e.id, Function.identity()))) + .map(users -> users.stream().collect(Collectors.toUnmodifiableMap(Entity::id, Function.identity()))) .map(users -> members.stream().collect(Collectors.toUnmodifiableMap( Function.identity(), m -> { @@ -56,7 +56,7 @@ public Mono, Map>> teamMembers(List getTeamEntity(TeamsRecord teamsRecord); @InheritInverseConfiguration - @Mapping(target = "teamCreatedAt", expression = "java( DateUtils.toLocalDateTime(team.createdAt) )") + @Mapping(target = "teamCreatedAt", expression = "java( DateUtils.toLocalDateTime(team.createdAt()) )") TeamsRecord getTeamRecord(Entity team); @Mapping(source = "temeTeamId", target = "id") @@ -37,8 +37,8 @@ public interface TeamsMapper { Entity getMemberEntity(TeamsMembersRecord teamsMembersRecord); @InheritInverseConfiguration - @Mapping(target = "temePendingFor", expression = "java( request.self.pending().value() )") - @Mapping(target = "temeCreatedAt", expression = "java( DateUtils.toLocalDateTime(request.createdAt) )") + @Mapping(target = "temePendingFor", expression = "java( request.self().pending().value() )") + @Mapping(target = "temeCreatedAt", expression = "java( DateUtils.toLocalDateTime(request.createdAt()) )") TeamsMembersRecord getTeamsMemberRecord(Entity request); default Instant fromLocalDateTime(LocalDateTime date) { diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImpl.java index e80d0574..3c7e5f03 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImpl.java @@ -50,17 +50,17 @@ public Flux> list(PageRequest pageRequest) { return authFacade.getConnectedUser() .map(u -> { if (pageRequest.filter().accept(propertiesVisitor).contains(EntitiesProperties.ID)) { - return Tuples.of(QueryContext.from(pageRequest), u.id); + return Tuples.of(QueryContext.from(pageRequest), u.id()); } - return Tuples.of(QueryContext.from(pageRequest).withUserId(u.id), u.id); + return Tuples.of(QueryContext.from(pageRequest).withUserId(u.id()), u.id()); }) .switchIfEmpty(Mono.just(Tuples.of(QueryContext.from(pageRequest), Entity.NO_ONE))) .flatMapMany(qc -> feedRepository.list(qc.getT1()) .map(re -> { - String createdBy = Arrays.stream(re.createdBy.split(",")) + String createdBy = Arrays.stream(re.createdBy().split(",")) .filter(u -> qc.getT2().equals(u)) .findAny().orElse(Entity.NO_ONE); - return Entity.identify(re.id, createdBy, re.self); + return Entity.identify(re.id(), createdBy, re.self()); })); } @@ -71,7 +71,7 @@ public Mono count(PageRequest pageRequest) { } else { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .map(u -> QueryContext.all(pageRequest.filter()).withUserId(u.id)) + .map(u -> QueryContext.all(pageRequest.filter()).withUserId(u.id())) .onErrorResume(UnauthenticatedUser.class, e -> Mono.just(QueryContext.all(pageRequest.filter()))) .flatMap(feedRepository::count); } @@ -86,7 +86,7 @@ public Mono> update(WebFeed toPersist) { } return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .flatMap(u -> feedRepository.update(toPersist.reference(), u.id, toPersist)); + .flatMap(u -> feedRepository.update(toPersist.reference(), u.id(), toPersist)); } @Override @@ -106,7 +106,7 @@ public Flux> add(Collection toAdd) { public Flux> subscribe(Collection feeds) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .map(u -> Tuples.of(feeds, u.id)) + .map(u -> Tuples.of(feeds, u.id())) .flatMapMany(t -> feedRepository.persistUserRelation(t.getT1(), t.getT2())); } @@ -140,7 +140,7 @@ public Mono delete(Collection toDelete) { .map(u -> QueryContext.builder() .filter(Criteria.property(EntitiesProperties.FEED_ID).in(toDelete) .or(Criteria.property(EntitiesProperties.ID).in(toDelete))) - .userId(u.id) + .userId(u.id()) .build()) .flatMap(feedRepository::delete) .map(FeedDeletedResult::unsubscribed); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImpl.java index 009b5eec..a6309533 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImpl.java @@ -69,7 +69,7 @@ public Flux list(PageRequest pageRequest) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(() -> new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) .map(user -> throwOnInvalidRequest(validRequest, user)) - .map(user -> QueryContext.from(validRequest).withUserId(user.id)) + .map(user -> QueryContext.from(validRequest).withUserId(user.id())) .flatMap(this::forgeAggregateQueryContext) .onErrorResume(UnauthenticatedUser.class, e -> Mono.fromCallable(() -> throwOnInvalidRequest(validRequest, null)) @@ -83,7 +83,7 @@ public Mono count(PageRequest pageRequest) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(() -> new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) .map(user -> throwOnInvalidRequest(validRequest, user)) - .map(user -> QueryContext.all(validRequest.filter()).withUserId(user.id)) + .map(user -> QueryContext.all(validRequest.filter()).withUserId(user.id())) .flatMap(this::forgeAggregateQueryContext) .flatMap(newsRepository::count) .onErrorResume(UnauthenticatedUser.class, e -> Mono.just(pageRequest.pagination().size())); @@ -91,7 +91,7 @@ public Mono count(PageRequest pageRequest) { public Mono forgeAggregateQueryContext(QueryContext qCtx) { List props = qCtx.filter.accept(new ListPropertiesCriteriaVisitor()); - if (props.size() == 1 && ID.equals(props.get(0))) { + if (props.size() == 1 && ID.equals(props.getFirst())) { // Shortcut for get one News from id return Mono.just(qCtx); } @@ -135,7 +135,7 @@ public Mono> getFeedFor(QueryContext qCtx, List props) { ? QueryContext.all(qCtx.filter) : QueryContext.all(qCtx.filter).withUserId(qCtx.userId); return feedRepository.list(feedQCtx) - .map(f -> f.id) + .map(Entity::id) .collectList() .map(feeds -> { if (feedQCtx.isScoped()) { @@ -158,7 +158,7 @@ public Mono> getStateQueryContext(List teamMates) { .pagination(Pagination.ALL) .build(); return stateRepository.list(query) - .map(state -> state.id) + .map(Entity::id) .distinct().collectList(); } @@ -171,20 +171,20 @@ public Mono get(String id) { public Mono> mark(String id, int flag) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(() -> new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .flatMap(user -> stateRepository.flag(id, user.id, flag)); + .flatMap(user -> stateRepository.flag(id, user.id(), flag)); } @Override public Mono> unmark(String id, int flag) { return authFacade.getConnectedUser() .switchIfEmpty(Mono.error(() -> new UnauthenticatedUser(AUTHENTICATION_NOT_FOUND))) - .flatMap(user -> stateRepository.unflag(id, user.id, flag)); + .flatMap(user -> stateRepository.unflag(id, user.id(), flag)); } @Override public Mono delete(Collection toDelete) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedOperation("Deleting news not permitted for user !"))) .flatMap(user -> newsRepository.delete(toDelete)); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/PopularNewsServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/PopularNewsServiceImpl.java index d27fd6a3..a6ad5e3a 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/PopularNewsServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/PopularNewsServiceImpl.java @@ -1,5 +1,6 @@ package fr.ght1pc9kc.baywatch.techwatch.domain; +import fr.ght1pc9kc.baywatch.common.api.model.Entity; import fr.ght1pc9kc.baywatch.security.api.AuthenticationFacade; import fr.ght1pc9kc.baywatch.techwatch.api.PopularNewsService; import fr.ght1pc9kc.baywatch.techwatch.api.model.Popularity; @@ -31,7 +32,7 @@ public class PopularNewsServiceImpl implements PopularNewsService { @Override public Flux get(Collection ids) { return authFacade.getConnectedUser() - .flatMapMany(user -> teamServicePort.getTeamMates(user.id)) + .flatMapMany(user -> teamServicePort.getTeamMates(user.id())) .collectList().map(teamMates -> QueryContext.builder() .filter(Criteria.property(NEWS_ID).in(ids) .and(Criteria.property(USER_ID).in(teamMates)) @@ -39,10 +40,10 @@ public Flux get(Collection ids) { .pagination(Pagination.of(-1, -1, Sort.of(Direction.ASC, NEWS_ID))) .build()) .flatMapMany(stateRepository::list) - .bufferUntilChanged(s -> s.id) + .bufferUntilChanged(Entity::id) .map(states -> { - Set fans = states.stream().map(s -> s.createdBy).collect(Collectors.toUnmodifiableSet()); - return new Popularity(states.get(0).id, fans.size(), fans); + Set fans = states.stream().map(Entity::createdBy).collect(Collectors.toUnmodifiableSet()); + return new Popularity(states.getFirst().id(), fans.size(), fans); }); } } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImpl.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImpl.java index eb543fd6..54ea00ec 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImpl.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImpl.java @@ -7,7 +7,6 @@ import fr.ght1pc9kc.baywatch.security.api.model.RoleUtils; import fr.ght1pc9kc.baywatch.techwatch.api.SystemMaintenanceService; import fr.ght1pc9kc.baywatch.techwatch.api.model.News; -import fr.ght1pc9kc.baywatch.techwatch.api.model.RawNews; import fr.ght1pc9kc.baywatch.techwatch.api.model.WebFeed; import fr.ght1pc9kc.baywatch.techwatch.domain.model.QueryContext; import fr.ght1pc9kc.baywatch.techwatch.domain.ports.FeedPersistencePort; @@ -39,7 +38,7 @@ public Flux> feedList() { @Override public Flux> feedList(PageRequest pageRequest) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .flatMapMany(u -> feedRepository.list(QueryContext.from(pageRequest))); } @@ -47,7 +46,7 @@ public Flux> feedList(PageRequest pageRequest) { @Override public Mono feedDelete(Collection toDelete) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .map(u -> QueryContext.all(Criteria.property(FEED_ID).in(toDelete))) .flatMap(feedRepository::delete) @@ -57,7 +56,7 @@ public Mono feedDelete(Collection toDelete) { @Override public Flux newsList(PageRequest pageRequest) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .flatMapMany(u -> newsRepository.list(QueryContext.from(pageRequest))); } @@ -65,7 +64,7 @@ public Flux newsList(PageRequest pageRequest) { @Override public Flux newsIdList(PageRequest pageRequest) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .flatMapMany(u -> newsRepository.listId(QueryContext.from(pageRequest))); } @@ -73,7 +72,7 @@ public Flux newsIdList(PageRequest pageRequest) { @Override public Mono newsLoad(Collection toLoad) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .flatMap(user -> newsRepository.persist(toLoad)); } @@ -81,7 +80,7 @@ public Mono newsLoad(Collection toLoad) { @Override public Mono newsDelete(Collection toDelete) { return authFacade.getConnectedUser() - .filter(user -> RoleUtils.hasRole(user.self, Role.SYSTEM)) + .filter(user -> RoleUtils.hasRole(user.self(), Role.SYSTEM)) .switchIfEmpty(Mono.error(() -> new UnauthorizedException(EXCEPTION_MESSAGE))) .flatMap(user -> newsRepository.delete(toDelete)); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/adapters/TeamServiceAdapter.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/adapters/TeamServiceAdapter.java index 339eeb8b..f0490d81 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/adapters/TeamServiceAdapter.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/adapters/TeamServiceAdapter.java @@ -1,5 +1,6 @@ package fr.ght1pc9kc.baywatch.techwatch.infra.adapters; +import fr.ght1pc9kc.baywatch.common.api.model.Entity; import fr.ght1pc9kc.baywatch.teams.api.TeamsService; import fr.ght1pc9kc.baywatch.teams.domain.model.PendingFor; import fr.ght1pc9kc.baywatch.techwatch.domain.ports.TeamServicePort; @@ -20,10 +21,10 @@ public class TeamServiceAdapter implements TeamServicePort { @Override public Flux getTeamMates(String userId) { return teamsService.list(PageRequest.all()) - .map(t -> t.id) + .map(Entity::id) .collectList().flatMapMany(teamsId -> teamsService.members(PageRequest.all(Criteria.property(ID).in(teamsId)))) - .filter(t -> t.self.pending().equals(PendingFor.NONE)) - .map(t -> t.self.userId()); + .filter(t -> t.self().pending().equals(PendingFor.NONE)) + .map(t -> t.self().userId()); } } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedController.java index 8839e201..d3e0dccf 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedController.java @@ -94,7 +94,7 @@ public Flux bulkUpdate(@RequestBody PatchPayload patchs) { try { FeedForm toPersist = mapper.readerFor(FeedForm.class).readValue(resource.value(), FeedForm.class); Mono persisted = subscribe(Mono.just(toPersist)) - .map(re -> URI.create(FEED_BASE.getPath() + "/" + Objects.requireNonNull(re.getBody()).id)); + .map(re -> URI.create(FEED_BASE.getPath() + "/" + Objects.requireNonNull(re.getBody()).id())); operations.add(persisted); } catch (IOException e) { return Flux.error(new IllegalArgumentException("Malformed PATCH (add) request !", e)); @@ -105,7 +105,7 @@ public Flux bulkUpdate(@RequestBody PatchPayload patchs) { String id = FEED_BASE.relativize(resource.path()).toString(); FeedForm toPersist = mapper.readerFor(FeedForm.class).readValue(resource.value(), FeedForm.class); Mono persisted = update(id, Mono.just(toPersist)) - .map(re -> URI.create(FEED_BASE.getPath() + "/" + re.id)); + .map(re -> URI.create(FEED_BASE.getPath() + "/" + re.id())); operations.add(persisted); } catch (IOException e) { return Flux.error(new IllegalArgumentException("Malformed PATCH (replace) request !", e)); @@ -152,7 +152,7 @@ public Mono>> subscribe(@Valid @RequestBody Mono< .build(); }) .flatMap(feed -> feedService.addAndSubscribe(Collections.singleton(feed)).next()) - .map(feed -> ResponseEntity.created(URI.create("/api/feeds/" + feed.id)).body(feed)) + .map(feed -> ResponseEntity.created(URI.create("/api/feeds/" + feed.id())).body(feed)) .onErrorMap(WebExchangeBindException.class, e -> { String message = e.getFieldErrors().stream().map(err -> err.getField() + " " + err.getDefaultMessage()).collect(Collectors.joining("\n")); diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsController.java index 52a27434..0e65f244 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsController.java @@ -72,7 +72,7 @@ public Flux> entities(Page> searchFeedsRespo @SchemaMapping(typeName = "SearchFeedsResponse") public Mono totalCount(Page> searchFeedsResponse) { return Mono.justOrEmpty(searchFeedsResponse.getHeaders().get("X-Total-Count")) - .map(h -> h.get(0)) + .map(List::getFirst) .map(Integer::parseInt) .switchIfEmpty(Mono.just(0)); } @@ -86,7 +86,7 @@ public Mono>>> feeds(List news) { List feedsIds = news.stream().flatMap(n -> n.getFeeds().stream()).distinct().toList(); PageRequest pageRequest = qsParser.parse(Map.of(EntitiesProperties.ID, feedsIds)); return feedService.list(pageRequest).collectList() - .map(feeds -> feeds.stream().collect(Collectors.toUnmodifiableMap(e -> e.id, Function.identity()))) + .map(feeds -> feeds.stream().collect(Collectors.toUnmodifiableMap(Entity::id, Function.identity()))) .map(feeds -> news.stream() .collect(Collectors.toUnmodifiableMap(Function.identity(), n -> n.getFeeds().stream() .filter(feeds::containsKey) @@ -110,7 +110,7 @@ public Mono> popularity(List news) { public Mono> subscribe(@Argument String id, @Argument String name, @Argument Collection tags) { Set tagsSet = Optional.ofNullable(tags).map(Set::copyOf).orElse(Set.of()); return feedService.get(id) - .map(f -> f.self.toBuilder().name(name).tags(tagsSet).build()) + .map(f -> f.self().toBuilder().name(name).tags(tagsSet).build()) .flatMapMany(f -> feedService.subscribe(Collections.singleton(f))) .next(); } diff --git a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/TagsController.java b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/TagsController.java index 137fe685..0cdd4502 100644 --- a/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/TagsController.java +++ b/sandside/src/main/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/TagsController.java @@ -25,7 +25,7 @@ public class TagsController { @GetMapping public Mono> list() { return feedService.list(PageRequest.all()) - .flatMap(f -> Flux.fromIterable(f.self.tags())) + .flatMap(f -> Flux.fromIterable(f.self().tags())) .distinct() .sort() .collectList() diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/common/infra/mappers/RecordToFeedConverterTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/common/infra/mappers/RecordToFeedConverterTest.java index 6e25e859..492512d7 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/common/infra/mappers/RecordToFeedConverterTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/common/infra/mappers/RecordToFeedConverterTest.java @@ -51,11 +51,11 @@ void should_convert_FeedRecord_to_Feed_pojo() { Entity actual = tested.recordToFeed(record); Assertions.assertAll( - () -> assertThat(actual.id).isEqualTo(TEST_SHA3), - () -> assertThat(actual.self.reference()).isEqualTo(TEST_SHA3), - () -> assertThat(actual.self.name()).isEqualTo("Blog ght1pc9kc"), - () -> assertThat(actual.self.location()).isEqualTo(TEST_URL), - () -> assertThat(actual.self.tags()).isEqualTo(Set.of("jedi", "light")) + () -> assertThat(actual.id()).isEqualTo(TEST_SHA3), + () -> assertThat(actual.self().reference()).isEqualTo(TEST_SHA3), + () -> assertThat(actual.self().name()).isEqualTo("Blog ght1pc9kc"), + () -> assertThat(actual.self().location()).isEqualTo(TEST_URL), + () -> assertThat(actual.self().tags()).isEqualTo(Set.of("jedi", "light")) ); } } \ No newline at end of file diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImplTest.java index e4037d1b..4c51c2e2 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/domain/NotifyServiceImplTest.java @@ -65,7 +65,7 @@ void should_broadcast_notification() { actualLuke::add, errorsLuke::add); ServerEvent eventBroadcast = tested.broadcast(EventType.NEWS_UPDATE, 42); - ServerEvent eventUser = tested.send(LUKE.id, EventType.USER_NOTIFICATION, "I'm your father"); + ServerEvent eventUser = tested.send(LUKE.id(), EventType.USER_NOTIFICATION, "I'm your father"); assertThat(disposableObiwan.isDisposed()).isFalse(); assertThat(disposableLuke.isDisposed()).isFalse(); @@ -104,7 +104,7 @@ void should_send_notification_to_user() { Disposable disposable = tested.subscribe().subscribe( actualObiwan::add, errorsObiwan::add); - ServerEvent eventUser = tested.send(UserSamples.OBIWAN.id, EventType.USER_NOTIFICATION, "I'm your father"); + ServerEvent eventUser = tested.send(UserSamples.OBIWAN.id(), EventType.USER_NOTIFICATION, "I'm your father"); tested.close(); @@ -137,14 +137,14 @@ void should_store_notification_when_user_absent() { BasicEvent event = new BasicEvent<>(Ulid.fast().toString(), EventType.USER_NOTIFICATION, "I'm your father"); when(authFacadeMock.getConnectedUser()).thenReturn(Mono.just(OBIWAN)); - tested.send(UserSamples.OBIWAN.id, EventType.USER_NOTIFICATION, "I'm your father"); + tested.send(UserSamples.OBIWAN.id(), EventType.USER_NOTIFICATION, "I'm your father"); verify(notificationPersistenceMock).persist(any()); reset(notificationPersistenceMock); when(notificationPersistenceMock.persist(any())).thenReturn(Mono.just(event)); - tested.send(UserSamples.OBIWAN.id, EventType.USER_NOTIFICATION, Mono.just("I'm your father")); + tested.send(UserSamples.OBIWAN.id(), EventType.USER_NOTIFICATION, Mono.just("I'm your father")); verify(notificationPersistenceMock).persist(any()); } diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapterTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapterTest.java index 96b7d73e..b46ea503 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapterTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/adapters/NotificationPersistenceAdapterTest.java @@ -49,7 +49,7 @@ void setUp(DSLContext dsl) { void should_consume_notifications(DSLContext dsl) { assertThat(dsl.fetchCount(Notifications.NOTIFICATIONS)).isNotZero(); - Flux actuals = tested.consume(UserSamples.OBIWAN.id); + Flux actuals = tested.consume(UserSamples.OBIWAN.id()); StepVerifier.create(actuals) .assertNext(actual -> Assertions.assertAll( @@ -64,7 +64,7 @@ void should_consume_notifications(DSLContext dsl) { void should_consume_dummy_notifications(DSLContext dsl) { assertThat(dsl.fetchCount(Notifications.NOTIFICATIONS)).isNotZero(); - Flux actuals = tested.consume(UserSamples.MWINDU.id); + Flux actuals = tested.consume(UserSamples.MWINDU.id()); StepVerifier.create(actuals) .assertNext(actual -> Assertions.assertAll( @@ -79,7 +79,7 @@ void should_consume_dummy_notifications(DSLContext dsl) { void should_not_consume_notifications(DSLContext dsl) { assertThat(dsl.fetchCount(Notifications.NOTIFICATIONS)).isNotZero(); - Flux actuals = tested.consume(UserSamples.DSIDIOUS.id); + Flux actuals = tested.consume(UserSamples.DSIDIOUS.id()); StepVerifier.create(actuals).verifyComplete(); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/samples/NotificationsRecordSamples.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/samples/NotificationsRecordSamples.java index 0d4acbe2..b364b5c6 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/samples/NotificationsRecordSamples.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/notify/infra/samples/NotificationsRecordSamples.java @@ -24,12 +24,12 @@ public class NotificationsRecordSamples implements RelationalDataSet l.get(1).asStartElement().getName().getLocalPart().equals(tag) - && l.get(l.size() - 1).asEndElement().getName().getLocalPart().equals(tag)) + && l.getLast().asEndElement().getName().getLocalPart().equals(tag)) .expectNextCount(expectedCount) .verifyComplete(); } @@ -133,7 +133,7 @@ void should_read_feed_headers(String resource, String expectedId, String expecte void should_read_rss_item(String inputFileName, String expectedTitle, String expectedUrl, String expectedPubDate, String expectedDescription) { List xmlEvents = toXmlEventList(inputFileName); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title).isEqualTo(expectedTitle), @@ -147,7 +147,7 @@ void should_read_rss_item(String inputFileName, String expectedTitle, String exp void should_read_atom_entry() { List xmlEvents = toXmlEventList("feeds/atom_entry.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title) @@ -170,7 +170,7 @@ void should_read_atom_entry() { void should_read_atom_entry_with_html_content() { List xmlEvents = toXmlEventList("feeds/atom_entry_with_html_content.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title) @@ -190,7 +190,7 @@ void should_read_atom_entry_with_html_content() { void should_read_rss_item_with_encoded_content() { List xmlEvents = toXmlEventList("feeds/rss_item_with_encoded_content.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title) @@ -210,7 +210,7 @@ void should_read_rss_item_with_encoded_content() { void should_read_rss_item_with_cdata() { List xmlEvents = toXmlEventList("feeds/rss_item_with_cdata.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title) @@ -230,7 +230,7 @@ void should_read_rss_item_with_cdata() { void should_read_rss_item_with_relative_link() { List xmlEvents = toXmlEventList("feeds/rss_item_with_relative_link.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) .assertNext(actual -> Assertions.assertAll( () -> assertThat(actual).extracting(RawNews::title) @@ -247,7 +247,7 @@ void should_read_rss_item_with_relative_link() { @Test void should_read_rss_item_with_illegal_protocol() { List xmlEvents = toXmlEventList("feeds/rss_item_with_illegal_protocol.xml"); - ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id, FeedSamples.JEDI.self.location()); + ScrapedFeed sampleFeed = new ScrapedFeed(FeedSamples.JEDI.id(), FeedSamples.JEDI.self().location()); StepVerifier.create(tested.readEntryEvents(xmlEvents, sampleFeed)) // Illegal link give empty Mono .verifyComplete(); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/scraper/infra/FeedScraperIntegrationTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/scraper/infra/FeedScraperIntegrationTest.java index b446dc74..7de2c402 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/scraper/infra/FeedScraperIntegrationTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/scraper/infra/FeedScraperIntegrationTest.java @@ -211,7 +211,7 @@ public Mono> getConnectedUser() { @Override public Context withAuthentication(Entity user) { Authentication authentication = new PreAuthenticatedAuthenticationToken(user, null, - AuthorityUtils.createAuthorityList(user.self.roles.stream().map(RoleUtils::toSpringAuthority).toArray(String[]::new))); + AuthorityUtils.createAuthorityList(user.self().roles.stream().map(RoleUtils::toSpringAuthority).toArray(String[]::new))); return ReactiveSecurityContextHolder.withAuthentication(authentication); } }; diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/api/model/RoleUtilsTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/api/model/RoleUtilsTest.java index 45aefa58..ad43b423 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/api/model/RoleUtilsTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/api/model/RoleUtilsTest.java @@ -26,19 +26,19 @@ class RoleUtilsTest { NOT_A_ROLE | USER | | false """) void should_check_user_has_role(String role, Role compare, String entity, boolean expected) { - assertThat(RoleUtils.hasPermission(UserSamples.OBIWAN.self.withRoles(role), Permission.of(compare, entity))) + assertThat(RoleUtils.hasPermission(UserSamples.OBIWAN.self().withRoles(role), Permission.of(compare, entity))) .isEqualTo(expected); } @Test void should_fail_upade_user_roles() { - assertThat(UserSamples.OBIWAN.self.withRoles("NOT_A_ROLE", Role.USER.name()).roles) + assertThat(UserSamples.OBIWAN.self().withRoles("NOT_A_ROLE", Role.USER.name()).roles) .containsOnly(Role.USER); } @Test void should_get_system() { - assertThat(RoleUtils.getSystemUser().self.roles).containsOnly(Role.SYSTEM); + assertThat(RoleUtils.getSystemUser().self().roles).containsOnly(Role.SYSTEM); } @ParameterizedTest diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImplTest.java index b0260e52..02cbdc5d 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/domain/UserServiceImplTest.java @@ -39,7 +39,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -61,7 +60,7 @@ class UserServiceImplTest { void setUp() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.YODA)); doAnswer(answer -> Stream.of(UserSamples.LUKE, UserSamples.YODA, UserSamples.OBIWAN) - .filter(u -> u.id.equals(answer.getArgument(0, String.class))) + .filter(u -> u.id().equals(answer.getArgument(0, String.class))) .findAny().map(Mono::just).orElseThrow() ).when(mockUserRepository).get(anyString()); when(mockUserRepository.list(any())).thenReturn(Flux.just(UserSamples.LUKE, UserSamples.OBIWAN, UserSamples.YODA)); @@ -80,7 +79,7 @@ void setUp() { @Test void should_get_user() { - StepVerifier.create(tested.get(UserSamples.LUKE.id)) + StepVerifier.create(tested.get(UserSamples.LUKE.id())) .expectNext(UserSamples.LUKE) .verifyComplete(); } @@ -105,7 +104,7 @@ void should_count_users() { void should_create_user_without_authentication() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.empty()); - StepVerifier.create(tested.create(UserSamples.OBIWAN.self)) + StepVerifier.create(tested.create(UserSamples.OBIWAN.self())) .verifyError(UnauthenticatedUser.class); } @@ -113,7 +112,7 @@ void should_create_user_without_authentication() { void should_create_user_without_admin() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.create(UserSamples.OBIWAN.self)) + StepVerifier.create(tested.create(UserSamples.OBIWAN.self())) .verifyError(UnauthorizedOperation.class); } @@ -123,9 +122,9 @@ void should_create_user_with_admin() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.YODA)); when(mockUserRepository.persist(any())).thenReturn(Flux.just(UserSamples.OBIWAN)); when(mockUserRepository.persist(anyString(), anyCollection())).thenReturn(Mono.just(UserSamples.OBIWAN)); - when(mockUlidFactory.create()).thenReturn(Ulid.from(UserSamples.OBIWAN.id.substring(2))); + when(mockUlidFactory.create()).thenReturn(Ulid.from(UserSamples.OBIWAN.id().substring(2))); - StepVerifier.create(tested.create(UserSamples.OBIWAN.self)) + StepVerifier.create(tested.create(UserSamples.OBIWAN.self())) .expectNext(UserSamples.OBIWAN) .verifyComplete(); @@ -133,57 +132,57 @@ void should_create_user_with_admin() { verify(mockUserRepository).persist(users.capture()); Entity actual = users.getValue().getFirst(); - Assertions.assertThat(actual).isEqualTo(Entity.identify(UserSamples.OBIWAN.id, CURRENT, UserSamples.OBIWAN.self)); + Assertions.assertThat(actual).isEqualTo(Entity.identify(UserSamples.OBIWAN.id(), CURRENT, UserSamples.OBIWAN.self())); } @Test void should_update_other_user_as_admin() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.YODA)); when(mockUserRepository.update(anyString(), any())).thenReturn(Mono.just(UserSamples.OBIWAN)); - UpdatableUser obiChan = UserSamples.OBIWAN.self.updatable() + UpdatableUser obiChan = UserSamples.OBIWAN.self().updatable() .name(Optional.of("Obi Chan")) .build(); - Mono> actual = tested.update(UserSamples.OBIWAN.id, obiChan, "kenobi"); + Mono> actual = tested.update(UserSamples.OBIWAN.id(), obiChan, "kenobi"); StepVerifier.create(actual) .assertNext(a -> Assertions.assertThat(a).isNotNull()) .verifyComplete(); - verify(mockUserRepository).update(UserSamples.OBIWAN.id, obiChan); + verify(mockUserRepository).update(UserSamples.OBIWAN.id(), obiChan); } @Test void should_update_my_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); when(mockUserRepository.update(anyString(), any())).thenReturn(Mono.just(UserSamples.OBIWAN)); - UpdatableUser obiChan = UserSamples.OBIWAN.self.updatable() + UpdatableUser obiChan = UserSamples.OBIWAN.self().updatable() .name(Optional.of("Obi Chan")) .build(); - Mono> actual = tested.update(UserSamples.OBIWAN.id, obiChan, UserSamples.OBIWAN.self.password); + Mono> actual = tested.update(UserSamples.OBIWAN.id(), obiChan, UserSamples.OBIWAN.self().password); StepVerifier.create(actual) .assertNext(a -> Assertions.assertThat(a).isNotNull()) .verifyComplete(); - verify(mockUserRepository).update(UserSamples.OBIWAN.id, obiChan); + verify(mockUserRepository).update(UserSamples.OBIWAN.id(), obiChan); } @Test void should_fail_update_user_with_invalid_password() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); when(mockUserRepository.update(anyString(), any())).thenReturn(Mono.just(UserSamples.OBIWAN)); - UpdatableUser obiChan = UserSamples.OBIWAN.self.updatable() + UpdatableUser obiChan = UserSamples.OBIWAN.self().updatable() .name(Optional.of("Obi Chan")) .build(); - Mono> actual = tested.update(UserSamples.OBIWAN.id, obiChan, "Invalid Password"); + Mono> actual = tested.update(UserSamples.OBIWAN.id(), obiChan, "Invalid Password"); StepVerifier.create(actual) .verifyError(UnauthorizedOperation.class); - verify(mockUserRepository, never()).update(UserSamples.OBIWAN.id, obiChan); + verify(mockUserRepository, never()).update(UserSamples.OBIWAN.id(), obiChan); } @Test @@ -193,7 +192,7 @@ void should_delete_users_as_admin() { when(mockUserRepository.list(any())).thenReturn(Flux.just(UserSamples.OBIWAN)); when(mockUserRepository.delete(anyCollection())).thenReturn(Mono.just(1)); - StepVerifier.create(tested.delete(List.of(UserSamples.OBIWAN.id))) + StepVerifier.create(tested.delete(List.of(UserSamples.OBIWAN.id()))) .expectNext(UserSamples.OBIWAN) .verifyComplete(); @@ -203,37 +202,37 @@ void should_delete_users_as_admin() { verify(mockUserRepository).delete(deleted.capture()); Assertions.assertThat(selected.getValue()) - .isEqualTo(QueryContext.all(Criteria.property(EntitiesProperties.ID).in(UserSamples.OBIWAN.id))); - Assertions.assertThat(deleted.getValue()).isEqualTo(List.of(UserSamples.OBIWAN.id)); + .isEqualTo(QueryContext.all(Criteria.property(EntitiesProperties.ID).in(UserSamples.OBIWAN.id()))); + Assertions.assertThat(deleted.getValue()).isEqualTo(List.of(UserSamples.OBIWAN.id())); } @Test void should_grant_role_as_admin() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.YODA)); - StepVerifier.create(tested.grants(UserSamples.LUKE.id, List.of(Permission.manager("42")))) + StepVerifier.create(tested.grants(UserSamples.LUKE.id(), List.of(Permission.manager("42")))) .expectNext(UserSamples.LUKE) .verifyComplete(); - verify(mockUserRepository).persist(UserSamples.LUKE.id, List.of("MANAGER:42")); + verify(mockUserRepository).persist(UserSamples.LUKE.id(), List.of("MANAGER:42")); } @Test void should_grant_role_as_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.grants(UserSamples.LUKE.id, List.of(Permission.manager("42")))) + StepVerifier.create(tested.grants(UserSamples.LUKE.id(), List.of(Permission.manager("42")))) .expectNext(UserSamples.LUKE) .verifyComplete(); - verify(mockUserRepository).persist(UserSamples.LUKE.id, List.of("MANAGER:42")); + verify(mockUserRepository).persist(UserSamples.LUKE.id(), List.of("MANAGER:42")); } @Test void should_fail_to_elevate_self_role() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.grants(UserSamples.LUKE.id, List.of(Role.ADMIN))) + StepVerifier.create(tested.grants(UserSamples.LUKE.id(), List.of(Role.ADMIN))) .verifyError(UnauthorizedOperation.class); } @@ -241,7 +240,7 @@ void should_fail_to_elevate_self_role() { void should_fail_to_grant_other_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.grants(UserSamples.OBIWAN.id, List.of(Permission.manager("42")))) + StepVerifier.create(tested.grants(UserSamples.OBIWAN.id(), List.of(Permission.manager("42")))) .verifyError(UnauthorizedOperation.class); } @@ -249,29 +248,29 @@ void should_fail_to_grant_other_user() { void should_revoke_role_as_admin() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.YODA)); - StepVerifier.create(tested.revokes(Permission.manager("42"), List.of(UserSamples.LUKE.id))) + StepVerifier.create(tested.revokes(Permission.manager("42"), List.of(UserSamples.LUKE.id()))) .expectNext() .verifyComplete(); - verify(mockUserRepository).delete("MANAGER:42", List.of(UserSamples.LUKE.id)); + verify(mockUserRepository).delete("MANAGER:42", List.of(UserSamples.LUKE.id())); } @Test void should_revoke_role_as_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.revokes(Permission.manager("42"), List.of(UserSamples.LUKE.id))) + StepVerifier.create(tested.revokes(Permission.manager("42"), List.of(UserSamples.LUKE.id()))) .expectNext() .verifyComplete(); - verify(mockUserRepository).delete("MANAGER:42", List.of(UserSamples.LUKE.id)); + verify(mockUserRepository).delete("MANAGER:42", List.of(UserSamples.LUKE.id())); } @Test void should_fail_to_revoke_other_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); - StepVerifier.create(tested.revokes(Role.MANAGER, List.of(UserSamples.OBIWAN.id))) + StepVerifier.create(tested.revokes(Role.MANAGER, List.of(UserSamples.OBIWAN.id()))) .verifyError(UnauthorizedOperation.class); } } \ No newline at end of file diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/infra/persistence/UserRepositoryTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/infra/persistence/UserRepositoryTest.java index 2b9be979..a7c7bb2a 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/infra/persistence/UserRepositoryTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/security/infra/persistence/UserRepositoryTest.java @@ -73,13 +73,13 @@ void should_get_user(WithSampleDataLoaded.Tracker dbTracker) { StepVerifier.create(tested.get(UsersRecordSamples.OKENOBI.getUserId())) .assertNext(actual -> Assertions.assertAll( - () -> assertThat(actual.id).isEqualTo(UserSamples.OBIWAN.id), - () -> assertThat(actual.createdAt).isEqualTo(Instant.parse("1970-01-01T00:00:00Z")), - () -> assertThat(actual.self.name).isEqualTo("Obiwan Kenobi"), - () -> assertThat(actual.self.login).isEqualTo("okenobi"), - () -> assertThat(actual.self.mail).isEqualTo("obiwan.kenobi@jedi.com"), - () -> assertThat(actual.self.password).isEqualTo(UserSamples.OBIWAN.self.password), - () -> assertThat(actual.self.roles).containsOnly(Role.MANAGER) + () -> assertThat(actual.id()).isEqualTo(UserSamples.OBIWAN.id()), + () -> assertThat(actual.createdAt()).isEqualTo(Instant.parse("1970-01-01T00:00:00Z")), + () -> assertThat(actual.self().name).isEqualTo("Obiwan Kenobi"), + () -> assertThat(actual.self().login).isEqualTo("okenobi"), + () -> assertThat(actual.self().mail).isEqualTo("obiwan.kenobi@jedi.com"), + () -> assertThat(actual.self().password).isEqualTo(UserSamples.OBIWAN.self().password), + () -> assertThat(actual.self().roles).containsOnly(Role.MANAGER) )).verifyComplete(); } @@ -89,13 +89,13 @@ void should_get_user_with_multiple_roles(WithSampleDataLoaded.Tracker dbTracker) StepVerifier.create(tested.get(UsersRecordSamples.LSKYWALKER.getUserId())) .assertNext(actual -> Assertions.assertAll( - () -> assertThat(actual.id).isEqualTo(UserSamples.LUKE.id), - () -> assertThat(actual.createdAt).isEqualTo(Instant.parse("1970-01-01T00:00:00Z")), - () -> assertThat(actual.self.name).isEqualTo("Luke Skywalker"), - () -> assertThat(actual.self.login).isEqualTo("lskywalker"), - () -> assertThat(actual.self.mail).isEqualTo("luke.skywalker@jedi.com"), - () -> assertThat(actual.self.password).isEqualTo(UserSamples.LUKE.self.password), - () -> assertThat(actual.self.roles).containsOnly(Role.USER, Permission.manager("TM01GP696RFPTY32WD79CVB0KDTF")) + () -> assertThat(actual.id()).isEqualTo(UserSamples.LUKE.id()), + () -> assertThat(actual.createdAt()).isEqualTo(Instant.parse("1970-01-01T00:00:00Z")), + () -> assertThat(actual.self().name).isEqualTo("Luke Skywalker"), + () -> assertThat(actual.self().login).isEqualTo("lskywalker"), + () -> assertThat(actual.self().mail).isEqualTo("luke.skywalker@jedi.com"), + () -> assertThat(actual.self().password).isEqualTo(UserSamples.LUKE.self().password), + () -> assertThat(actual.self().roles).containsOnly(Role.USER, Permission.manager("TM01GP696RFPTY32WD79CVB0KDTF")) )).verifyComplete(); } @@ -113,7 +113,7 @@ void should_list_user_with_criteria(WithSampleDataLoaded.Tracker dbTracker) { dbTracker.skipNextSampleLoad(); StepVerifier.create(tested.list(QueryContext.all(Criteria.property("name").eq("Obiwan Kenobi")))) - .expectNextMatches(actual -> UserSamples.OBIWAN.id.equals(actual.id)) + .expectNextMatches(actual -> UserSamples.OBIWAN.id().equals(actual.id())) .verifyComplete(); } @@ -190,8 +190,8 @@ void should_persist_roles(DSLContext dsl) { .containsOnly("MANAGER:TM01GP696RFPTY32WD79CVB0KDTF", "USER"); StepVerifier.create(tested.persist(UsersRecordSamples.LSKYWALKER.getUserId(), List.of("MANAGER:42")) - .map(e -> e.self)) - .expectNext(UserSamples.LUKE.self.withRoles("MANAGER:TM01GP696RFPTY32WD79CVB0KDTF", "USER", "MANAGER:42")) + .map(Entity::self)) + .expectNext(UserSamples.LUKE.self().withRoles("MANAGER:TM01GP696RFPTY32WD79CVB0KDTF", "USER", "MANAGER:42")) .verifyComplete(); assertThat( diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImplTest.java index f5c89e15..47f05288 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/domain/TeamServiceImplTest.java @@ -85,7 +85,7 @@ void setUp(DSLContext dsl) { when(mockAuthFacade.grantAuthorization(any(), anyCollection())).thenReturn(Mono.empty().then()); when(mockAuthFacade.revokeAuthorization(any(), anyCollection())).thenReturn(Mono.empty().then()); when(mockAuthFacade.removeAuthorizations(anyCollection())).thenReturn(Mono.empty().then()); - when(mockAuthFacade.listManagers(anyString())).thenReturn(Flux.just(UserSamples.MWINDU.id)); + when(mockAuthFacade.listManagers(anyString())).thenReturn(Flux.just(UserSamples.MWINDU.id())); Scheduler immediate = Schedulers.immediate(); TeamsMapper mapper = Mappers.getMapper(TeamsMapper.class); @@ -100,7 +100,7 @@ void should_get_team(Tracker dbTracker) { dbTracker.skipNextSampleLoad(); StepVerifier.create(tested.get("TM01GP696RFPTY32WD79CVB0KDTF")) - .assertNext(next -> Assertions.assertThat(next.id).isEqualTo("TM01GP696RFPTY32WD79CVB0KDTF")) + .assertNext(next -> Assertions.assertThat(next.id()).isEqualTo("TM01GP696RFPTY32WD79CVB0KDTF")) .verifyComplete(); } @@ -110,7 +110,7 @@ void should_list_teams(Tracker dbTracker) { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.LUKE)); StepVerifier.create(tested.list(PageRequest.all())) - .assertNext(next -> Assertions.assertThat(next.id).isEqualTo("TM01GP696RFPTY32WD79CVB0KDTF")) + .assertNext(next -> Assertions.assertThat(next.id()).isEqualTo("TM01GP696RFPTY32WD79CVB0KDTF")) .verifyComplete(); } @@ -129,10 +129,10 @@ void should_create_team() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); StepVerifier.create(tested.create("Jedi council team", "May the Force be with you")) .assertNext(actual -> assertAll( - () -> Assertions.assertThat(actual.id).isNotBlank(), - () -> Assertions.assertThat(actual.createdBy).isEqualTo(UserSamples.OBIWAN.id), - () -> Assertions.assertThat(actual.self.name()).isEqualTo("Jedi council team"), - () -> verify(mockAuthFacade).grantAuthorization(UserSamples.OBIWAN.id, List.of("MANAGER:" + actual.id)) + () -> Assertions.assertThat(actual.id()).isNotBlank(), + () -> Assertions.assertThat(actual.createdBy()).isEqualTo(UserSamples.OBIWAN.id()), + () -> Assertions.assertThat(actual.self().name()).isEqualTo("Jedi council team"), + () -> verify(mockAuthFacade).grantAuthorization(UserSamples.OBIWAN.id(), List.of("MANAGER:" + actual.id())) )).verifyComplete(); } @@ -143,9 +143,9 @@ void should_update_managed_team(Entity manager, DSLContext dsl) { StepVerifier.create(tested.update(JEDI_TEAM.getTeamId(), "Luke Skywalker Team", "The new topic for Skywalker")) .assertNext(actual -> assertAll( - () -> Assertions.assertThat(actual.id).isEqualTo(JEDI_TEAM.getTeamId()), - () -> Assertions.assertThat(actual.self.name()).isEqualTo("Luke Skywalker Team"), - () -> Assertions.assertThat(actual.self.topic()).isEqualTo("The new topic for Skywalker") + () -> Assertions.assertThat(actual.id()).isEqualTo(JEDI_TEAM.getTeamId()), + () -> Assertions.assertThat(actual.self().name()).isEqualTo("Luke Skywalker Team"), + () -> Assertions.assertThat(actual.self().topic()).isEqualTo("The new topic for Skywalker") )).verifyComplete(); TeamsRecord actual = dsl.selectFrom(Teams.TEAMS).where(Teams.TEAMS.TEAM_ID.eq(JEDI_TEAM.getTeamId())) @@ -160,8 +160,8 @@ void should_update_managed_team(Entity manager, DSLContext dsl) { static Stream allowedTeamModificationUsers() { return Stream.of( - arguments(named(UserSamples.LUKE.self.name, UserSamples.LUKE)), - arguments(named(UserSamples.YODA.self.name, UserSamples.YODA)) + arguments(named(UserSamples.LUKE.self().name, UserSamples.LUKE)), + arguments(named(UserSamples.YODA.self().name, UserSamples.YODA)) ); } @@ -175,10 +175,10 @@ void should_fail_to_update_unmanaged_team() { @Test void should_list_team_members() { - StepVerifier.create(tested.members(PageRequest.all(Criteria.property(ID).eq(JEDI_TEAM.getTeamId()))).map(e -> e.self.userId()).collectList()) + StepVerifier.create(tested.members(PageRequest.all(Criteria.property(ID).eq(JEDI_TEAM.getTeamId()))).map(e -> e.self().userId()).collectList()) .assertNext(actual -> Assertions.assertThat(actual).containsOnly( - UserSamples.LUKE.id, - UserSamples.OBIWAN.id + UserSamples.LUKE.id(), + UserSamples.OBIWAN.id() )).verifyComplete(); } @@ -187,22 +187,22 @@ void should_list_team_members() { void should_add_member(Entity user, PendingFor expectedPendingFor) { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(user)); - StepVerifier.create(tested.addMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.DSIDIOUS.id)).collectList()) + StepVerifier.create(tested.addMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.DSIDIOUS.id())).collectList()) .assertNext(actual -> assertAll( () -> Assertions.assertThat(actual).isNotNull().isNotEmpty(), - () -> Assertions.assertThat(actual).extracting(e -> e.self.userId()).containsOnly( - UserSamples.DSIDIOUS.id, UserSamples.LUKE.id, UserSamples.OBIWAN.id), + () -> Assertions.assertThat(actual).extracting(e -> e.self().userId()).containsOnly( + UserSamples.DSIDIOUS.id(), UserSamples.LUKE.id(), UserSamples.OBIWAN.id()), () -> Assertions.assertThat(requireNonNull(actual).stream() - .filter(e -> e.self.userId().equals(UserSamples.DSIDIOUS.id)) + .filter(e -> e.self().userId().equals(UserSamples.DSIDIOUS.id())) .findFirst()).isPresent() - .map(e -> e.self.pending()).contains(expectedPendingFor) + .map(e -> e.self().pending()).contains(expectedPendingFor) )).verifyComplete(); } static Stream addMembersProfiles() { return Stream.of( - arguments(named(UserSamples.DSIDIOUS.self.name, UserSamples.DSIDIOUS), PendingFor.MANAGER), - arguments(named(UserSamples.LUKE.self.name, UserSamples.LUKE), PendingFor.USER) + arguments(named(UserSamples.DSIDIOUS.self().name, UserSamples.DSIDIOUS), PendingFor.MANAGER), + arguments(named(UserSamples.LUKE.self().name, UserSamples.LUKE), PendingFor.USER) ); } @@ -211,11 +211,11 @@ static Stream addMembersProfiles() { void should_remove_member_as(Entity user) { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(user)); - StepVerifier.create(tested.removeMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.OBIWAN.id)).collectList()) + StepVerifier.create(tested.removeMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.OBIWAN.id())).collectList()) .assertNext(actual -> assertAll( () -> Assertions.assertThat(actual).isNotNull().isNotEmpty(), - () -> Assertions.assertThat(actual).extracting(e -> e.self.userId()) - .containsOnly(UserSamples.LUKE.id) + () -> Assertions.assertThat(actual).extracting(e -> e.self().userId()) + .containsOnly(UserSamples.LUKE.id()) )).verifyComplete(); } @@ -231,7 +231,7 @@ static Stream removeMembersProfiles() { void should_fail_to_remove_member_as_unauthorized_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.DSIDIOUS)); - StepVerifier.create(tested.removeMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.OBIWAN.id)).collectList()) + StepVerifier.create(tested.removeMembers(JEDI_TEAM.getTeamId(), List.of(UserSamples.OBIWAN.id())).collectList()) .verifyError(TeamPermissionDenied.class); } diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/infra/samples/TeamsMembersRecordSamples.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/infra/samples/TeamsMembersRecordSamples.java index 73d1d3a7..83469db7 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/infra/samples/TeamsMembersRecordSamples.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/teams/infra/samples/TeamsMembersRecordSamples.java @@ -18,14 +18,14 @@ public List records() { return List.of( TEAMS_MEMBERS.newRecord() .setTemeTeamId(TeamsRecordSamples.JEDI_TEAM.getTeamId()) - .setTemeUserId(UserSamples.LUKE.id) - .setTemeCreatedBy(UserSamples.LUKE.id) + .setTemeUserId(UserSamples.LUKE.id()) + .setTemeCreatedBy(UserSamples.LUKE.id()) .setTemeCreatedAt(LocalDateTime.parse("2023-01-10T22:52:42")) .setTemePendingFor(PendingFor.NONE.value()), TEAMS_MEMBERS.newRecord() .setTemeTeamId(TeamsRecordSamples.JEDI_TEAM.getTeamId()) - .setTemeUserId(UserSamples.OBIWAN.id) - .setTemeCreatedBy(UserSamples.LUKE.id) + .setTemeUserId(UserSamples.OBIWAN.id()) + .setTemeCreatedBy(UserSamples.LUKE.id()) .setTemeCreatedAt(LocalDateTime.parse("2023-01-12T22:52:42")) .setTemePendingFor(PendingFor.NONE.value()) ); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImplTest.java index bedbd0cf..0b1c2187 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/FeedServiceImplTest.java @@ -58,7 +58,7 @@ void setUp() { when(mockFeedRepository.count(any())).thenReturn(Mono.just(42)); ScraperServicePort mockScraperService = mock(ScraperServicePort.class); - when(mockScraperService.fetchFeedData(any())).thenReturn(Mono.just(FeedSamples.JEDI.self)); + when(mockScraperService.fetchFeedData(any())).thenReturn(Mono.just(FeedSamples.JEDI.self())); tested = new FeedServiceImpl(mockFeedRepository, mockScraperService, mockAuthFacade, new ListPropertiesCriteriaVisitor() { }); } @@ -90,7 +90,7 @@ void should_list_feed_for_user() { tested.list().collectList().block(); verify(mockFeedRepository, times(1)).list(captor.capture()); - assertThat(captor.getValue()).isEqualTo(QueryContext.empty().withUserId(UserSamples.OBIWAN.id)); + assertThat(captor.getValue()).isEqualTo(QueryContext.empty().withUserId(UserSamples.OBIWAN.id())); } { @@ -99,7 +99,7 @@ void should_list_feed_for_user() { verify(mockFeedRepository, times(1)).list(captor.capture()); assertThat(captor.getValue()).isEqualTo(QueryContext.first( - Criteria.property("name").eq("jedi")).withUserId(UserSamples.OBIWAN.id)); + Criteria.property("name").eq("jedi")).withUserId(UserSamples.OBIWAN.id())); } } @@ -121,18 +121,18 @@ void should_add_feed_from_user() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); - StepVerifier.create(tested.add(List.of(FeedSamples.JEDI.self))) + StepVerifier.create(tested.add(List.of(FeedSamples.JEDI.self()))) .expectNext(FeedSamples.JEDI) .verifyComplete(); verify(mockFeedRepository, times(1)).persist(captor.capture()); - assertThat(captor.getValue()).containsExactly(FeedSamples.JEDI.self); + assertThat(captor.getValue()).containsExactly(FeedSamples.JEDI.self()); } @Test @SuppressWarnings("unchecked") void should_subscribe_feeds_for_user() { - WebFeed jediFeed = BAYWATCH_MAPPER.recordToFeed(FeedRecordSamples.JEDI).self; + WebFeed jediFeed = BAYWATCH_MAPPER.recordToFeed(FeedRecordSamples.JEDI).self(); when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); @@ -148,10 +148,10 @@ void should_subscribe_feeds_for_user() { @Test void should_add_unsecured_url() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(UserSamples.OBIWAN)); - StepVerifier.create(tested.add(List.of(FeedSamples.UNSECURE_PROTOCOL.self))) + StepVerifier.create(tested.add(List.of(FeedSamples.UNSECURE_PROTOCOL.self()))) .verifyError(IllegalArgumentException.class); - StepVerifier.create(tested.update(FeedSamples.UNSECURE_PROTOCOL.self)) + StepVerifier.create(tested.update(FeedSamples.UNSECURE_PROTOCOL.self())) .verifyError(IllegalArgumentException.class); } diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImplTest.java index 69b8b0f6..96a87b20 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/NewsServiceImplTest.java @@ -55,7 +55,7 @@ void setUp() { mockAuthFacade = mock(AuthenticationFacade.class); StatePersistencePort mockStateRepository = mock(StatePersistencePort.class); when(mockStateRepository.list(any())).thenReturn(Flux.just( - Entity.identify(MAY_THE_FORCE.id(), OBIWAN.id, MAY_THE_FORCE.getState()) + Entity.identify(MAY_THE_FORCE.id(), OBIWAN.id(), MAY_THE_FORCE.getState()) )); FeedPersistencePort mockFeedRepository = mock(FeedPersistencePort.class); when(mockFeedRepository.list(any())).thenReturn(Flux.fromIterable(FeedSamples.SAMPLES)); @@ -118,12 +118,12 @@ void should_list_news_for_authenticated_user() { ArgumentCaptor userIdCaptor = ArgumentCaptor.forClass(String.class); verify(mockTeamServicePort, times(1)).getTeamMates(userIdCaptor.capture()); - Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id); + Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id()); verify(mockNewsPersistence, times(1)).list(captor.capture()); Assertions.assertThat(captor.getValue().filter).isEqualTo( Criteria.or( // FEED_ID in the 2 FEEDS ids plus the ID of the connected user - Criteria.property(FEED_ID).in(JEDI.id, SITH.id, LUKE.id), + Criteria.property(FEED_ID).in(JEDI.id(), SITH.id(), LUKE.id()), Criteria.property(NEWS_ID).in(MAY_THE_FORCE.id()) ) ); @@ -142,12 +142,12 @@ void should_count_for_authenticated_user() { ArgumentCaptor userIdCaptor = ArgumentCaptor.forClass(String.class); verify(mockTeamServicePort, times(1)).getTeamMates(userIdCaptor.capture()); - Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id); + Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id()); verify(mockNewsPersistence, times(1)).count(captor.capture()); Assertions.assertThat(captor.getValue().filter).isEqualTo( Criteria.or(// FEED_ID in the 2 FEEDS ids plus the ID of the connected user - Criteria.property(FEED_ID).in(JEDI.id, SITH.id, LUKE.id), + Criteria.property(FEED_ID).in(JEDI.id(), SITH.id(), LUKE.id()), Criteria.property(NEWS_ID).in(MAY_THE_FORCE.id()) ) ); @@ -156,7 +156,7 @@ void should_count_for_authenticated_user() { @Test void should_list_news_with_teammates() { when(mockAuthFacade.getConnectedUser()).thenReturn(Mono.just(LUKE)); - when(mockTeamServicePort.getTeamMates(LUKE.id)).thenReturn(Flux.just(OBIWAN.id)); + when(mockTeamServicePort.getTeamMates(LUKE.id())).thenReturn(Flux.just(OBIWAN.id())); StepVerifier.create(tested.list(PageRequest.all())) .assertNext(actual -> { @@ -169,16 +169,16 @@ void should_list_news_with_teammates() { ArgumentCaptor userIdCaptor = ArgumentCaptor.forClass(String.class); verify(mockTeamServicePort, times(1)).getTeamMates(userIdCaptor.capture()); - Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id); + Assertions.assertThat(userIdCaptor.getValue()).isEqualTo(LUKE.id()); verify(mockNewsPersistence, times(1)).list(captor.capture()); Assertions.assertThat(captor.getValue().filter).isEqualTo( Criteria.or( // FEED_ID in the 2 FEEDS ids plus the ID of the connected user - Criteria.property(FEED_ID).in(JEDI.id, SITH.id, LUKE.id), + Criteria.property(FEED_ID).in(JEDI.id(), SITH.id(), LUKE.id()), Criteria.property(NEWS_ID).in(MAY_THE_FORCE.id()) ) ); - Assertions.assertThat(captor.getValue().teamMates).containsOnly(LUKE.id, OBIWAN.id); + Assertions.assertThat(captor.getValue().teamMates).containsOnly(LUKE.id(), OBIWAN.id()); } @Test diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImplTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImplTest.java index 565c26c2..86ffa176 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImplTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/domain/SystemMaintenanceServiceImplTest.java @@ -84,7 +84,7 @@ void should_list_feed_for_admin() { { StepVerifier.create(tested.feedList()) - .expectNextMatches(r -> r.id.equals(FeedRecordSamples.JEDI.getFeedId())) + .expectNextMatches(r -> r.id().equals(FeedRecordSamples.JEDI.getFeedId())) .verifyComplete(); verify(mockFeedRepository, times(1)).list(captor.capture()); @@ -94,7 +94,7 @@ void should_list_feed_for_admin() { { clearInvocations(mockFeedRepository); StepVerifier.create(tested.feedList(PageRequest.one(Criteria.property("name").eq("jedi")))) - .expectNextMatches(r -> r.id.equals(FeedRecordSamples.JEDI.getFeedId())) + .expectNextMatches(r -> r.id().equals(FeedRecordSamples.JEDI.getFeedId())) .verifyComplete(); verify(mockFeedRepository, times(1)).list(captor.capture()); @@ -123,7 +123,7 @@ void should_delete_feed_for_admin() { @Test void should_list_news_for_authenticated_user() { Criteria filter = Criteria.or( - Criteria.property(FEED_ID).in(JEDI.id, SITH.id), + Criteria.property(FEED_ID).in(JEDI.id(), SITH.id()), Criteria.property(NEWS_ID).in(MAY_THE_FORCE.id()) ); StepVerifier.create(tested.newsList(PageRequest.all(filter))) diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedControllerTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedControllerTest.java index 08e31dc2..69401d71 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedControllerTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/FeedControllerTest.java @@ -59,8 +59,8 @@ void should_patch_feeds() throws JsonProcessingException { )); StepVerifier.create(tested.bulkUpdate(payload)) .expectNext( - URI.create("/feeds/" + FeedSamples.SITH.id), - URI.create("/feeds/" + FeedSamples.JEDI.id), + URI.create("/feeds/" + FeedSamples.SITH.id()), + URI.create("/feeds/" + FeedSamples.JEDI.id()), URI.create("/feeds/42")) .verifyComplete(); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsControllerTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsControllerTest.java index 1714dd60..ed7dc0d3 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsControllerTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/controllers/GraphQLFeedsControllerTest.java @@ -61,7 +61,7 @@ void setUp() { void should_call_get() throws JsonProcessingException { Map response = gqlClient.documentName("feedsServiceTest").operationName("GetFeed") - .variable("feedId", FeedSamples.JEDI.id) + .variable("feedId", FeedSamples.JEDI.id()) .execute().path("getFeed") .entity(new ParameterizedTypeReference>() { }).get(); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/persistence/FeedRepositoryTest.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/persistence/FeedRepositoryTest.java index 63ca4719..02fda813 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/persistence/FeedRepositoryTest.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/techwatch/infra/persistence/FeedRepositoryTest.java @@ -72,15 +72,15 @@ void setUp(DSLContext dslContext) { @Test void should_get_user_feed() { - FeedsRecord expected = FeedRecordSamples.SAMPLE.records().get(0); + FeedsRecord expected = FeedRecordSamples.SAMPLE.records().getFirst(); Entity actual = tested.get(QueryContext.id(expected.getFeedId())).block(); assertThat(actual).isNotNull(); assertAll( - () -> assertThat(actual.id).isEqualTo(expected.getFeedId()), - () -> assertThat(actual.self.location()).isEqualTo(URI.create(expected.getFeedUrl())), - () -> assertThat(actual.self.name()).isEqualTo(expected.getFeedName()), - () -> assertThat(actual.self.tags()).isEqualTo(Set.of()) + () -> assertThat(actual.id()).isEqualTo(expected.getFeedId()), + () -> assertThat(actual.self().location()).isEqualTo(URI.create(expected.getFeedUrl())), + () -> assertThat(actual.self().name()).isEqualTo(expected.getFeedName()), + () -> assertThat(actual.self().tags()).isEqualTo(Set.of()) ); } @@ -123,27 +123,27 @@ void should_persist_feeds_to_user(DSLContext dsl) { Entity expected = Entity.identify( FeedRecordSamples.JEDI.getFeedId(), Mappers.getMapper(BaywatchMapper.class).recordToFeed(FeedRecordSamples.JEDI) - .self.toBuilder() + .self().toBuilder() .name(FeedRecordSamples.JEDI.getFeedName() + " of Obiwan") .tags(Set.of("jedi", "saber")) .build()); - StepVerifier.create(tested.persistUserRelation(Collections.singleton(expected.self), OKENOBI.getUserId())) + StepVerifier.create(tested.persistUserRelation(Collections.singleton(expected.self()), OKENOBI.getUserId())) .assertNext(actual -> assertThat(actual).isEqualTo(expected)) .verifyComplete(); { - FeedsRecord actual = dsl.selectFrom(FEEDS).where(FEEDS.FEED_ID.eq(expected.id)).fetchOne(); + FeedsRecord actual = dsl.selectFrom(FEEDS).where(FEEDS.FEED_ID.eq(expected.id())).fetchOne(); assertThat(actual).isNotNull(); assertThat(actual.getFeedName()).isEqualTo(FeedRecordSamples.JEDI.getFeedName()); } { - FeedsUsersRecord actual = dsl.selectFrom(FEEDS_USERS).where(FEEDS_USERS.FEUS_FEED_ID.eq(expected.id)) + FeedsUsersRecord actual = dsl.selectFrom(FEEDS_USERS).where(FEEDS_USERS.FEUS_FEED_ID.eq(expected.id())) .fetchOne(); assertThat(actual).isNotNull(); assertThat(actual.getFeusUserId()).isEqualTo(OKENOBI.getUserId()); - assertThat(actual.getFeusTags()).isEqualTo(String.join(",", expected.self.tags())); + assertThat(actual.getFeusTags()).isEqualTo(String.join(",", expected.self().tags())); } } @@ -158,7 +158,7 @@ void should_update_feed(DSLContext dsl) { .name("Obiwan Kenobi") .tags(Set.of("jedi", "light")) .build()); - Mono> update = tested.update(expected.id, OKENOBI.getUserId(), expected.self); + Mono> update = tested.update(expected.id(), OKENOBI.getUserId(), expected.self()); StepVerifier.create(update) .expectNext(expected) .verifyComplete(); @@ -212,13 +212,13 @@ void should_delete_feeds_for_user(DSLContext dsl) { { int countUser = dsl.fetchCount(FEEDS_USERS, FEEDS_USERS.FEUS_FEED_ID.in(ids) - .and(FEEDS_USERS.FEUS_USER_ID.eq(OBIWAN.id))); + .and(FEEDS_USERS.FEUS_USER_ID.eq(OBIWAN.id()))); assertThat(countUser).isEqualTo(2); } tested.delete(QueryContext.builder() .filter(Criteria.property(FEED_ID).in(ids)) - .userId(OBIWAN.id) + .userId(OBIWAN.id()) .build()).block(); { @@ -232,7 +232,7 @@ void should_delete_feeds_for_user(DSLContext dsl) { @Test void should_list_orphan_feed() { List> actuals = tested.list(QueryContext.all(Criteria.property(COUNT).eq(0))).collectList().block(); - assertThat(actuals).extracting(e -> e.id).containsExactly( - FeedRecordSamples.FEEDS_RECORDS.get(FeedRecordSamples.FEEDS_RECORDS.size() - 1).getFeedId()); + assertThat(actuals).extracting(Entity::id).containsExactly( + FeedRecordSamples.FEEDS_RECORDS.getLast().getFeedId()); } } \ No newline at end of file diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/NewsSamples.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/NewsSamples.java index f7a999ba..dd7cd150 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/NewsSamples.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/NewsSamples.java @@ -43,7 +43,7 @@ public final class NewsSamples { .publication(Instant.parse("2022-04-01T22:00:42Z")) .build()) .state(State.of(Flags.READ)) - .feeds(Set.of(FeedSamples.JEDI.id)) + .feeds(Set.of(FeedSamples.JEDI.id())) .build(); public static final List SAMPLES = List.of(MAY_THE_FORCE, ORDER_66); diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRecordSamples.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRecordSamples.java index cb1dd89d..7f9411ea 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRecordSamples.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRecordSamples.java @@ -13,23 +13,23 @@ public class UsersRecordSamples implements RelationalDataSet { public static final UsersRecordSamples SAMPLE = new UsersRecordSamples(); public static final UsersRecord OKENOBI = Users.USERS.newRecord() - .setUserId(UserSamples.OBIWAN.id) - .setUserCreatedAt(UserSamples.OBIWAN.createdAt.atOffset(ZoneOffset.UTC).toLocalDateTime()) - .setUserLogin(UserSamples.OBIWAN.self.login) - .setUserName(UserSamples.OBIWAN.self.name) - .setUserPassword(UserSamples.OBIWAN.self.password) - .setUserEmail(UserSamples.OBIWAN.self.mail); + .setUserId(UserSamples.OBIWAN.id()) + .setUserCreatedAt(UserSamples.OBIWAN.createdAt().atOffset(ZoneOffset.UTC).toLocalDateTime()) + .setUserLogin(UserSamples.OBIWAN.self().login) + .setUserName(UserSamples.OBIWAN.self().name) + .setUserPassword(UserSamples.OBIWAN.self().password) + .setUserEmail(UserSamples.OBIWAN.self().mail); public static final UsersRecord LSKYWALKER = Users.USERS.newRecord() - .setUserId(UserSamples.LUKE.id) - .setUserCreatedAt(UserSamples.LUKE.createdAt.atOffset(ZoneOffset.UTC).toLocalDateTime()) - .setUserLogin(UserSamples.LUKE.self.login) - .setUserName(UserSamples.LUKE.self.name) - .setUserPassword(UserSamples.LUKE.self.password) - .setUserEmail(UserSamples.LUKE.self.mail); + .setUserId(UserSamples.LUKE.id()) + .setUserCreatedAt(UserSamples.LUKE.createdAt().atOffset(ZoneOffset.UTC).toLocalDateTime()) + .setUserLogin(UserSamples.LUKE.self().login) + .setUserName(UserSamples.LUKE.self().name) + .setUserPassword(UserSamples.LUKE.self().password) + .setUserEmail(UserSamples.LUKE.self().mail); public static final UsersRecord DSIDIOUS = Users.USERS.newRecord() - .setUserId(UserSamples.DSIDIOUS.id) + .setUserId(UserSamples.DSIDIOUS.id()) .setUserCreatedAt(LocalDateTime.parse("2023-01-10T22:59:42")) .setUserLogin("dsidious") .setUserName("Dark Sidious") diff --git a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRolesSamples.java b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRolesSamples.java index d4d513b3..88a37bb4 100644 --- a/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRolesSamples.java +++ b/sandside/src/test/java/fr/ght1pc9kc/baywatch/tests/samples/infra/UsersRolesSamples.java @@ -15,15 +15,15 @@ public class UsersRolesSamples implements RelationalDataSet { @Override public List records() { List records = new ArrayList<>( - UserSamples.OBIWAN.self.roles.size() + UserSamples.LUKE.self.roles.size()); - records.addAll(UserSamples.OBIWAN.self.roles.stream() + UserSamples.OBIWAN.self().roles.size() + UserSamples.LUKE.self().roles.size()); + records.addAll(UserSamples.OBIWAN.self().roles.stream() .map(r -> USERS_ROLES.newRecord() - .setUsroUserId(UserSamples.OBIWAN.id) + .setUsroUserId(UserSamples.OBIWAN.id()) .setUsroRole(r.toString())) .toList()); - records.addAll(UserSamples.LUKE.self.roles.stream() + records.addAll(UserSamples.LUKE.self().roles.stream() .map(r -> USERS_ROLES.newRecord() - .setUsroUserId(UserSamples.LUKE.id) + .setUsroUserId(UserSamples.LUKE.id()) .setUsroRole(r.toString())) .toList()); return List.copyOf(records);