Commit ba54d850 authored by Sridhar Pothanaveni's avatar Sridhar Pothanaveni

Project with Spring boot webflux and mongoDB

parent 9d083b86
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
# WebFlux-MongoDB Aggregations
Create project with Spring boot Webflux wit MongoDB database.
=> Models 1.Employee 2.Cities 3.Sales
Employee End points:
1.http://localhost:8080/employee/saveEmployee
1.http://localhost:8080/employee/findById/{empId}
1.http://localhost:8080/employee/findAllEmployees
1.http://localhost:8080/employee/findAllEmployeesBySalary : Find all employees who is having salary greater than 30k
Cities End Points:
1.http://localhost:8080/cities/createCity
1.http://localhost:8080/cities/findAll
1.http://localhost:8080/cities/findByCitiesInContinent : Find all cities by continent using Aggregation classes
1.http://localhost:8080/cities/findCitiesByPopulation : Find all cities by population by continent wise using mongodb query directly in aggregations classes
\ No newline at end of file
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%
<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 http://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.techgeeknext</groupId>
<artifactId>spring-boot-webflux-task</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-webflux-task</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.4</version>
</dependency> -->
</dependencies>
</project>
\ No newline at end of file
package com.nisum.task;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SwaggerDefinition
//@EnableWebMvc
//@EnableSwagger2
//@EnableWebFlux
//@OpenAPIDefinition(info = @Info(title = "Swagger Demo", version = "1.0", description = "Documentation APIs v1.0"))
@SpringBootApplication
public class TaskApplication //extends SpringBootServletInitializer
{
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
// @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// return application.sources(TaskApplication.class);
// }
//
// @Bean
// public Docket api() {
// return new Docket(DocumentationType.SWAGGER_2)
// .select()
// .apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
// .build();
// //.apiInfo(apiInfo());
// }
}
// private ApiInfo apiInfo() {
// return new ApiInfo(
// "API XXXX",
// "API XXXX para integrações entre sistemas.",
// "API V1",
// "Terms of service",
// // new Contact("XXXX", "www.XXXX.com", "XXXX.XXXX@XXXX.com"),
// "License of XXX", "API license URL", Collections.emptyList());
// }
// }
// @Bean
// public Docket productApi() {
// return new Docket(DocumentationType.SWAGGER_2).select()
// .apis(RequestHandlerSelectors.basePackage("com.nisum.task")).build();
// }
package com.nisum.task.config;
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;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
@Configuration
@EnableMongoRepositories(basePackages = "com.nisum.task.repository")
public class MongoDbConfig extends AbstractReactiveMongoConfiguration {
@Value("${database.name}")
private String databaseName;
@Value("${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.nisum.task.config;
//@Configuration
//@EnableSwagger2
//@OpenAPIDefinition(info = @Info(title = "Swagger Demo", version = "1.0", description = "Documentation APIs v1.0"))
public class SwaggerConfig {
// @Bean
// public Docket createRestApi() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(new ApiInfoBuilder()
// .description("My Reactive API")
// .title("My Domain object API")
// .version("1.0.0")
// .build())
// .enable(true)
// .select()
// .apis(RequestHandlerSelectors.basePackage("com.nisum.task.controller"))
// .paths(PathSelectors.any())
// .build();
// }
}
package com.nisum.task.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
@Configuration
public class WebFluxConfig implements WebFluxConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html**")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
package com.nisum.task.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.task.entity.Cities;
import com.nisum.task.service.CityService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/cities")
public class CitiesController {
@Autowired
private CityService cityService;
@PostMapping("/createCity")
public Mono<Cities> saveCity(@RequestBody Cities city) {
return cityService.createCity(city);
}
@GetMapping("/findAll")
public Flux<Cities> getAllCities() {
return cityService.findAll();
}
@GetMapping("/findByCitiesInContinent")
public Flux<Cities> findAllCities() {
return cityService.getAllCities();
}
@GetMapping("/findCitiesByPopulation")
public Flux<Cities> findAllCitiesByPopulation() {
return cityService.citiesByPopulation();
}
@GetMapping("/findCitiesBySorting")
public Flux<Cities> findCitiesBySorting() {
return cityService.sortByPopulation();
}
}
package com.nisum.task.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.task.entity.Employee;
import com.nisum.task.service.EmployeeService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/saveEmployee")
public Mono<Employee> saveEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
@GetMapping("/findById/{empId}")
public Mono<Employee> getEmployee(@PathVariable String empId) {
return employeeService.findById(Long.valueOf(empId));
}
@GetMapping("/findAllEmployees")
public Flux<Employee> findAllEmployee() {
return employeeService.findAllEmployees();
}
@GetMapping("/findAllEmployeesBySalary")
public Flux<Employee> findAllEmployees() {
return employeeService.fetchEmployessBySalary();
}
}
package com.nisum.task.controller;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.task.entity.Sales;
import com.nisum.task.service.SalesService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/sales")
public class SalesController {
@Autowired
private SalesService salesService;
@PostMapping("/addSale")
public Mono<Sales> addSale(@RequestBody Sales sale) {
return salesService.addSale(sale);
}
@GetMapping("/findById/{saleId}")
public Mono<Sales> getSale(@PathVariable String saleId) {
return salesService.findById(Long.valueOf(saleId));
}
@GetMapping("/findAllSales")
public Flux<Sales> findSales() {
return salesService.findAllSales();
}
@GetMapping("/searchBy/{mode}/{location}")
public Flux<Document> findSalesByLocation(@PathVariable String mode,@PathVariable String location) {
return salesService.searchByPurchaseModes(mode,location);
}
@GetMapping("/searchByLocation/{mode}/{location}")
public Flux<Sales> findByLocation(@PathVariable String mode,@PathVariable String location) {
return salesService.findByPurchaseModeAndLocation(mode,location);
}
}
package com.nisum.task.entity;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Cities {
private ObjectId _id;
private String name;
private String country;
private String continent;
private String population;
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
@Override
public String toString() {
return "Cities [_id=" + _id + ", name=" + name + ", country=" + country + ", continent=" + continent
+ ", population=" + population + "]";
}
}
package com.nisum.task.entity;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Customer {
private ObjectId _id;
private String email;
private String gender;
private String age;
private Integer satisfaction;
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Integer getSatisfaction() {
return satisfaction;
}
public void setSatisfaction(Integer satisfaction) {
this.satisfaction = satisfaction;
}
@Override
public String toString() {
return "Customer [_id=" + _id + ", email=" + email + ", gender=" + gender + ", age=" + age + ", satisfaction="
+ satisfaction + "]";
}
}
package com.nisum.task.entity;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Employee {
private Long id;
private String firstName;
private String lastName;
private String age;
private Double salary;
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 Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age
+ ", salary=" + salary + "]";
}
}
package com.nisum.task.entity;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Items {
private ObjectId _id;
private String name;
private Double price;
private Integer quantity;
private List<String> tags;
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Items [_id=" + _id + ", name=" + name + ", price=" + price + ", quantity=" + quantity + ", tags=" + tags
+ "]";
}
}
package com.nisum.task.entity;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Sales {
private ObjectId _id;
private String storeLocation;
private boolean couponUsed;
private String purchaseMethod;
private Customer customer;
private List<Items> items;
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getStoreLocation() {
return storeLocation;
}
public void setStoreLocation(String storeLocation) {
this.storeLocation = storeLocation;
}
public boolean isCouponUsed() {
return couponUsed;
}
public void setCouponUsed(boolean couponUsed) {
this.couponUsed = couponUsed;
}
public String getPurchaseMethod() {
return purchaseMethod;
}
public void setPurchaseMethod(String purchaseMethod) {
this.purchaseMethod = purchaseMethod;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
package com.nisum.task.exception;
public class EmployeeException extends RuntimeException{
public EmployeeException(String message) {
super(message);
}
}
package com.nisum.task.repository;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.nisum.task.entity.Cities;
import reactor.core.publisher.Flux;
@Repository
public interface CityRepository extends ReactiveMongoRepository<Cities, Long>{
@Aggregation(pipeline = {
"{$match:{'continent':'South America'}}",
})
Flux<Cities> findMaxPopulation();
}
package com.nisum.task.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.nisum.task.entity.Employee;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Repository
public interface EmployeeRepository extends ReactiveMongoRepository<Employee, Long>{
Mono<Employee> findById(Long employeeId);
//@Query(value= {$gt:[{"salary":1000}]})
Flux<Employee> findEmployeesBySalary();
//db.employee.find({$gt:[{"salary":1000}]})
}
package com.nisum.task.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.nisum.task.entity.Sales;
import reactor.core.publisher.Flux;
@Repository
public interface SalesRepository extends ReactiveMongoRepository<Sales, Long>{
Flux<Sales> findByPurchaseMethodAndStoreLocation(String mode, String location);
}
package com.nisum.task.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import com.nisum.task.entity.Cities;
import com.nisum.task.repository.CityRepository;
import com.nisum.task.util.CustomAggregationOperation;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class CityService {
@Autowired
private CityRepository cityRepository;
@Autowired
private ReactiveMongoTemplate mongoTemplate;
public Flux<Cities> findAll() {
return cityRepository.findAll();
}
public Flux<Cities> getAllCities() {
AggregationOperation match = Aggregation.match(Criteria.where("continent").in("Asia", "North America"));
AggregationOperation group = Aggregation.group("$_id").first("$name").as("name");
AggregationOperation sort = Aggregation.sort(Sort.by(Collections.singletonList(Sort.Order.asc("name"))));
List<AggregationOperation> operations = new ArrayList<>();
operations.add(match);
operations.add(group);
operations.add(sort);
// operations.add(max);
Aggregation aggregation = Aggregation.newAggregation(operations);
Flux<Cities> allCities = mongoTemplate.aggregate(aggregation, Cities.class, Cities.class);
return allCities;
}
public Mono<Cities> createCity(Cities city) {
return cityRepository.save(city);
}
public Flux<Cities> citiesByPopulation() {
String query1 = "{$match:{'continent':{$in:['Europe','North America']}}},"
+ "{$group:{'_id':'$continent',population:{$sum:'$population'}}}," + "{$sort:{'population':-1}}";
TypedAggregation<Cities> aggregation = Aggregation.newAggregation(Cities.class,
new CustomAggregationOperation(query1));
Flux<Cities> allCities = mongoTemplate.aggregate(aggregation, Cities.class, Cities.class);
return allCities;
}
public Flux<Cities> sortByPopulation() {
return cityRepository.findMaxPopulation();
}
}
package com.nisum.task.service;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.nisum.task.entity.Employee;
import com.nisum.task.exception.EmployeeException;
import com.nisum.task.repository.EmployeeRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;
// @Autowired
// private MongoOperations mongoOperations;
public Mono<Employee> saveEmployee(Employee emp) throws EmployeeException {
System.out.println("IN Service");
return employeeRepository.save(emp);
}
public Mono<Employee> findById(Long employeeId) throws EmployeeException {
return employeeRepository.findById(employeeId);
}
public Flux<Employee> findAllEmployees() throws EmployeeException {
return employeeRepository.findAll();
}
public Flux<Employee> fetchEmployessBySalary() {
Query query = new Query().with(Sort.by(Collections.singletonList(Sort.Order.asc("firstName"))));
query.addCriteria(Criteria.where("salary").gte(30000));
return reactiveMongoTemplate.find(query, Employee.class);
}
public Mono<Employee> updateEmpBySalary(Long employeeId, Double salary) throws EmployeeException {
Query query = new Query(Criteria.where("id").is(employeeId));
Update update = new Update().set("salary", 1200);
Mono<Employee> emp = reactiveMongoTemplate.findAndModify(query, update, Employee.class);
return emp;
}
}
package com.nisum.task.service;
import java.util.Arrays;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mongodb.reactivestreams.client.AggregatePublisher;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.nisum.task.entity.Sales;
import com.nisum.task.repository.SalesRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class SalesService {
@Autowired
private SalesRepository salesRepository;
//@Autowired
//private ReactiveMongoTemplate mongoTemplate;
//@Autowired
//private MongoClient mongoClient;
public Mono<Sales> addSale(Sales sale) {
return salesRepository.save(sale);
}
public Mono<Sales> findById(Long saleId) {
return salesRepository.findById(saleId);
}
public Flux<Sales> findAllSales() {
return salesRepository.findAll();
}
public Flux<Document> searchByPurchaseModes(String purchaseMode, String location) {
MongoClient mongoClient = MongoClients
.create("mongodb+srv://sridharyadav589:9640037146@testcluster.bl9klfi.mongodb.net/test");
MongoDatabase database = mongoClient.getDatabase("sample_supplies");
MongoCollection<Document> collection = database.getCollection("sales");
// AggregatePublisher<Document> result = collection.aggregate(Arrays.asList(
// new Document("$search",
// new Document("index", "default")
// .append("text",
// new Document("query", "{\"purchaseMethod\":\"Online\"}")
// .append("path", new Document("wildcard", "*")))),
// new Document("$limit", 8L),
// new Document("$sort", new Document("storeLocation", 1L))));
AggregatePublisher<Document> result = collection
.aggregate(
Arrays.asList(
new Document("$search",
new Document("index", "default").append("text",
new Document("query",
"{\"purchaseMethod\":\"online\",\"storeLocation\":\"Denver\"}")
.append("path", new Document("wildcard", "*")))),
new Document("$limit", 10L)));
Flux<Document> list = Flux.from(result);
return list;
}
public Flux<Sales> findByPurchaseModeAndLocation(String mode,String location) {
return salesRepository.findByPurchaseMethodAndStoreLocation(mode,location);
}
}
package com.nisum.task.util;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
public class CustomAggregationOperation implements AggregationOperation {
private String jsonOperation;
public CustomAggregationOperation(String jsonOperation) {
this.jsonOperation = jsonOperation;
}
@Override
public org.bson.Document toDocument(AggregationOperationContext aggregationOperationContext) {
return aggregationOperationContext.getMappedObject(org.bson.Document.parse(jsonOperation));
}
}
package com.nisum.task.util;
public class EmployeeUtil {
}
#spring.data.mongodb.port=27017
#spring.data.mongodb.host=localhost
#spring.data.mongodb.host=mongodb+srv://sridharyadav589:9640037146@testcluster.bl9klfi.mongodb.net/test
#database.name= studentDB
#database.host = mongodb://localhost:27017/
#database.host = mongodb://localhost:27017/
#spring.main.web-application-type: reactive
#spring.main.allow-bean-definition-overriding=true
database.name= sample_supplies
database.host = mongodb+srv://sridharyadav589:9640037146@testcluster.bl9klfi.mongodb.net/test
#springdoc.swagger-ui.path=/swagger-doc/swagger-ui.html
#springdoc.api-docs.path=/swagger-doc/v3/api-docs
#spring.main.web-application-type=none
package com.nisum.task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
import com.nisum.task.controller.EmployeeController;
import com.nisum.task.entity.Employee;
import com.nisum.task.service.EmployeeService;
import static org.mockito.Mockito.times;
import static org.hamcrest.CoreMatchers.equalTo;
import reactor.core.publisher.Mono;
@RunWith(SpringRunner.class)
@WebFluxTest(controllers = EmployeeController.class)
//@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class EmployeeControllerTest
{
// @MockBean
//EmployeeRepository repository;
@MockBean
private EmployeeService employeeService;
@Autowired
private WebTestClient webClient;
@Test
public void testCreateEmployee() {
Employee employee = new Employee();
employee.setId(4L);
employee.setFirstName("Suresh");
employee.setLastName("L");
employee.setAge("40");
employee.setSalary(55000d);
Mockito.when(employeeService.saveEmployee(employee)).thenReturn(Mono.just(employee));
webClient.post()
.uri("/employee/saveEmployee")
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(employee))
.exchange()
.expectStatus().isOk();
Mockito.verify(employeeService,times(1)).saveEmployee(employee);
}
@Test
public void testGetEmployeeById()
{
webClient.get().uri("/employee/findById/{empId}", 1)
.exchange()
.expectStatus().isOk()
.expectBody(Employee.class)
.value(emp -> emp.getId(),equalTo(1l))
.value(emp -> emp.getFirstName(), equalTo("Sridhar"))
.value(emp -> emp.getLastName(), equalTo("P"))
.value(emp -> emp.getAge(), equalTo("28"))
.value(emp -> emp.getSalary(), equalTo("10"));
//Mockito.verify(employeeService,times(1)).findById(2L);
}
}
\ No newline at end of file
package com.nisum.task;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TaskApplicationTests {
@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