Commit 0526bdc6 authored by Julien SADAOUI's avatar Julien SADAOUI
Browse files

feat: add spring-reactor tp

parent f76e9389
version = "1.0.0"
group = "com.ippon.codingdojo"
\ No newline at end of file
plugins {
id 'java'
}
apply from: 'artifact.gradle'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation "io.reactivex.rxjava2:rxjava:2.2.1"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.1'
}
test {
useJUnitPlatform()
}
\ No newline at end of file
# spring-reactor
This is a sample demonstrating Spring 5 Webflux framework. It uses Spring Data Mongo’s support for reactive libraries to provide an end to end reactive flow.
Enoncé : Spring 5 & Reactor
===========================
L'application que nous développons sert à gérer des listes de comptes
- Il y a plusieurs utilisateurs
- Chaque utilisateur peut avoir plusieurs comptes
- Ces comptes peuvent être partagées entre plusieurs utilisateurs
- Chaque compte contient plusieurs transactions
L'application est déjà en partie codée:
Depuis le début, nous avons fait uniquement des traitements avec des appels synchrones. En mode Servlet, un thread
est monopolisé pendant tout le traitement d'une requête HTTP qu'il soit en traitement ou en attente d'entrées/sorties
(accès en base de données, lecture de fichier, appel réseau, etc.)
Maintenant, nous allons utiliser les technologies Spring WebFlux et Reactor pour ajouter et afficher des Todos contenus
dans ces listes avec des traitements aynchrones.
I. Configuration de la sécurité HTTP
------------------------------------
1. Dans la classe "SecurityConfiguration", activez la sécurité pour les applications réactives dans Spring
2. Toujours dans la classe "SecurityConfiguration", ajoutez la gestion des annotations de sécurité
3. Afin de récupérer les informations de l'utilisateur, ajoutez un Bean UserDetailsService.
- Utilisez l'implémentation MongoReactiveUserDetailsService permettant de récupérer l'utilisateur dans la base MongoDB
Vous devez maintenant être capables de vous authentifier dans l'application en mode réactif avec l'un des utilisateurs
créés par le Bean InitialSetupMigration (par exemple: philip@ippon.fr / Pa$$word1)
Partie II : Développement de la liste des comptes
-------------------------------------------------
Nous allons coder les couches Controller et Service permettant d'ajouter, supprimer et lister la liste des Comptes
pour l'utilisateur en cours.
1. Implémentez la méthode "getCurrentUser" de la classe "UserServiceImpl" pour retourner l'utilisateur en cours:
- La classe helper ReactiveSecurityContextHolder fournit le nom de l'utilisateur connecté
2. Implémentez les méthodes de la classe "AccountServiceImpl"
- Ajoutez un nouveau Compte et partagez-la à un utilisateur
- Ajoutez une nouvelle Transaction à un Compte.
- Récupérez la liste des Transactions associées à un Compte
3. Complétez les méthodes de la couche Controller
Partie III : Création d'un test d'intégration
---------------------------------------------
Nous allons maintenant réaliser les tests d'intégration sur le controllers AccountController et TransactionController.
On exploite l'utilitaire WebTestClient pour tester le contrôleur ; l'API permet d'effectuer des traitements en mode asynchrone.
Elle offre en outre toute une panoplie d'outils permettant de vérifier les réponses obtenues.
- Configurez l'utilitaire WebTestClient
- Utilisez WebTestClient pour créer un nouveau Transaction
- Utilisez WebTestClient pour récupérer la liste des Transaction et vérifiez le flux de données avec la classe StepVerifier
\ No newline at end of file
repositories {
mavenCentral()
}
plugins {
id("java")
id("org.springframework.boot") version "2.1.1.RELEASE"
id("idea")
}
apply(plugin = "io.spring.dependency-management")
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
group = "fr.ippon.codingdojo"
version = "1.0.0"
defaultTasks("bootRun")
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-data-mongodb-reactive")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("com.github.mongobee:mongobee:0.13")
runtimeOnly("de.flapdoodle.embed:de.flapdoodle.embed.mongo")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "junit")
}
testImplementation("org.springframework.security:spring-security-test")
testImplementation("io.projectreactor:reactor-test")
}
tasks.withType<Test> {
useJUnitPlatform()
maxHeapSize = "1G"
testLogging.showStandardStreams = true
}
......@@ -28,7 +28,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
......
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
lombok.anyConstructor.addConstructorProperties=true
\ No newline at end of file
rootProject.name = "spring-reactor_solution"
package fr.ippon.codingdojo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
}
package fr.ippon.codingdojo.config;
import com.github.mongobee.Mongobee;
import com.mongodb.MongoClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
@Configuration
@Slf4j
public class DatabaseConfiguration {
@Bean
public Mongobee mongobee(MongoClient mongoClient, MongoTemplate mongoTemplate, MongoProperties mongoProperties) {
log.debug("Configuring Mongobee");
Mongobee mongobee = new Mongobee(mongoClient);
mongobee.setDbName(mongoProperties.getDatabase());
mongobee.setMongoTemplate(mongoTemplate);
// package to scan for migrations
mongobee.setChangeLogsScanPackage("fr.ippon.codingdojo.config.dbmigrations");
mongobee.setEnabled(true);
return mongobee;
}
}
package fr.ippon.codingdojo.config;
import fr.ippon.codingdojo.security.MongoReactiveUserDetailsService;
import fr.ippon.codingdojo.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.SecurityWebFilterChain;
@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfiguration {
@Bean
public SecurityWebFilterChain security(ServerHttpSecurity http) {
return http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.httpBasic().and()
.build();
}
@Bean
public ReactiveUserDetailsService userDetailsRepository(UserService userService) {
return new MongoReactiveUserDetailsService(userService, User.withDefaultPasswordEncoder());
}
}
package fr.ippon.codingdojo.config.dbmigrations;
import com.github.mongobee.changeset.ChangeLog;
import com.github.mongobee.changeset.ChangeSet;
import fr.ippon.codingdojo.domain.User;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* Creates the initial database setup
*/
@ChangeLog(order = "001")
public class InitialSetupMigration {
@ChangeSet(order = "01", author = "jsadaoui-demo", id = "01-addCustomers")
public void addCustomers(MongoTemplate mongoTemplate) {
mongoTemplate.save(User.builder()
.email("customer@email.org")
.password("Pa$$word1")
.firstName("customer_first-name")
.lastName("customer_last-name")
.role("CUSTOMER")
.build());
mongoTemplate.save(User.builder()
.email("employee@email.org")
.password("Pa$$word1")
.firstName("employee_first-name")
.lastName("employee_last-name")
.role("USER")
.role("EMPLOYEE")
.build());
}
}
package fr.ippon.codingdojo.domain;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
@Document
@Builder
@Data
@EqualsAndHashCode(exclude = "number")
@CompoundIndex(name = "account_ref_to_customer", def = "{'customerId' : 1}")
public class Account {
@Id
private String number;
@NotNull
private BigDecimal balance;
@Size(min = 1, max = 255)
private String description;
@Builder.Default
private Set<Transaction> transactions = new HashSet<>();
@NotEmpty
private String customerId;
}
package fr.ippon.codingdojo.domain;
import java.math.BigDecimal;
import java.util.function.BiFunction;
public enum Operation {
DEBIT((balance, amount) -> balance.subtract(amount)),
CREDIT((balance, amount) -> balance.add(amount));
private final BiFunction<BigDecimal, BigDecimal, BigDecimal> compute;
Operation(BiFunction<BigDecimal, BigDecimal, BigDecimal> compute) {
this.compute = compute;
}
public BigDecimal compute(BigDecimal balance, BigDecimal amount) {
return compute.apply(balance, amount);
}
}
package fr.ippon.codingdojo.domain;
import lombok.Builder;
import lombok.Value;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
@Builder
@Value
public class Transaction {
@NotNull
private BigDecimal amount;
@NotNull
private Operation operation;
@NotNull
private LocalDate date;
}
package fr.ippon.codingdojo.domain;
import lombok.Builder;
import lombok.Singular;
import lombok.Value;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Set;
@Document
@Builder
@Value
public class User {
@Id
@Email
private String email;
@Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")
private String password;
@Size(min = 1, max = 255)
private String firstName;
@Size(min = 1, max = 255)
private String lastName;
@Singular
@NotEmpty
private Set<String> roles;
}
package fr.ippon.codingdojo.repository;
import fr.ippon.codingdojo.domain.Account;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import reactor.core.publisher.Flux;
public interface AccountRepository extends ReactiveMongoRepository<Account, String> {
Flux<Account> findByCustomerId(String customerId);
}
package fr.ippon.codingdojo.repository;
import fr.ippon.codingdojo.domain.User;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface UserRepository extends ReactiveMongoRepository<User, String> {
}
package fr.ippon.codingdojo.security;
import fr.ippon.codingdojo.service.UserService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import reactor.core.publisher.Mono;
public class MongoReactiveUserDetailsService implements ReactiveUserDetailsService {
private final UserService userService;
private final User.UserBuilder userBuilder;