Skip to content

Commit

Permalink
chore(sandside): #194 refactor Entity into record
Browse files Browse the repository at this point in the history
refs #194
  • Loading branch information
Marthym committed Jan 7, 2024
1 parent bb3ae5e commit 8f66bf7
Show file tree
Hide file tree
Showing 53 changed files with 329 additions and 325 deletions.
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
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;

/**
* Hold the standard Persistence information
*
* @param <T> The type of the persisted object
* @param self The Persisted Entity
* @param <T> The type of the persisted object
*/
@Builder
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor
public final class Entity<T> {
public record Entity<T>(
@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
Expand All @@ -43,7 +37,7 @@ public final class Entity<T> {
* @return An identified Object with ID
*/
public static <T> Entity<T> identify(String id, Instant createdAt, T entity) {
return new Entity<>(id, NO_ONE, createdAt, entity);
return new Entity<T>(id, NO_ONE, createdAt, entity);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class IndexableDataAdapter implements IndexableDataPort {
@Override
public Flux<IndexableFeed> listFeed() {
return systemMaintenanceService.feedList()
.map(f -> mapper.getIndexableFromFeed(f.self));
.map(f -> mapper.getIndexableFromFeed(f.self()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,21 @@ public Flux<ServerEvent> 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<ServerEvent> sink = Sinks.many().multicast().onBackpressureBuffer();
AtomicReference<Subscription> subscription = new AtomicReference<>();
Flux<ServerEvent> multicastFlux = this.multicast.asFlux()
.doOnSubscribe(subscription::set);
log.atDebug().addArgument(u.id)
log.atDebug().addArgument(u.id())
.log("Subscribe notification for {}");
Flux<ServerEvent> 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);
Expand All @@ -92,10 +92,10 @@ public Flux<ServerEvent> subscribe() {
@Override
public Mono<Boolean> 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;
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public Mono<ResponseEntity<Object>> disposeSse() {
@PreAuthorize("hasRole('ADMIN')")
public Mono<Void> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class NotificationPersistenceAdapter implements NotificationPersistencePo

@Override
public Mono<ServerEvent> persist(Entity<ServerEvent> event) {
Mono<NotificationsRecord> notificationsRecord = event.self.accept(new ServerEventVisitor<>() {
Mono<NotificationsRecord> notificationsRecord = event.self().accept(new ServerEventVisitor<>() {
@Override
public <T> Mono<NotificationsRecord> visit(BasicEvent<T> event) {
return Mono.just(NOTIFICATIONS.newRecord()
Expand All @@ -50,14 +50,14 @@ public <T> Mono<NotificationsRecord> visit(ReactiveEvent<T> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,19 @@ public Mono<Void> opmlImport(Flux<DataBuffer> 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<Void> writeOpml(OutputStream out, Entity<User> 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<WebFeed> feed = signal.get();
if (feed != null) {
opmlWriter.writeOutline(feed.self);
opmlWriter.writeOutline(feed.self());
}
})
.doOnComplete(opmlWriter::endOmplDocument)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ public Mono<Void> 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();
Expand All @@ -84,23 +84,23 @@ public Mono<Void> scrapSingleNews(URI uri) {
@Override
public Mono<News> 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()
.id(Hasher.identify(link))
.link(link)
.publication(clock.instant())
.build())
.feeds(Set.of(u.id))
.feeds(Set.of(u.id()))
.state(State.NONE)
.build());
}

@Override
public Mono<Try<News>> applyNewsFilters(News news) {
Mono<RawNews> 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()));

Expand All @@ -118,14 +118,14 @@ public Mono<Try<News>> applyNewsFilters(News news) {

private Mono<Boolean> 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);
Expand All @@ -134,7 +134,7 @@ private Mono<Boolean> notAlreadyExists(News news) {
@Override
public Mono<News> 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 ->
Expand All @@ -150,7 +150,7 @@ public Mono<News> saveAndShare(News news) {
@Override
public Mono<AtomFeed> applyFeedsFilters(AtomFeed feed) {
Mono<AtomFeed> 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));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ public Mono<Void> 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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -55,7 +56,7 @@ private Flux<String> keepStaredNewsIds(Collection<String> 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<String> toBeDeleted = new ArrayList<>(newsIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public Flux<String> listAllNewsId() {
@Override
public Flux<ScrapedFeed> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class AuthenticationServiceImpl implements AuthenticationService {
@Override
public Mono<BaywatchAuthentication> 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())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,22 @@ public JwtBaywatchAuthenticationProviderImpl(byte[] secretKey, Duration validity
@Override
public BaywatchAuthentication createToken(Entity<User> user, boolean remember, Collection<String> authorities) {
List<String> 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 {
JWSSigner signer = new MACSigner(secretKey);

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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public Mono<PasswordEvaluation> 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))
);
}

Expand Down
Loading

0 comments on commit 8f66bf7

Please sign in to comment.