Commit 2c29b3f9 authored by Ravinder Pannala's avatar Ravinder Pannala

My First Commit

parent 959fcf5b
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.reactor</groupId>
<artifactId>Project-Reactor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Project-Reactor</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>-->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.example.reactor.ProjectReactor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProjectReactorApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectReactorApplication.class, args);
}
}
/*
package com.example.reactor.ProjectReactor.config;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories(basePackages = "com.example.reactor.ProjectReactor.repository")
public class MongoDBConfig extends AbstractReactiveMongoConfiguration {
@Value("{mongodb.database.name}")
private String databaseName;
@Value("{mongodb.database.host}")
private String databaseHost;
@Override
protected String getDatabaseName() {
return databaseName;
}
@Override
public MongoClient reactiveMongoClient() {
String name = databaseHost;
return MongoClients.create(name);
}
@Bean
public ReactiveMongoTemplate reactiveMongoTemplate(){
return new ReactiveMongoTemplate(reactiveMongoClient(),getDatabaseName());
}
}
*/
package com.example.reactor.ProjectReactor.controller;
import com.example.reactor.ProjectReactor.entity.Contact;
import com.example.reactor.ProjectReactor.repository.ContactRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/contact")
@RequiredArgsConstructor
public class ContactController {
@Autowired
private ContactRepository contactRepository;
@PostMapping(value = "/save")
private Mono<ResponseEntity<Contact>> saveContact(@RequestBody Contact contact) {
Mono<ResponseEntity<Contact>> responseEntityMono = contactRepository.insert(contact)
.map(c1 -> new ResponseEntity<>(c1, HttpStatus.ACCEPTED))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE));
return responseEntityMono;
}
@GetMapping(value = "/all")
private Flux<Contact> getAllContact() {
Flux<Contact> all = contactRepository.findAll();
return all;
}
@GetMapping(value = "/get/{id}")
private Mono<ResponseEntity<Contact>> getContactById(@PathVariable String id) {
return contactRepository.findById(id)
.map(c -> new ResponseEntity<>(c, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@DeleteMapping(value = "/delete/{id}")
private Mono<Void> deleteById(@PathVariable String id) {
return contactRepository.deleteById(id);
}
@GetMapping(value = "/get/email")
private Mono<ResponseEntity<Contact>> findByEmail(@RequestParam("email") String email) {
return contactRepository.findFirstByEmail(email)
.map(c -> new ResponseEntity<>(c, HttpStatus.FOUND))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PutMapping(value = "/update/{id}")
private Mono<ResponseEntity<Contact>> updateContact(@RequestBody Contact contact, @PathVariable String id) {
return contactRepository.findById(id).flatMap(c -> {
contact.setId(id);
return contactRepository.save(contact)
.map(c1 -> new ResponseEntity<>(c1, HttpStatus.OK))
.defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
});
}
}
package com.example.reactor.ProjectReactor.entity;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Contact {
@Id
private String id;
private String name;
private String email;
private String phone;
}
package com.example.reactor.ProjectReactor.repository;
import com.example.reactor.ProjectReactor.entity.Contact;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;
@Repository
public interface ContactRepository extends ReactiveMongoRepository<Contact,String> {
Mono<Contact> findFirstByEmail(String email);
//Mono<Contact> findAllByPhoneOrName(String phoneOrName);
}
server.port=8090
#mongodb.database.name=Contact
#mongodb.database.host=mongodb://localhost:27017/
spring.data.mongodb.uri=mongodb://localhost:27017/Contact
package com.example.reactor.ProjectReactor;
import com.example.reactor.ProjectReactor.entity.Contact;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@AutoConfigureWebTestClient
@ActiveProfiles("unit_test")
public class ContactControllerTest {
@Autowired
private WebTestClient webTestClient;
Contact contact;
@Test
@Order(1)
public void createContact() {
Flux<Contact> saveFlux = webTestClient
.post()
.uri("/api/contact/save")
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Contact("1", "Ravi", "Ravi@gmail.com", "352323")))
.exchange()
.expectStatus().isAccepted()
.returnResult(Contact.class).getResponseBody().log();
saveFlux.next().subscribe(c -> {
this.contact = c;
});
Assertions.assertNotNull(contact);
}
@Test
@Order(2)
public void getByEmail() {
Flux<Contact> getByEmail = webTestClient.get().uri("/api/contact/get/email?email={email}", "Ravi@gmail.com")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isFound().
returnResult(Contact.class).getResponseBody().log();
StepVerifier.create(getByEmail).expectSubscription().expectNextMatches(c -> c.getPhone().equals("45475434")).verifyComplete();
}
/* @Test
@Order(3)
public void updateContact() {
Flux<Contact> updateFlux = webTestClient.put().uri("/api/contact/update/{id}", contact.getId()).accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Contact("WebTestClient", "wtc@email.com", "11111111").setId(contact.getId())))
.exchange()
.returnResult(Contact.class).getResponseBody().log();
StepVerifier.create(updateFlux).expectSubscription().expectNextMatches(c -> c.getEmail().equals("wtc@email.com")).verifyComplete();
}*/
}
package com.example.reactor.ProjectReactor;
import com.example.reactor.ProjectReactor.entity.Contact;
import com.example.reactor.ProjectReactor.repository.ContactRepository;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ContactReposityTest {
@Autowired
private ContactRepository contactRepository;
@Autowired
private ReactiveMongoOperations reactiveMongoOperations;
@BeforeAll
public void insertData() {
Contact c = new Contact();
c.setName("Raja");
c.setEmail("Raja@gmail.com");
c.setPhone("7546");
Contact c1 = new Contact();
c1.setName("Revan");
c1.setEmail("Revan@gmail.com");
c1.setPhone("12324");
Contact c2 = new Contact();
c2.setName("Arya");
c2.setEmail("Arya@gmail.com");
c2.setPhone("534646");
/* Contact c3 = new Contact();
c3.setName("Raja");
c3.setEmail("Raja@gmail.com");
c3.setPhone("7546");
Contact c4 = new Contact();
c4.setName("Raja");
c4.setEmail("Raja@gmail.com");
c4.setPhone("7546");*/
StepVerifier.create(contactRepository.insert(c).log()).expectSubscription().expectNextCount(1).verifyComplete();
StepVerifier.create(contactRepository.save(c1).log()).expectSubscription().expectNextCount(1).verifyComplete();
StepVerifier.create(contactRepository.save(c2).log()).expectSubscription().expectNextMatches(a -> a.getId() != null).verifyComplete();
}
@Test
@Order(1)
public void findAll() {
StepVerifier.create(contactRepository.findAll().log()).expectSubscription().expectNextCount(4).expectComplete();
}
@Test
@Order(2)
public void findByEmail() {
StepVerifier.create(contactRepository.findFirstByEmail("Arya@gmail.com").log()).expectSubscription().expectNextCount(1).verifyComplete();
}
@Test
@Order(3)
public void updateContact() {
Mono<Contact> firstByEmail = contactRepository.findFirstByEmail("Arya@gmail.com")
.map(c -> {
c.setPhone("11111");
return c;
}).flatMap(c1 -> contactRepository.save(c1));
StepVerifier.create(firstByEmail.log()).expectSubscription().expectNextMatches(c -> c.getPhone().equals("11111")).verifyComplete();
}
@Test
@Order(4)
public void deleteContact() {
Mono<Void> firstByEmail = contactRepository.findFirstByEmail("Arya@gmail.com").flatMap(c1 -> {
return contactRepository.deleteById(c1.getId());
}).log();
StepVerifier.create(firstByEmail).expectSubscription().verifyComplete();
}
}
package com.example.reactor.ProjectReactor;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import sun.reflect.annotation.ExceptionProxy;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
@SpringBootTest
public class ErrorSample {
Logger log = LoggerFactory.getLogger(ErrorSample.class);
@Test
public void onErrorReturnDirectly_Mono() {
Mono.
just(2).
map(i -> i / 0). //Arthimetic Exception
onErrorReturn(0).
subscribe(num -> System.out.println("Number after exception--->" + num));
}
/*
type – the error type to match
fallbackValue – the value to emit if an error occurs that matches the type
*/
@Test
public void onErrorReturnExceptionTypeMatched_Mono() {
Mono.just(2)
.map(i -> i / 0)
.onErrorReturn(ArithmeticException.class, 0)
.subscribe(num -> System.out.println("ExceptionTypeMatched--->" + num));
}
/*
predicate – the error predicate to match
fallbackValue – the value to emit if an error occurs that matches the predicate
*/
@Test
public void onErrorReturnPredicateValueMatched_Mono() {
Mono.just(2)
.map(i -> i / 0)
.onErrorReturn(error -> error instanceof ArithmeticException, 0)
.subscribe(num -> System.out.println("Predicate Value matched--->" + num));
}
/*
Params: fallback – the function to choose the fallback to an alternative Mono
Returns: a Mono falling back upon source onError
*/
@Test
public void onErrorResumeDefault_Mono() {
//Function<Throwable, Mono<Integer>> function = error -> Mono.just(4);
Function<Throwable, Mono<Integer>> function = error -> Mono.error(new RuntimeException("Exceptions occurred"));
Mono.just(2)
.map(i -> i / 0)
.onErrorResume(function)
.subscribe(num -> System.out.println("Error Occured pass another function" + num));
}
/*
Params:type – the error type to match fallback – the function to choose the fallback to an alternative Mono
Returns:a Mono falling back upon source onError
*/
@Test
public void onErrorResumeExceptionTypeMatched_Mono() {
Function<Throwable, Mono<Integer>> function = error -> Mono.just(4);
Mono
.just(2)
.map(i -> i / 0)
.onErrorResume(ArithmeticException.class, function)
.subscribe(num -> System.out.println("Exception type matched--->" + num));
}
/*
Params:predicate – the error predicate to match fallback – the function to choose the fallback to an alternative Mono
Returns:a Mono falling back upon source onError
*/
@Test
public void onErrorResumePredicateMatched_Mono() {
Function<Throwable, Mono<Integer>> function = error -> Mono.just(4);
Mono.just(2)
.map(i -> i / 0)
.onErrorResume(error -> error instanceof ArithmeticException, function)
.subscribe(num -> System.out.println("Predicate Matched--->" + num));
}
/*
param errorConsumer a {@link BiConsumer} fed with errors matching the {@link Class} and the value that triggered the error.
return a {@link Mono} that attempts to continue processing on errors
*/
@Test
public void onErrorContinueDefault_Mono() {
BiConsumer<Throwable, Object> biConsumer = (e, i) -> {
System.out.println("Error-->" + e + "----> Value" + i);
};
Mono.just(2).map(i -> i / 0).onErrorContinue(biConsumer).subscribe(num -> System.out.println("onErrorContinue--->" + num));
}
/*
Params:type – the Class of Exception that are resumed from. errorConsumer – a BiConsumer fed with errors matching the Class and the value that triggered the error.
Returns:a Mono that attempts to continue processing on some errors.
*/
@Test
public void onErrorContinueExceptionClassMatched_Mono() {
BiConsumer<Throwable, Object> biConsumer = (e, i) -> {
System.out.println("Error-->" + e + "----> Value" + i);
};
Mono.just(2)
.map(i -> i / 0)
.onErrorContinue(ArithmeticException.class, biConsumer)
.subscribe(num -> System.out.println(num));
}
/*
Params:errorPredicate – a Predicate used to filter which errors should be resumed from. This MUST be idempotent, as it can be used several times. errorConsumer – a BiConsumer fed with errors matching the predicate and the value that triggered the error.
Returns:a Mono that attempts to continue processing on some errors.
*/
@Test
public void onErrorContinuePredicateMatched_Mono() {
BiConsumer<Throwable, Object> biConsumer = (e, i) -> {
System.out.println("Error-->" + e + " Value--->" + i);
};
Mono.just(2)
.map(i -> i / 0)
.onErrorContinue(error -> error instanceof ArithmeticException, biConsumer)
.subscribe(s -> System.out.println(s));
}
/*
param onError the error callback to call on {@link Subscriber#onError(Throwable)}
return a new {@link Mono}
*/
@Test
public void doOnError_Mono() {
Consumer<Throwable> consumer = (error) -> {
log.info("caught error");
};
Mono.just(2)
.map(i -> i / 0) // will produce ArithmeticException
.doOnError(consumer)
.onErrorResume(e -> Mono.empty())
.subscribe(num -> log.info("Number: {}", num));
}
/*
@param exceptionType the type of exceptions to handle
@param onError the error handler for relevant errors
@param <E> type of the error to handle
@return an observed {@link Mono}
*/
@Test
public void doOnErrorIfArithmeticException_Mono() {
Mono.just(2)
.map(i -> i / 0) // will produce ArithmeticException
.doOnError(
ArithmeticException.class,
error -> log.info("caught error")
).onErrorResume(e -> Mono.empty())
.subscribe(num -> log.info("Number: {}", num));
}
/*
Params:predicate – the matcher for exceptions to handle onError – the error handler for relevant error
Returns:an observed Mono
*/
@Test
public void doOnErrorIfPredicatePasses_Mono() {
Mono.just(2)
.map(i -> i / 0) // will produce ArithmeticException
.doOnError(
error -> error instanceof ArithmeticException,
System.err::println
).onErrorResume(e -> Mono.empty())
.subscribe(num -> log.info("Number: {}", num));
}
/*
Params:mapper – the error transforming Function
Returns:a Mono that transforms source errors to other errors
*/
@Test
public void onErrorMap_Mono() {
Mono.just(2)
.map(i -> i / 0)
.onErrorMap(e -> new RuntimeException("2 is not divisible by 0"))
.subscribe(n -> System.out.println("Number -->" + n));
}
/*
Params:type – the class of the exception type to react to mapper – the error transforming Function
Returns:a Mono that transforms some source errors to other erro
*/
@Test
public void onErrorMapExceptionMatched_Mono() {
Mono.just(2)
.map(i -> i / 0)
.onErrorMap(ArithmeticException.class, e -> new RuntimeException(" number is not divisible by 0"))
.subscribe(n -> System.out.println(n));
}
@Test
public void onErrorMapPredicateMatch_mono() {
Mono.just(2).map(i -> i / 0)
.onErrorMap(error -> error instanceof ArrayIndexOutOfBoundsException, e -> new Exception("Number is not divisible by 0"))
.subscribe(num -> System.out.println(num));
}
@Test
public void onErrorMapPredicateMatch_Flux(){
Flux.just(2,0,1).map(i->i/0)
.onErrorMap(ArithmeticException.class, e -> new RuntimeException(" number is not divisible by 0"))
.subscribe(n -> System.out.println("Num-->"+n));
}
}
package com.example.reactor.ProjectReactor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
public class FluxTest {
private static List<String> words = Arrays.asList(
"the",
"quick",
"brown",
"fox",
"jumped",
"over",
"the",
"lazy",
"dog"
);
@Test
public void concatenateFlux() {
Flux<Integer> evenFlux = Flux.range(1, 5).filter(x -> x % 2 == 0);
Flux<Integer> oddFlux = Flux.range(1, 6).filter(x -> x % 2 != 0);
Flux<Integer> concat = Flux.concat(evenFlux, oddFlux);
StepVerifier.create(concat.log())
.expectSubscription()
.expectNext(2)
.expectNext(4)
.expectNext(1)
.expectNext(3)
.expectNext(5)
.verifyComplete();
}
@Test
public void concatenateWithFlux() {
Flux<Integer> evenFlux = Flux.range(1, 5).filter(x -> x % 2 == 0);
Flux<Integer> oddFlux = Flux.range(1, 6).filter(x -> x % 2 != 0);
Flux<Integer> integerFlux = evenFlux.concatWith(oddFlux);
StepVerifier.create(integerFlux.log())
.expectSubscription()
.expectNext(2)
.expectNext(4)
.expectNext(1)
.expectNext(3)
.expectNext(5)
.verifyComplete();
}
@Test
public void combineLatest() {
Flux<Integer> evenFlux = Flux.range(1, 5).filter(x -> x % 2 == 0);
Flux<Integer> oddFlux = Flux.range(1, 6).filter(x -> x % 2 != 0);
Flux<Integer> combineLatestFlux = Flux.combineLatest(evenFlux, oddFlux, (a, b) -> a + b);
StepVerifier.create(combineLatestFlux.log())
.expectSubscription()
.expectNext(5)
.expectNext(7)
.expectNext(9)
.verifyComplete();
}
@Test
public void merge() {
Flux<Integer> evenFlux = Flux.range(1, 5).filter(x -> x % 2 == 0);
Flux<Integer> oddFlux = Flux.range(1, 6).filter(x -> x % 2 != 0);
Flux<Integer> combineLatestFlux = Flux.merge(evenFlux, oddFlux);
StepVerifier.create(combineLatestFlux.log())
.expectSubscription()
.expectNext(2)
.expectNext(4)
.expectNext(1)
.expectNext(3)
.expectNext(5)
.verifyComplete();
}
@Test
public void zip() {
Flux<Integer> evenFlux = Flux.range(1, 5).filter(x -> x % 2 == 0);
Flux<Integer> oddFlux = Flux.range(1, 6).filter(x -> x % 2 != 0);
//Flux<Integer> primeFlux = Flux.range(1, 5).filter(x -> x % 3 == 0);
Flux<Integer> zip = Flux.zip(evenFlux, oddFlux, (a, b) -> a + b);
StepVerifier.create(zip)
.expectSubscription()
.expectNext(3)
.expectNext(7)
.verifyComplete();
}
@Test
public void verifyNextAs2() {
final List<Integer> source = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Flux<Integer> flux = Flux.fromStream(source.stream());
StepVerifier.create(flux.log())
.expectNextSequence(source)
.expectComplete()
.verify();
}
@Test
public void sampleCreation(){
Flux<String> just = Flux.just("Ravi", "Rajesh");
Flux<String> stringFlux = Flux.fromIterable(words);
just.subscribe(System.out::println);
stringFlux.subscribe(System.out::println);
}
@Test
public void findingMissingLetters(){
Flux<String> sort = Flux.fromIterable(words)
.flatMap(word -> Flux.fromArray(word.split("")))
.distinct()
.sort()
.zipWith(Flux.range(1,Integer.MAX_VALUE),(string,count)->String.format("%2d,%s",count,string));
sort.subscribe(System.out::println);
}
@Test
public void fluxToList(){
Flux<String> just = Flux.just("Ravi", "Pannala", "Reddy");
List<String> wordsList = new ArrayList<>();
just.collectList().subscribe(wordsList::addAll);
wordsList.forEach(System.out::println);
just.collectMap(
item -> item.split(":")[0],
item -> item.split(":")[1]);
}
}
package com.example.reactor.ProjectReactor;
import com.example.reactor.ProjectReactor.entity.Contact;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.util.function.Tuple2;
import java.util.Random;
import java.util.stream.DoubleStream;
@SpringBootTest
public class MonoSample {
@Test
public void zip() {
Mono<String> mono = Mono.justOrEmpty("Ravi");
Mono<String> just = Mono.just("Pannala");
Mono<String> log = Mono.zip(mono, just, (a, b) -> a + "" + b).log();
StepVerifier.create(log).expectSubscription().expectNext("RaviPannala").expectComplete().verify();
}
public void block() {
String str = Mono.just("Ravi").block();
}
@Test
public void createMono() {
Mono<String> mono = Mono.just("Ravi");
mono.subscribe(a -> System.out.println("Mono with Just--->" + a));
Mono<Object> error = Mono.error(new Throwable());
error.subscribe(a -> System.out.println("Mono with Error--->" + a));
Mono<Object> empty = Mono.empty();
empty.subscribe(a -> System.out.println("Mono with empty--->" + a));
Mono<Integer> from = Mono.from(Flux.range(1, 10));
from.subscribe(s -> System.out.println("Mono with from --->" + s));
Random rd = new Random();
Mono<Double> doubleMono = Mono.fromSupplier(rd::nextDouble);
doubleMono.subscribe(s -> System.out.println("From Supplier-->" + s));
Mono<String> hello = Mono.fromCallable(() -> "Hello");
hello.subscribe(a -> System.out.println("From Callable --->" + a));
}
@Test
public void map() {
Mono<Contact> mono = Mono.just(new Contact("1", "Ravi", "Ravi@gmail.com", "3423523"));
Mono<String> stringMono = mono.map(c -> {
c.setName(null);
return c;
}).map(c -> c.getName()).onErrorReturn("Error Occured");
stringMono.subscribe(a -> System.out.println(a));
}
@Test
public void zipWith() {
Mono<String> ravinder = Mono.just("Ravinder");
Mono<Integer> just = Mono.just(1);
Mono<String> map = ravinder.zipWith(just).map(t -> {
return t.getT1() + t.getT2();
});
map.subscribe(s->System.out.println("zip With---->"+s));
}
@Test
public void filter(){
Mono<String> str1 = Mono.just("Ravi");
Mono<String> str2= Mono.just("Pannala");
Mono<String> map = str1.zipWith(str2).map(tule2 -> {
return tule2.getT2() + tule2.getT1();
});
Mono<String> stringMono = map.filter(str -> str.contains("Ravi")).switchIfEmpty(Mono.just("Error Occured"));
stringMono.subscribe(s->System.out.println("filter Mono--->"+s));
}
private <T> T identityWithThreadLogging(T el, String operation) {
System.out.println(operation + " -- " + el + " -- " +
Thread.currentThread().getName());
return el;
}
@Test
public void flatMapWithoutChangingScheduler() {
Flux.range(1,4)
.map(n->identityWithThreadLogging(n,"map1"))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(f->Mono.just(f).map(n->identityWithThreadLogging(n,"mono")))
.subscribe(n-> {
identityWithThreadLogging(n,"subscribe");
System.out.println(n);
});
}
@Test
public void combiningParallelAndSequentialFlux() {
Flux.range(1, 4).
subscribeOn(Schedulers.parallel()).
map(n -> identityWithThreadLogging(n, "map1"))
.parallel()
.runOn(Schedulers.boundedElastic())
.map(n -> identityWithThreadLogging(n, "parallelFlux"))
.sequential()
.map(n -> identityWithThreadLogging(n, "map2")).
subscribe(n -> identityWithThreadLogging(n, "subscribe"));
}
}
package com.example.reactor.ProjectReactor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.core.publisher.Flux;
@SpringBootTest
class ProjectReactorApplicationTests {
}
package com.example.reactor.ProjectReactor;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
public class ResourceHandlers {
private void close(Closeable closeable){
try {
closeable.close();
System.out.println("Closed the resource");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void write(BufferedWriter bw, String string){
try {
bw.write(string);
bw.newLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
package com.example.reactor.ProjectReactor;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
public class SampleSubscriber<I extends Number> extends BaseSubscriber<Integer> {
protected void hookOnSubscribe(Subscription subscription) {
System.out.println("Hook on Subscribe");
request(1);
}
protected void hookOnNext(Integer value) {
System.out.println("Hook on Next");
request(1);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment