Spring webflux non-blocking response - java

I have a request method that use 'username' and 'password' body parameters to find real user from database, validate it by using request password and if everything is fine - return generated token as String.
public Mono<ServerResponse> handleLogin(ServerRequest request) {
User body = request.bodyToMono(User.class).block();
return userRepository.findById(body.getUsername())
.filter(user -> passwordEncoder.matches(body.getPassword(), user.getPassword()))
.flatMap(user -> ServerResponse.ok().body(Mono.just(tokens.store(user)), String.class))
.switchIfEmpty(ServerResponse.badRequest().build());
}
This method works fine, but i'm trying to make it as non-blocking and i'm not sure how to achieve it. Any help appreciated.
Updated
For now i changed my method content to
return request.bodyToMono(User.class)
.flatMap(body -> userRepository.findById(body.getUsername()).flatMap(user -> Mono.just(new Object[]{body.getPassword(), user})))
.filter(obj -> {
User user = (User) obj[1];
return user.isActive() && passwordEncoder.matches((CharSequence) obj[0], user.getPassword());
})
.flatMap(obj -> {
User user = (User) obj[1];
return ServerResponse.ok().body(Mono.just(tokens.store(user)), String.class);
})
.switchIfEmpty(ServerResponse.badRequest().build());
This is non-blocking, but looks like not so elegant solution. Can it be improved/simplified somehow?

Remember
1) Everything is stream.
2) Keep your flow composed
3) No blocking operation at all.
Solution
So, keep your flow composed without blocking operation
public Mono<ServerResponse> handleLogin(ServerRequest request) {
return request.bodyToMono(User.class)
.flatMap(body -> userRepository.findById(body.getUsername())
.filter(user -> passwordEncoder.matches(body.getPassword(), user.getPassword()))
.flatMap(user -> ServerResponse.ok().body(Mono.just(tokens.store(user)), String.class))
.switchIfEmpty(ServerResponse.badRequest().build());
}
Regarding the last update
Regarding the last update, from my point of view, the code might be optimized in a next way:
return request.bodyToMono(User.class)
.flatMap(body -> userRepository.findById(body.getUsername())
.filter(user -> user.isActive())
.filter(user -> passwordEncoder.matches(body.getPassword(), user.getPassword()))
)
.flatMap(user -> ServerResponse.ok().syncBody(tokens.store(user)))
.switchIfEmpty(ServerResponse.badRequest().build());

Related

Mockito Test for Elastic Java api client

I have tried to mock the response for the below method, but it's not working. Not able to mock the search.hits().hits() method.
Any idea how to do that?
SearchResponse<Product> search = client.search(s -> s
.index("products")
.query(q -> q
.term(t -> t
.field("name")
.value(v -> v.stringValue("bicycle"))
)),
Product.class);
for (Hit<Product> hit: search.hits().hits()) {
processProduct(hit.source());
}
Reference for code- https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html#_your_first_request

Reactive - Improve Mono syntax

I have this block of code that works fine:
return isBlacklistedToken(refreshToken, Boolean.TRUE).flatMap(isBlacklisted -> {
if (isBlacklisted)
return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
else
return isBlacklistedToken(accessToken, Boolean.FALSE).flatMap(isABlacklisted -> {
if (isABlacklisted)
return Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username)));
else
return blacklistTokens(username, refreshToken, accessToken);
});
});
To summarize it:
calls the isBlacklistedToken function (returns a Mono<Boolean> with the result of the refresh token)
If the refresh token is blacklisted, throws an UnauthorizedException
If the refresh token is not blacklisted, does the same process for the access token
If both tokens are not blacklisted, finally blacklists them.
This syntax, while it works, seems a bit sloppy. Is there a way to improve that? I wrote this piece of code, and while it throws an exception, the last part (blacklisting the tokens) always executes - peraphs my knowledge of reactive programming is a bit off.
return isBlacklistedToken(refreshToken, Boolean.TRUE)
.flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
.then(isBlacklistedToken(accessToken, Boolean.FALSE))
.flatMap(isBlacklisted -> isBlacklisted ? Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))) : Mono.empty())
.then(blacklistTokens(username, refreshToken, accessToken));
Edit: adding the isBlacklistedToken method
private Mono<Boolean> isBlacklistedToken(final String token, final Boolean type) {
return blacklistService.isBlacklisted(token, type);
}
and the respective blacklistService call (just a repository call, really simple)
public Mono<Boolean> isBlacklisted(final String token, final Boolean isRefresh) {
return Mono.just(this.blacklistRepository.existsBlacklistByTokenAndIsRefresh(token, isRefresh));
}
I would suggest the following:
return isBlacklistedToken(refreshToken, Boolean.TRUE)
.filter(isBlacklisted -> !isBlacklisted)
.flatMap(isBlacklisted -> isBlacklistedToken(accessToken, Boolean.FALSE))
.filter(isBlacklisted -> !isBlacklisted)
.flatMap(isBlacklisted -> blacklistTokens(username, refreshToken, accessToken))
.switchIfEmpty(Mono.error(new UnauthorizedException(format("The user %s has already logged out.", username))));
Sorry if there is some compile error but I tried this in Kotlin and needed to translate it to Java, which is become less and less easy.

Inner list from DTO is null while testing with Spring WebFlux

I have the following unit test (JUnit 5):
FluxExchangeResult<CalendarDTO> calendarEntityResult = client.get()
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.returnResult(CalendarDTO.class);
assertNotNull(calendarEntityResult);
final Flux<CalendarDTO> responseBody = calendarEntityResult.getResponseBody();
responseBody.flatMap(calendarDTO -> {
assertNotNull(calendarDTO);
final List<AppointmentDTO> calendarEvents = calendarDTO.getCalendarEvents();
assertNotNull(calendarEvents);
assertFalse(calendarEvents.isEmpty());
return Flux.just(calendarEvents);
}).map(calendarEvents ->
calendarEvents.get(0)
).doOnNext(appointmentDTO ->
assertEquals(appointmentDTO, validAppointmentDTO())
).subscribe();
/*StepVerifier.create(responseBody)
.assertNext(calendarDTO -> {
assertNotNull(calendarDTO);
final List<AppointmentDTO> calendarEvents = calendarDTO.getCalendarEvents();
assertNotNull(calendarEvents);
assertFalse(calendarEvents.isEmpty());
final AppointmentDTO appointmentDTO = calendarEvents.get(0);
assertNotNull(appointmentDTO);
assertEquals(validAppointmentDTO(), appointmentDTO);
})
.expectComplete()
.verify();*/
For some reason, the assertNotNull(calendarEvents); is failing. The method itself when running it with Postman is fine. What has me puzzled is that on debug time, the calendarEntityResult has calendarEvents!
> GET /appointments
> WebTestClient-Request-Id: [1]
No content
< 200 OK OK
< Content-Type: [application/json;charset=UTF-8]
< Content-Length: [377]
{"data":{"calendarEvents":[{"id":null,"startTime":"2020-01-16T13:19:37.510-06:00","endTime":"2020-01-16T14:19:37.511-06:00","timeZoneStart":"America/Regina","timeZoneEnd":"America/Regina","summary":"unit test summary","description":"unit test description","organizerName":"Developer","organizerEmail":"developer#dev.com","status":null,"alarm":15}]},"notifications":null}
The commented code gives the same result. To be clear, the DTO itself is not null; the problem is the calendarEvents array. It's possible I'm doing something wrong since I'm new to reactive programming in general, so code improvements are most welcome. Am I extracting the data in a wrong manner?
You should be using the stepverifier when asserting any type of flux. Will make your life easier.
final Flux<String> responseBody = testClient.get()
.exchange()
.expectStatus()
.isOk()
.returnResult(String.class)
.getResponseBody();
StepVerifier.create(responseBody)
.assertNext(s -> assertEquals(s, "Foo"))
.assertNext(s -> assertEquals(s, "Bar"));
Turns out the root DTO was already wrapped into yet another DTO. It probably caused getResponseBody() to misinterpret the contents of the list and defaulted those to null. Leaving response here for the curious:
final Flux<AppointmentCalendarResponse> responseBody = client.get()
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.returnResult(AppointmentCalendarResponse.class)
.getResponseBody();
StepVerifier.create(responseBody)
.assertNext(data -> {
CalendarDTO calendarDTO = data.getData();
final List<AppointmentDTO> calendarEvents = calendarDTO.getCalendarEvents();
assertNotNull(calendarEvents);
})
.expectComplete()
.verify();
You're using the same DB?
Because generaly the DB test and DB Dev is different.

How reuse flux mono value?

Consider a code:
WebClient webClient = ... ;
public Mono<MyWrapper> someFunction () {
Mono<MyDto> mono = webClient.get()
.uri("myUrl")
.retrieve()
.bodyToMono(MyDto.class);
Mono<FirstDto> first = mono.map(dto -> {...});
Mono<SecondDto> second = mono.map(dto -> {...}); //<- connection closed error here
return Mono.zip(first, second).map(zip -> {
return new MyWrapper(first, second);
});
}
Second map operation leads to connection closed error. I suppose that flux tried to send new request. (Does it or not?)
Second is there a way to map mono twice: to one type and another one without sending new request?
Have you tried using compose?
Mono<MyWrapper> mono = webClient.get()
.uri("myUrl")
.retrieve()
.bodyToMono(MyDto.class)
.compose(dto -> dto
.zip(dto.map(dto -> {...}), dto.map(dto -> {...})))
.map(MyWrapper::new);
API:
https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#compose-java.util.function.Function-

Rxjava approach the get last Observable from each thread

I'm thinking how to use RXJava for the scenario described bellow.
A List<Object>,each object will be sent to k8s and checked the status till the respone return true,so my polling active is that:
private Observable<Boolean> startPolling(String content) {
log.info("start polling "+ content);
return Observable.interval(2, TimeUnit.SECONDS)
.take(3)
.observeOn(Schedulers.newThread())
.flatMap(aLong -> Observable.just(new CheckSvcStatus().check(content)))
.takeUntil(checkResult -> checkResult)
.timeout(3000L, TimeUnit.MILLISECONDS, Observable.just(false))
;
}
Function of sent action:
Observable<Compo> sentYamlAndGet() {
log.info("sent yaml");
sentYaml()
return Observable.just(content);
}
I try to use the foreach to get each object status which like this:
public void rxInstall() throws JsonProcessingException {
List<Boolean>observables = Lists.newArrayList();
Observable.from(list)
.subscribeOn(Schedulers.newThread())
.concatMap(s -> sendYamlAndGet())
.timeout(3000l, TimeUnit.MILLISECONDS)
.subscribe()
;
Observable.from(list).forEach(s -> {
observables.add(Observable.just(s)
.flatMap(this::startPolling)
.toBlocking()
.last()
)
;
System.out.println(new ObjectMapper().writeValueAsString(observables));
}
Objects of outputs list is :{"o1","o2","o3","o4","o5"}
the last status of objest which I want is : [false,true,false,false,true].
All above style is not much 'ReactX',check object status action do not affect to each other.
How to throw foreach? I trid toIterable(),toList() but failed.
Observable.from(list)
.concatMap(s -> sentYamlAndGet())
.concatMap(this::startPolling)
....
;
Wanted to know if it's good practice to do that and what would be the best way to do that?
Thanks in advance.
pps: currentlly I'm using rxjava1 <version>1.2.0</version> but can change to 2(´▽`)ノ

Categories

Resources