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
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@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 com.example.reactor.ProjectReactor.entity.Contact;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.core.Disposable;
import reactor.core.publisher.*;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.util.function.Tuple2;
import java.io.Serializable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@SpringBootTest
public class FluxSample {
@Test
public void createFlux() {
//Creating empty Flux
Flux<Object> empty = Flux.empty();
empty.subscribe(s -> System.out.println("Empty Flux from -->" + s));
//Creat Flux from Error
Flux<Object> error = Flux.error(new NullPointerException("Error Occured"));
error.subscribe(e -> System.out.println("Error Flux" + e));
//Creat flux with Just
Flux<String> just = Flux.just("Ravi", "Ramu");
just.subscribe(v -> System.out.println(v));
//Create flux with fromItrerable
List<String> stringList = Arrays.asList("Apple", "Ball", "Cat");
Flux<String> stringFlux = Flux.fromIterable(stringList);
stringFlux.subscribe(c -> System.out.println(c));
//Create Flux from Array
Flux<Integer> integerFlux = Flux.fromArray(new Integer[]{1, 2, 3, 4, 5});
integerFlux.subscribe(i -> System.out.println(i));
//Create Flux from Stream
Stream<Integer> integerStream = Stream.of(10, 11, 12, 13, 145);
Flux<Integer> integerFlux1 = Flux.fromStream(integerStream);
integerFlux1.subscribe(i -> System.out.println(i));
//Create Flux from another publisher
Flux<String> just1 = Flux.from(Mono.just("just"));
just1.subscribe(i -> System.out.println(i));
//Create Flux from range
Flux<Integer> range = Flux.range(1, 5);
range.subscribe(r -> System.out.println(r));
StepVerifier.create(just.log()).expectNext("Ravi").expectNext("Ramu").expectComplete();
Flux.empty().log();
Flux.never().log();
}
@Test
public void subscribe() {
Flux<Integer> range = Flux.range(1, 4);
range.subscribe();
range.subscribe(i -> System.out.println(i));
range.map(i -> {
if (i <= 3) return i;
throw new RuntimeException("Value got 4");
});
Disposable done = range.subscribe(i -> System.out.println(i),
error -> System.err.println("Error: " + error),
() -> System.out.println("Done"));
done.dispose();
SampleSubscriber<Integer> sampleSubscriber = new SampleSubscriber<Integer>();
Flux<Integer> range1 = Flux.range(1, 4);
range1.subscribe(sampleSubscriber);
}
@Test
public void generateFlux() {
Flux<Object> generate = Flux.generate(
() -> 0,
(state, sink) -> {
sink.next("3 X " + state + " = " + 3 * state);
if (state == 10) sink.complete();
return state + 1;
});
generate.subscribe(s -> System.out.println(s));
Flux<Object> generate1 = Flux.generate(
AtomicInteger::new,
(state, sink) -> {
int i = state.getAndIncrement();
sink.next("3 x " + state + " = " + 3 * i);
if (i == 10) sink.complete();
return state;
});
generate1.subscribe(s->System.out.println(s));
}
@Test
public void errorFlux() {
Flux<Object> error = Flux.error(new RuntimeException());
Flux<Integer> integerFlux = Flux.just(1, 4, 0).map(i -> (100 / i)).onErrorReturn(0);
integerFlux.subscribe(s->System.out.println(s));
StepVerifier.create(error.log()).expectError(RuntimeException.class).verify();
}
@Test
public void handleError() {
Flux<String> stringFlux = Flux.just("Hello", "World")
.concatWith(Mono.just("Ravi"))
.concatWith(Mono.error(new RuntimeException("Exception Occured")))
.concatWith(Mono.just("Pannala"));
StepVerifier.create(stringFlux).expectSubscription().expectNext("Hello").expectNext("World")
.expectNext("Ravi").expectError(RuntimeException.class).verify();
}
@Test
public void filter() {
Flux<Integer> filter = Flux.range(1, 10).filter(i -> i % 2 == 0);
Flux<Integer> filter1 = Flux.range(1, 10).filter(i -> i % 2 != 0);
StepVerifier.create(filter.log()).expectSubscription()
.expectNext(2).expectNext(4)
.expectNext(6).expectNext(8)
.verifyComplete();
}
@Test
public void flatMap() {
List<Contact> contactList = new ArrayList<>();
contactList.add(new Contact("st1", "Ravi", "Ravi@gmail.com", "8777565"));
// contactList.add(new Contact("st2", "avi", "avi@gmail.com", "777565"));
Flux<Contact> cFlux = Flux.fromIterable(contactList).flatMap(c -> {
return asynchrnousContact(c);
}).log();
StepVerifier.create(cFlux).expectSubscription()
.expectNext(new Contact("ST1", "RAVI", "RAVI@GMAIL.COM", "8777565"))
.verifyComplete();
}
private Mono<Contact> asynchrnousContact(Contact c) {
Contact contact = new Contact(c.getId().toUpperCase(), c.getName().toUpperCase(), c.getEmail().toUpperCase(), c.getPhone());
return Mono.just(contact);
}
@Test
private void map() {
List<Contact> contactList = new ArrayList<>();
contactList.add(new Contact("st1", "Ravi", "Ravi@gmail.com", "8777565"));
Flux<Contact> mapF = Flux.fromIterable(contactList)
.map(c -> new Contact(c.getId().toUpperCase(), c.getName().toUpperCase(), c.getEmail().toUpperCase(), c.getPhone()))
.log();
StepVerifier.create(mapF).expectSubscription()
.expectNext(new Contact("ST1", "RAVI", "RAVI@GMAIL.COM", "8777565"))
.verifyComplete();
}
@Test
public void parallel() {
ParallelFlux<Integer> log = Flux.range(1, 10)
.parallel()
.runOn(Schedulers.parallel())
.map(i -> i + 1)
.map(i -> i * 2)
.map(i -> i + 1)
.log();
StepVerifier.create(log).expectSubscription().expectNextCount(9).expectComplete();
}
@Test
public void multipleSubscribes() throws InterruptedException {
System.out.println("Starts");
Flux<String> just = Flux.just("a", "b", "c").log().delayElements(Duration.ofSeconds(1));
Disposable subscribe = just.map(i -> i.toUpperCase()).subscribe(a -> System.out.println("Observer 1:---" + a));
just.subscribe(a -> System.out.println("ObServer 2:--" + a));
System.out.println("Ends");
Thread.sleep(10000);
}
@Test
public void create() {
Flux<Integer> integerFlux = Flux.create((FluxSink<Integer> fluxSink) -> {
IntStream.range(0, 5).peek(i -> System.out.println("Going to Emit" + i)).forEach(fluxSink::next);
}, FluxSink.OverflowStrategy.DROP).log();
//First observer. takes 1 ms to process each element
integerFlux.delayElements(Duration.ofMillis(1)).subscribe(i -> System.out.println("First :: " + i));
//Second observer. takes 2 ms to process each element
integerFlux.delayElements(Duration.ofMillis(2)).subscribe(i -> System.out.println("Second:: " + i));
}
@Test
public void generate() {
AtomicInteger atomicInteger = new AtomicInteger();
Flux<Integer> generate = Flux.generate((SynchronousSink<Integer> synSink) -> {
System.out.println("Flux generate");
synSink.next(atomicInteger.getAndIncrement());
});
generate.delayElements(Duration.ofMillis(50))
.subscribe(i -> System.out.println("First consumed ::" + i));
}
@Test
public void schedularImmediate() {
/*Flux<Integer> log = Flux.range(0, 5).publishOn(Schedulers.immediate()).map(i -> {
System.out.println("Mapping for " + i + " is done by thread " + Thread.currentThread().getName());
return i;
}).log();
log.subscribe(i->System.out.println(i));*/
Flux<Integer> log1 = Flux.range(0, 2).publishOn(Schedulers.parallel()).map(i -> {
System.out.println("Mapping for " + i + " is done by thread " + Thread.currentThread().getName());
return i;
}).log();
log1.subscribeOn(Schedulers.parallel()).subscribe(i -> System.out.println("Paraller Subscription " + Thread.currentThread().getName()));
}
@Test
public void combine() {
Flux<Integer> log = Flux.just(1, 3, 4, 5).log();
Flux<Character> log1 = Flux.just('a', 'b', 'c', 'd').log();
Flux<? extends Serializable> concat = Flux.concat(log, log1);
Flux<String> stringFlux = Flux.combineLatest(log, log1, (a, b) -> a + " " + b);
stringFlux.subscribe(i -> System.out.println(i));
}
@Test
public void zip() {
Flux<Integer> just = Flux.just(1, 2, 3, 4);
Flux<Integer> just1 = Flux.just(9, 8, 7, 6);
Flux<Tuple2<Integer, Integer>> zip = Flux.zip(just, just1);
zip.subscribe(tuple -> {
System.out.println("First Source " + tuple.getT1() + " Second Source " + tuple.getT2());
});
}
/*@Test
public void fileReading() throws IOException {
Path ipPath = Paths.get("C:\\Users\\rpannala\\Downloads\\RAVINDER_REDDY_PANNALA.docx");
Flux<String> stringFlux = Flux.using(
() -> Files.lines(ipPath),
Flux::fromStream,
Stream::close
);
Path opPath = Paths.get("C:\\Users\\rpannala\\Downloads\\large-output-file.txt");
BufferedWriter bw = Files.newBufferedWriter(opPath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
stringFlux
.subscribe(s -> write(bw, s),
(e) -> close(bw), // close file if error / oncomplete
() -> close(bw)
);
}
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.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