Commit 094a5ee7 authored by Ravinder Pannala's avatar Ravinder Pannala

First commit

parent e49494eb
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/
# 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.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.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.nisum</groupId>
<artifactId>webflux-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>webflux-mongodb</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-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</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>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-ui</artifactId>
<version>1.6.4</version>
</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.nisum.webfluxmongodb.Service;
import com.example.nisum.webfluxmongodb.model.Address;
import com.example.nisum.webfluxmongodb.repository.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class AddressService {
@Autowired
private AddressRepository addressRepository;
public Mono<Address> save(Address address) {
return addressRepository.save(address);
}
public Flux<Address> findByStudentId(Long studentId) {
return addressRepository.findByStudentId(studentId);
}
public Flux<Address> findByCity(String city) {
return addressRepository.findByCity(city);
}
}
package com.example.nisum.webfluxmongodb.Service;
import com.example.nisum.webfluxmongodb.dto.StudentBasicDto;
import com.example.nisum.webfluxmongodb.dto.StudentDto;
import com.example.nisum.webfluxmongodb.model.Address;
import com.example.nisum.webfluxmongodb.model.Student;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import com.example.nisum.webfluxmongodb.repository.AddressRepository;
import com.example.nisum.webfluxmongodb.repository.StudentRepository;
import com.example.nisum.webfluxmongodb.repository.SubjectRepository;
import com.example.nisum.webfluxmongodb.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuples;
import java.util.ArrayList;
import java.util.List;
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
@Autowired
AddressRepository addressRepository;
@Autowired
SubjectRepository subjectRepository;
@Autowired
TeacherRepository teacherRepository;
public Mono<Student> save(StudentDto studentDto) {
Student s = new Student();
s.setId(studentDto.getId());
s.setFirstName(studentDto.getFirstName());
s.setLastName(studentDto.getLastName());
s.setAge(studentDto.getAge());
s.setPhoneNumbers(studentDto.getPhoneNumbers());
Mono<Student> saveMono = studentRepository.save(s);
List<Address> addressList = new ArrayList<>();
List<Subject> subjectList = new ArrayList<>();
List<Teachers> teachersList = new ArrayList<>();
saveMono.subscribe(student -> {
studentDto.getAddresses().forEach(add -> {
Address address = new Address();
address.setId(add.getId());
address.setStudentId(add.getStudentId());
address.setAddress(add.getAddress());
address.setAddressType(add.getAddressType());
address.setCity(add.getCity());
address.setPincode(add.getPincode());
addressList.add(address);
});
studentDto.getSubjects().forEach(sub -> {
Subject subject = new Subject();
subject.setId(sub.getId());
subject.setStudentId(sub.getStudentId());
subject.setSubjectName(sub.getSubjectName());
subjectList.add(subject);
});
studentDto.getTeachers().forEach(teach -> {
Teachers teachers = new Teachers();
teachers.setId(teach.getId());
teachers.setStudentId(teach.getStudentId());
teachers.setTeacherName(teach.getTeacherName());
teachers.setTeacherSubject(teach.getTeacherSubject());
teachersList.add(teachers);
});
Flux<Address> addressFlux = addressRepository.saveAll(addressList);
Flux<Subject> subjectFlux = subjectRepository.saveAll(subjectList);
Flux<Teachers> teachersFlux = teacherRepository.saveAll(teachersList);
});
return saveMono;
}
public Flux<Student> getAll() {
Flux<Student> studentFlux = studentRepository.findAll().flatMap(student -> {
Flux<Address> addressFlux = addressRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Address())).log();
Flux<Subject> subjectFlux = subjectRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Subject())).log();
Flux<Teachers> teachersFlux = teacherRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Teachers())).log();
List<Address> addressList = new ArrayList<>();
List<Subject> subjectList = new ArrayList<>();
List<Teachers> teachersList = new ArrayList<>();
addressFlux.collectList().subscribe(addressList::addAll);
subjectFlux.collectList().subscribe(subjectList::addAll);
teachersFlux.collectList().subscribe(teachersList::addAll);
student.setAddress(addressList);
student.setSubjects(subjectList);
student.setTeachers(teachersList);
return Flux.just(student).log();
}).switchIfEmpty(Flux.just(new Student()));
return studentFlux;
}
public Mono<Student> findById(Long studentId) {
Mono<Student> map = studentRepository.findById(studentId).zipWhen(student -> {
Flux<Address> addressFlux = addressRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Address()));
Flux<Subject> subjectFlux = subjectRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Subject()));
Flux<Teachers> teachersFlux = teacherRepository.findByStudentId(student.getId()).switchIfEmpty(Flux.just(new Teachers()));
return addressFlux.collectList().zipWith(subjectFlux.collectList()).zipWith(teachersFlux.collectList());
}).map(tuple2 -> {
Student student = tuple2.getT1();
Tuple2<Tuple2<List<Address>, List<Subject>>, List<Teachers>> astCominationTuple = tuple2.getT2();
Tuple2<List<Address>, List<Subject>> asCombinationTuple = astCominationTuple.getT1();
List<Teachers> teachersList = astCominationTuple.getT2();
List<Address> addressLIst = asCombinationTuple.getT1();
List<Subject> subjectList = asCombinationTuple.getT2();
student.setAddress(addressLIst);
student.setSubjects(subjectList);
student.setTeachers(teachersList);
return student;
});
return map.log();
}
public Flux<Student> searchNames(String names) {
String[] split = names.split(",");
Flux<Student> studentFlux = Flux.fromArray(split).flatMap(name -> studentRepository.findByFirstName(name));
return studentFlux;
}
public Flux<Tuple2<Tuple2<Tuple2<Student, Address>, Subject>, Teachers>> searchNamesWithZip(String name) {
Flux<Student> studentByName = studentRepository.findByFirstName(name);
Flux<Tuple2<Student, Address>> studentAddFlux = studentByName.flatMap(student -> {
Mono<Address> addressById = addressRepository.findById(student.getId());
return studentByName.zipWith(addressById);
});
Flux<Tuple2<Tuple2<Student, Address>, Subject>> studentAddSubjectFlux = studentAddFlux.flatMap(student -> {
Flux<Subject> subjectById = subjectRepository.findByStudentId(student.getT1().getId());
return studentAddFlux.zipWith(subjectById);
});
Flux<Tuple2<Tuple2<Tuple2<Student, Address>, Subject>, Teachers>> studentAddSubTeachersFlux = studentAddSubjectFlux.flatMap(student -> {
Flux<Teachers> teachersById = teacherRepository.findByStudentId(student.getT1().getT1().getId());
return studentAddSubjectFlux.zipWith(teachersById);
});
return studentAddSubTeachersFlux;
}
public Flux<Tuple2<String, String>> studentNames() {
Flux<Student> studentFlux = studentRepository.findAll();
Flux<String> map = studentFlux.map(student -> {
return student.getFirstName();
});
Flux<String> map1 = studentFlux.map(student -> {
return student.getLastName();
});
Flux<String> map2 = studentFlux.map(student -> {
return student.getAge();
});
Flux<Tuple3<String, String, String>> zip = Flux.zip(map, map1, map2);
Flux<Tuple2<String, String>> map3 = zip.map(e -> Tuples.of(e.getT1() + e.getT2(), e.getT3()));
/*Mono<List<String>> listMono = zip.map(string -> {
return string.getT1().toUpperCase() + " " + string.getT2().toUpperCase() + "----" + string.getT3();
}).collectList();*/
//Flux<Tuple2<String, String>> tuple2Flux = map.zipWith(map1);
return map3;
}
public Flux<StudentBasicDto> studentBasicInformation() {
Flux<StudentBasicDto> studentBasicDtoFlux =studentRepository.findAll().flatMap(student -> {
Flux<Address> addressFlux = addressRepository.findByStudentId(student.getId());
Flux<Subject> subjectFlux = subjectRepository.findByStudentId(student.getId());
Flux<String> stringFlux = subjectFlux.map(sub -> sub.getSubjectName());
Flux<Teachers> teachersFlux = teacherRepository.findByStudentId(student.getId());
StudentBasicDto basicDto = new StudentBasicDto();
basicDto.setFullName(student.getFirstName() + "" + student.getLastName());
basicDto.setId(student.getId());
basicDto.setPresentAddress(Mono.from(addressFlux).block());
basicDto.setFirstTeacher(Mono.from(teachersFlux).block());
basicDto.setPrimarySubject(Mono.from(stringFlux).block());
return Flux.just(basicDto);
});
return studentBasicDtoFlux;
}
//Find Students who are all belogs to Specified location
public Flux<Student> findStudentsWhoBelogstoSpecifiedLocation(String location){
List<Address> addresses = new ArrayList<>();
Flux<Student> studentFlux = studentRepository.findAll().flatMap(student -> {
Flux<Address> byCity = addressRepository.findByCity(location);
byCity.collectList().subscribe(addresses::addAll);
student.setAddress(addresses);
return Flux.just(student);
});
return studentFlux;
}
}
package com.example.nisum.webfluxmongodb.Service;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.repository.SubjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class SubjectService {
@Autowired
private SubjectRepository subjectRepository;
public Mono<Subject> save(Subject subject) {
return subjectRepository.save(subject);
}
public Flux<Subject> findByStudentId(Long studentId) {
return subjectRepository.findByStudentId(studentId);
}
}
package com.example.nisum.webfluxmongodb.Service;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import com.example.nisum.webfluxmongodb.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class TeacherService {
@Autowired
private TeacherRepository teacherRepository;
public Mono<Teachers> save(Teachers teachers) {
return teacherRepository.save(teachers);
}
public Flux<Teachers> findByStudentId(Long studentId) {
return teacherRepository.findByStudentId(studentId);
}
}
package com.example.nisum.webfluxmongodb.controller;
import com.example.nisum.webfluxmongodb.Service.AddressService;
import com.example.nisum.webfluxmongodb.model.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/address")
public class AddressController {
@Autowired
AddressService addressService;
@PostMapping("/save")
public Mono<Address> save(@RequestBody Address address){
return addressService.save(address);
}
@GetMapping("/{studentId}")
public Flux<Address> findByStudentId(@PathVariable Long studentId){
return addressService.findByStudentId(studentId);
}
@GetMapping("/city/{city}")
public Flux<Address> findByCity(@PathVariable String city){
return addressService.findByCity(city);
}
}
package com.example.nisum.webfluxmongodb.controller;
import com.example.nisum.webfluxmongodb.Service.StudentService;
import com.example.nisum.webfluxmongodb.dto.StudentBasicDto;
import com.example.nisum.webfluxmongodb.dto.StudentDto;
import com.example.nisum.webfluxmongodb.model.Address;
import com.example.nisum.webfluxmongodb.model.Student;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
@RestController
@RequestMapping("/api/student")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping(value = "/save")
public Mono<Student> saveStudent(@RequestBody StudentDto studentDto){
return studentService.save(studentDto);
}
@GetMapping(value="/getAll")
public Flux<Student> getAll(){
return studentService.getAll();
}
@GetMapping(value="/{studentId}")
public Mono<Student> findByStudentId(@PathVariable Long studentId){
Mono<Student> student = studentService.findById(studentId);
student.subscribe(student1 -> System.out.println(student1));
return student;
}
@GetMapping(value = "/searchNames/{names}")
public Flux<Student> searchNames(@PathVariable String names){
Flux<Student> studentFlux = studentService.searchNames(names);
return studentFlux;
}
@GetMapping("/searchNamesWithZip/{name}")
public Flux<Tuple2<Tuple2<Tuple2<Student, Address>, Subject>, Teachers>> searchNamesWithZip(@PathVariable String name){
return studentService.searchNamesWithZip(name);
}
@GetMapping("/getStudentNames")
public Flux<Tuple2<String, String>> studentNames(){
//Flux<Tuple2<String, String>> tuple2Flux = studentService.studentNames();
return studentService.studentNames();
}
@GetMapping("/studentsBasicInfo")
public Flux<StudentBasicDto> studentBasicInformation(){
Flux<StudentBasicDto> studentBasicDtoFlux = studentService.studentBasicInformation();
return studentBasicDtoFlux;
}
@GetMapping("/getStudents/{city}")
public Flux<Student> findStudentsWhoBelogstoSpecifiedLocation(@PathVariable String city){
return studentService.findStudentsWhoBelogstoSpecifiedLocation(city);
}
}
package com.example.nisum.webfluxmongodb.controller;
import com.example.nisum.webfluxmongodb.Service.SubjectService;
import com.example.nisum.webfluxmongodb.model.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/subject")
public class SubjectController {
@Autowired
private SubjectService subjectService;
@PostMapping("/save")
public Mono<Subject> save(@RequestBody Subject subject){
return subjectService.save(subject);
}
@GetMapping("/{studentId}")
public Flux<Subject> findByStudentId(@PathVariable Long studentId){
return subjectService.findByStudentId(studentId);
}
}
package com.example.nisum.webfluxmongodb.controller;
import com.example.nisum.webfluxmongodb.Service.TeacherService;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@PostMapping("/save")
public Mono<Teachers> save(@RequestBody Teachers teachers){
return teacherService.save(teachers);
}
@GetMapping("/{studentId}")
public Flux<Teachers> findByStudentId(@PathVariable Long studentId){
return teacherService.findByStudentId(studentId);
}
}
package com.example.nisum.webfluxmongodb.dto;
import com.example.nisum.webfluxmongodb.model.Address;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import lombok.Value;
public class StudentBasicDto {
private Long id;
private String fullName;
private Address presentAddress;
private String primarySubject;
private Teachers firstTeacher;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Address getPresentAddress() {
return presentAddress;
}
public void setPresentAddress(Address presentAddress) {
this.presentAddress = presentAddress;
}
public String getPrimarySubject() {
return primarySubject;
}
public void setPrimarySubject(String primarySubject) {
this.primarySubject = primarySubject;
}
public Teachers getFirstTeacher() {
return firstTeacher;
}
public void setFirstTeacher(Teachers firstTeacher) {
this.firstTeacher = firstTeacher;
}
public StudentBasicDto(Long id, String fullName, Address presentAddress, String primarySubject, Teachers firstTeacher) {
this.id = id;
this.fullName = fullName;
this.presentAddress = presentAddress;
this.primarySubject = primarySubject;
this.firstTeacher = firstTeacher;
}
public StudentBasicDto() {
}
@Override
public String toString() {
return "StudentBasicDto{" +
"id=" + id +
", fullName='" + fullName + '\'' +
", presentAddress=" + presentAddress +
", primarySubject=" + primarySubject +
", firstTeacher=" + firstTeacher +
'}';
}
}
package com.example.nisum.webfluxmongodb.dto;
import com.example.nisum.webfluxmongodb.model.Address;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import java.util.List;
public class StudentDto {
private Long id;
private String firstName;
private String lastName;
private String age;
private List<String> phoneNumbers;
private List<Address> addresses;
private List<Subject> subjects;
private List<Teachers> teachers;
public StudentDto(Long id, String firstName, String lastName, String age, List<String> phoneNumbers, List<Address> addresses, List<Subject> subjects, List<Teachers> teachers) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phoneNumbers = phoneNumbers;
this.addresses = addresses;
this.subjects = subjects;
this.teachers = teachers;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public List<Teachers> getTeachers() {
return teachers;
}
public void setTeachers(List<Teachers> teachers) {
this.teachers = teachers;
}
public StudentDto() {
}
@Override
public String toString() {
return "StudentDto{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age='" + age + '\'' +
", phoneNumbers=" + phoneNumbers +
", addresses=" + addresses +
", subjects=" + subjects +
", teachers=" + teachers +
'}';
}
}
package com.example.nisum.webfluxmongodb.model;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Address {
@Id
private Long id;
private String address;
private String city;
private String pincode;
private String addressType;
private Long studentId;
}
package com.example.nisum.webfluxmongodb.model;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Document
public class Student {
@Id
private Long id;
private String firstName;
private String lastName;
private String age;
private List<String> phoneNumbers;
private List<Address> address;
private List<Subject> subjects;
private List<Teachers> teachers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public List<Teachers> getTeachers() {
return teachers;
}
public void setTeachers(List<Teachers> teachers) {
this.teachers = teachers;
}
}
package com.example.nisum.webfluxmongodb.model;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Subject {
@Id
private Long id;
private String subjectName;
private Long studentId;
}
package com.example.nisum.webfluxmongodb.model;
import lombok.*;
import org.springframework.data.annotation.Id;
@Data
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Teachers {
@Id
private Long id;
private String teacherName;
private String teacherSubject;
private Long studentId;
}
package com.example.nisum.webfluxmongodb.repository;
import com.example.nisum.webfluxmongodb.model.Address;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Repository
public interface AddressRepository extends ReactiveMongoRepository<Address,Long> {
Flux<Address> findByStudentId(Long studentId);
Flux<Address> findByCity(String location);
}
package com.example.nisum.webfluxmongodb.repository;
import com.example.nisum.webfluxmongodb.model.Student;
import org.reactivestreams.Publisher;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface StudentRepository extends ReactiveMongoRepository<Student,Long> {
Flux<Student> findByFirstName(String name);
}
package com.example.nisum.webfluxmongodb.repository;
import com.example.nisum.webfluxmongodb.model.Subject;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface SubjectRepository extends ReactiveMongoRepository<Subject,Long> {
Flux<Subject> findByStudentId(Long studentId);
}
package com.example.nisum.webfluxmongodb.repository;
import com.example.nisum.webfluxmongodb.model.Subject;
import com.example.nisum.webfluxmongodb.model.Teachers;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface TeacherRepository extends ReactiveMongoRepository<Teachers,Long> {
Flux<Teachers> findByStudentId(Long studentId);
}
package com.example.nisum.webfluxmongodb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class webfluxMongoDBApplication {
public static void main(String[] args) {
SpringApplication.run(webfluxMongoDBApplication.class, args);
}
}
package com.example.nisum.webfluxmongodb.zipping.DTO;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import lombok.*;
import java.util.List;
@Data
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentEmployeeDto {
private String name;
private List<Employee> employeeList;
}
package com.example.nisum.webfluxmongodb.zipping.Exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorMessage> handleException(ResourceNotFoundException ex) {
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setStatusCode(HttpStatus.NOT_FOUND.value());
errorMessage.setErrorMessage(ex.getMessage());
errorMessage.setErrorDescription(ex.getLocalizedMessage());
errorMessage.setErrorDate(new Date());
return new ResponseEntity<>(errorMessage, HttpStatus.NOT_FOUND);
}
}
package com.example.nisum.webfluxmongodb.zipping.Exception;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Data
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class ErrorMessage {
int statusCode;
private String errorMessage;
private String errorDescription;
private Date errorDate;
}
package com.example.nisum.webfluxmongodb.zipping.Exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
package com.example.nisum.webfluxmongodb.zipping.controller;
import com.example.nisum.webfluxmongodb.zipping.DTO.DepartmentEmployeeDto;
import com.example.nisum.webfluxmongodb.zipping.model.Department;
import com.example.nisum.webfluxmongodb.zipping.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/dept")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@RequestMapping("/save")
private Mono<Department> save(@RequestBody Department department) {
return departmentService.save(department);
}
@RequestMapping("/get")
private Flux<Department> getAll() {
return departmentService.getAll();
}
@RequestMapping("/get/{orgId}")
private Flux<Department> getByOrgId(@PathVariable int orgId){
return departmentService.findByOrganizationId(orgId);
}
//Get Department by Id
@RequestMapping("/get/{deptId}")
private Mono<DepartmentEmployeeDto> findByDepartmentId(@PathVariable int id){
return departmentService.findById(id);
}
}
package com.example.nisum.webfluxmongodb.zipping.controller;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import com.example.nisum.webfluxmongodb.zipping.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("/save")
private Mono<Employee> save(@RequestBody Employee employee) {
return employeeService.save(employee);
}
@RequestMapping("/get")
private Flux<Employee> getAll() {
return employeeService.getAll();
}
@RequestMapping("/get/{orgId}")
private Flux<Employee> findByOrganizationId(@PathVariable int orgId) {
return employeeService.findByOrganizationId(orgId);
}
@RequestMapping("/get/{Id}")
private Flux<Employee> findByDepartmentId(@PathVariable int departmentId) {
return employeeService.findByDepartmentId(departmentId);
}
}
package com.example.nisum.webfluxmongodb.zipping.controller;
import com.example.nisum.webfluxmongodb.zipping.Exception.ResourceNotFoundException;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import com.example.nisum.webfluxmongodb.zipping.model.Organization;
import com.example.nisum.webfluxmongodb.zipping.service.EmployeeService;
import com.example.nisum.webfluxmongodb.zipping.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.BooleanOperators;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ResourceAccessException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api/org")
public class OrganizationController {
@Autowired
private OrganizationService organizationService;
@RequestMapping("/save")
private Mono<Organization> save(@RequestBody Organization organization) {
return organizationService.save(organization);
}
@RequestMapping("/get")
private Flux<Organization> getAll() {
return organizationService.getAll();
}
@RequestMapping("/get/{id}")
private Mono<Organization> findById(@PathVariable int id) {
Mono<Organization> organizationMono = organizationService.findById(id);
organizationMono.switchIfEmpty(Mono.error(new ResourceNotFoundException("Resource not found")));
return organizationMono;
}
}
package com.example.nisum.webfluxmongodb.zipping.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Document
public class Department {
@Id
private int id;
private String name;
private int organizationId;
private List<Employee> employees;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getOrganizationId() {
return organizationId;
}
public void setOrganizationId(int organizationId) {
this.organizationId = organizationId;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Department(int id, String name, int organizationId, List<Employee> employees) {
this.id = id;
this.name = name;
this.organizationId = organizationId;
this.employees = employees;
}
public Department(int id, String name) {
this.id = id;
this.name = name;
}
public Department(int id, String name, int organizationId) {
this.id = id;
this.name = name;
this.organizationId = organizationId;
}
public Department() {
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name='" + name + '\'' +
", organizationId=" + organizationId +
", employees=" + employees +
'}';
}
}
package com.example.nisum.webfluxmongodb.zipping.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Employee {
@Id
private int id;
private String name;
private int salary;
private int organizationId;
private int departmentId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getOrganizationId() {
return organizationId;
}
public void setOrganizationId(int organizationId) {
this.organizationId = organizationId;
}
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
public Employee(int id, String name, int salary, int organizationId, int departmentId) {
this.id = id;
this.name = name;
this.salary = salary;
this.organizationId = organizationId;
this.departmentId = departmentId;
}
public Employee(int id, String name, int salary, int organizationId) {
this.id = id;
this.name = name;
this.salary = salary;
this.organizationId = organizationId;
}
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public Employee() {
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
", organizationId=" + organizationId +
", departmentId=" + departmentId +
'}';
}
}
package com.example.nisum.webfluxmongodb.zipping.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Document
public class Organization {
@Id
private int id;
private String name;
private List<Employee> employees;
private List<Department> departments;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
public Organization(int id, String name, List<Employee> employees, List<Department> departments) {
this.id = id;
this.name = name;
this.employees = employees;
this.departments = departments;
}
public Organization(int id, String name, List<Employee> employees) {
this.id = id;
this.name = name;
this.employees = employees;
}
public Organization(int id, String name) {
this.id = id;
this.name = name;
}
public Organization() {
}
@Override
public String toString() {
return "Organization{" +
"id=" + id +
", name='" + name + '\'' +
", employees=" + employees +
", departments=" + departments +
'}';
}
}
package com.example.nisum.webfluxmongodb.zipping.repository;
import com.example.nisum.webfluxmongodb.zipping.model.Department;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface DepartmentRepository extends ReactiveMongoRepository<Department,Integer> {
Flux<Department> findByOrganizationId(int orgId);
}
package com.example.nisum.webfluxmongodb.zipping.repository;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
@Repository
public interface EmployeeRepository extends ReactiveMongoRepository<Employee, Integer> {
Flux<Employee> findByOrganizationId(int orgId);
Flux<Employee> findByDepartmentId(int departmentId);
}
package com.example.nisum.webfluxmongodb.zipping.repository;
import com.example.nisum.webfluxmongodb.zipping.model.Organization;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseStatus;
@Repository
public interface OrganizationRepository extends ReactiveMongoRepository<Organization,Integer> {
}
package com.example.nisum.webfluxmongodb.zipping.service;
import com.example.nisum.webfluxmongodb.zipping.DTO.DepartmentEmployeeDto;
import com.example.nisum.webfluxmongodb.zipping.Exception.ResourceNotFoundException;
import com.example.nisum.webfluxmongodb.zipping.model.Department;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import com.example.nisum.webfluxmongodb.zipping.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import java.util.ArrayList;
import java.util.List;
@Service
public class DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
@Autowired
private EmployeeService employeeService;
public Mono<Department> save(Department department) {
return departmentRepository.save(department);
}
public Flux<Department> getAll() {
return departmentRepository.findAll();
}
public Flux<Department> findByOrganizationId(int orgId) {
return departmentRepository.findByOrganizationId(orgId);
}
public Mono<DepartmentEmployeeDto> findById(int id) {
List<Employee> employees = new ArrayList<>();
Mono<DepartmentEmployeeDto> map = departmentRepository
.findById(id).zipWhen(dept -> {
Flux<Employee> employeeFlux = employeeService.findByDepartmentId(dept.getId()).switchIfEmpty(Flux.just(new Employee()));
DepartmentEmployeeDto departmentEmployeeDto = new DepartmentEmployeeDto();
departmentEmployeeDto.setName(dept.getName());
employeeFlux.collectList().subscribe(employees::addAll);
departmentEmployeeDto.setEmployeeList(employees);
return Mono.just(departmentEmployeeDto);
}).switchIfEmpty(Mono.error(new ResourceNotFoundException("Department id not found"))).map(tuple -> {
DepartmentEmployeeDto t2 = tuple.getT2();
return t2;
});
return map;
}
}
package com.example.nisum.webfluxmongodb.zipping.service;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import com.example.nisum.webfluxmongodb.zipping.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public Mono<Employee> save(Employee employee) {
return employeeRepository.save(employee);
}
public Flux<Employee> getAll() {
return employeeRepository.findAll();
}
public Flux<Employee> findByOrganizationId(int orgId) {
return employeeRepository.findByOrganizationId(orgId);
}
public Flux<Employee> findByDepartmentId(int departmentId) {
return employeeRepository.findByDepartmentId(departmentId);
}
}
package com.example.nisum.webfluxmongodb.zipping.service;
import com.example.nisum.webfluxmongodb.zipping.Exception.ResourceNotFoundException;
import com.example.nisum.webfluxmongodb.zipping.model.Department;
import com.example.nisum.webfluxmongodb.zipping.model.Employee;
import com.example.nisum.webfluxmongodb.zipping.model.Organization;
import com.example.nisum.webfluxmongodb.zipping.repository.OrganizationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import java.util.ArrayList;
import java.util.List;
@Service
public class OrganizationService {
@Autowired
private OrganizationRepository organizationRepository;
@Autowired
private DepartmentService departmentService;
@Autowired
private EmployeeService employeeService;
public Mono<Organization> save(Organization organization) {
return organizationRepository.save(organization);
}
public Flux<Organization> getAll() {
return organizationRepository.findAll();
}
public Mono<Organization> findById(int id) {
Mono<Organization> organizationMono = organizationRepository.findById(id).zipWhen(org -> {
Flux<Department> departmentFlux = departmentService.findByOrganizationId(org.getId()).switchIfEmpty(Flux.just(new Department()));
Flux<Employee> employeeFlux = employeeService.findByOrganizationId(org.getId()).switchIfEmpty(Flux.just(new Employee()));
return departmentFlux.collectList().zipWith(employeeFlux.collectList());
}).map(tuple -> {
Organization organization = tuple.getT1();
Tuple2<List<Department>, List<Employee>> departmentEmployeeTuple = tuple.getT2();
organization.setDepartments(departmentEmployeeTuple.getT1());
organization.setEmployees(departmentEmployeeTuple.getT2());
return organization;
}).switchIfEmpty(Mono.error(new ResourceNotFoundException("Resource not found")));
return organizationMono;
}
}
spring.data.mongodb.uri=mongodb://localhost:27017/
spring.data.mongodb.database=school
package com.example.nisum.webfluxmongodb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WebfluxMongodbApplicationTests {
@Test
void contextLoads() {
}
}
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