Commit 72216b67 authored by Prangshu Maity's avatar Prangshu Maity

commit the poc code

parents
/mvnw text eol=lf
*.cmd text eol=crlf
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
#
# http://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.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
This diff is collapsed.
<# : batch portion
@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 http://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 Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
<?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>3.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nisum</groupId>
<artifactId>BookInfo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BookInfo</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</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>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.asyncer</groupId>
<artifactId>r2dbc-mysql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<!--<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
&lt;!&ndash;<version>1.18.24</version>
<scope>provided</scope>&ndash;&gt;
</dependency>-->
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
<!--<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>-->
<!--<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.0</version> &lt;!&ndash; Use the latest version available &ndash;&gt;
</dependency>-->
<!--<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
<annotationProcessorPaths>
&lt;!&ndash;<annotationProcessorPath>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</annotationProcessorPath>&ndash;&gt;
</annotationProcessorPaths>
</configuration>
</plugin>-->
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
<configuration>
<includes>
<include>**/*Test.java</include> &lt;!&ndash; Customize test includes &ndash;&gt;
</includes>
<forkCount>1</forkCount> &lt;!&ndash; Control the number of forks used &ndash;&gt;
<reuseForks>false</reuseForks> &lt;!&ndash; Whether to reuse JVM fork &ndash;&gt;
</configuration>
</plugin>-->
</plugins>
</build>
</project>
package com.nisum.BookInfo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookInfoApplication {
public static void main(String[] args) {
SpringApplication.run(BookInfoApplication.class, args);
}
}
package com.nisum.BookInfo.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.r2dbc.core.DatabaseClient;
import javax.sql.DataSource;
import static io.r2dbc.spi.ConnectionFactoryOptions.*;
@Configuration
public class DataSourceConfiguration {
private final Logger log = LoggerFactory.getLogger(DataSourceConfiguration.class);
public static final String POOL = "pool";
public static final String MYSQL = "mysql";
@Bean
public DataSource createDataSource(DataSourceProperties dataSourceProperties) {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/test1");
hikariConfig.setUsername("root");
hikariConfig.setPassword("root");
return new HikariDataSource(hikariConfig);
}
@Bean
public DataSourceTransactionManager createTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public ConnectionFactory createConnectionFactory(DataSourceProperties dataSourceProperties) {
return ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(DRIVER, POOL)
.option(PROTOCOL, MYSQL)
.option(HOST, dataSourceProperties.getHostName())
.option(PORT, dataSourceProperties.getPort())
.option(USER, dataSourceProperties.getUserName())
.option(PASSWORD, dataSourceProperties.getPassword())
.option(DATABASE, dataSourceProperties.getDatabaseName())
.build());
}
public DatabaseClient createDataBaseClient(ConnectionFactory connectionFactory) {
return DatabaseClient.create(connectionFactory);
}
}
package com.nisum.BookInfo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("spring.r2dbc")
public class DataSourceProperties {
private String driverClassName;
private String hostName;
private Integer port;
private String databaseName;
private String url;
private String userName;
private String password;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "DataSourceProperties{" +
"driverClassName='" + driverClassName + '\'' +
", hostName='" + hostName + '\'' +
", port=" + port +
", databaseName='" + databaseName + '\'' +
", url='" + url + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
package com.nisum.BookInfo.controller;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.service.BookService;
import com.nisum.BookInfo.validator.CommonServiceValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/books")
public class BookController {
private static final Logger logger = LoggerFactory.getLogger(BookController.class);
@Autowired
public BookService bookService;
@Autowired
public CommonServiceValidator validator;
/* @Autowired
private ModelMapper modelMapper;
@PostMapping("/createBook")
public Mono<Book> create(@RequestBody Book book){
logger.info("CreateBook method called");
return bookService.create(book);
}
@GetMapping("/getAllBook")
public Flux<Book> getAllBook(){
logger.info("getAllBook method called");
return bookService.getAllBooks();
}
@GetMapping("/getSingleBook/{bookId}")
public Mono<Book> getSingleBook(@PathVariable Integer bookId){
logger.info("getSingleBook method called");
return bookService.getBook(bookId);
}
@PutMapping("/updateBook/{bookId}")
public Mono<Book> update(@RequestBody Book book,@PathVariable Integer bookId){
logger.info("update method called");
return bookService.updateBook(book,bookId);
}
@DeleteMapping("/deleteBook/{bookId}")
public Mono<Void> delete(@PathVariable Integer bookId){
logger.info("delete method called");
return bookService.deleteBook(bookId);
}
*/
// Create a new book
@PostMapping("/createBook")
public Mono<?> createBook(@RequestBody Mono<BookDto> bookDto) {
/* return bookService.saveBook(bookDto)
.map(rows -> "Book created successfully!");*/
return bookDto.doOnNext(bookbookDto -> logger.info("validating incoming Book data: {}", bookDto))
.flatMap(bookDto1 -> {
return validateBook(bookDto1)
.then(bookService.saveBook(bookDto1));
})
.map(ResponseEntity::ok)
.doOnError(error -> logger.error("Error while adding Book: {}", error.getMessage()));
}
// Get all books
@GetMapping("/getAllBook")
public Flux<Book> getAllBooks() {
//return bookService.getAllBooks();
return bookService.getAllBooks()
.doOnNext(employee -> logger.info("Processing Book data: {}", employee))
.doOnError(error -> logger.error("Error fetching Book: {}", error.getMessage()));
}
// Get a book by IDBookService
@GetMapping("/getBookById/{id}")
public Mono<?> getBookById(@PathVariable Integer id) {
// return bookService.getBookById(id);
return validator.isBookIdValid(id)
.flatMap(valid -> bookService.getBookById(id))
.map(ResponseEntity::ok)
.doOnError(error -> logger.error("Error fetching Book by ID: {}", error.getMessage()));
}
// Update a book by ID
@PutMapping("/updateBook/{id}")
public Mono<?> updateBook(@PathVariable Integer id, @RequestBody Mono<BookDto> bookDto) {
/* return bookService.updateBook(id, bookDto)
.map(rows -> "Book updated successfully!");*/
return validator.isBookIdValid(id)
.flatMap(valid -> bookDto
.flatMap(dto -> {
return validateBook(dto)
.then(bookService.updateBook(id, dto));
})
)
.map(ResponseEntity::ok)
.doOnError(error -> logger.error("Error updating Book: {}", error.getMessage()));
}
// Delete a book by ID
@DeleteMapping("/deleteBookById/{id}")
public Mono<?> deleteBook(@PathVariable Integer id) {
/* return bookService.deleteBook(id)
.map(rows -> "Book deleted successfully!");*/
return validator.isBookIdValid(id)
.flatMap(valid -> bookService.deleteBook(id))
.thenReturn(ResponseEntity.ok().build())
.doOnError(error -> logger.error("Error deleting Book: {}", error.getMessage()));
}
private Mono<Void> validateBook(BookDto bookDto) {
return validator.isBookIdValid(bookDto.getBookId())
.then(validator.isBookNameValid(bookDto.getName()))
.then();
}
}
package com.nisum.BookInfo.dao;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.exception.BookNotFoundException;
import com.nisum.BookInfo.util.AppErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Repository
public class BookDao {
@Autowired
private DatabaseClient databaseClient;
public Mono<Book> saveBook(Book book) {
return databaseClient
.sql("INSERT INTO book_details (book_id, book_name,book_desc,book_publiser,book_author) VALUES (:bookId, :name,:desc,:publiser,:author)")
.bind("bookId", book.getBookId())
.bind("name", book.getName())
.bind("desc", book.getDesc())
.bind("publiser", book.getPubliser())
.bind("author", book.getAuthor())
.fetch()
.rowsUpdated().flatMap(rows ->
{
if (rows > 0) {
return Mono.just(book); //Returning the saved employee
} else {
return Mono.error(new BookNotFoundException(AppErrorCode.BOOK_NOT_FOUND,"Data Invalid") {
});
}
});
}
public Flux<Book> getAllBooks() {
return databaseClient
.sql("SELECT book_id, book_name, book_desc, book_publiser,book_author FROM book_details")
.map((row, metadata) -> new Book(
row.get("book_id", Integer.class),
row.get("book_name", String.class),
row.get("book_desc", String.class),
row.get("book_publiser", String.class),
row.get("book_author", String.class)
))
.all(); // Returns Flux<Book> for all books
}
public Mono<Book> getBookById(Integer id) {
return databaseClient
.sql("SELECT book_id, book_name, book_desc, book_publiser,book_author FROM book_details WHERE book_id = :book_id")
.bind("book_id", id)
.map((row, metadata) -> new Book(
row.get("book_id", Integer.class),
row.get("book_name", String.class),
row.get("book_desc", String.class),
row.get("book_publiser", String.class),
row.get("book_author", String.class)
))
.one(); // Returns Mono<Book> for a single book or empty if not found
}
// Update a book
public Mono<Book> updateBook(Integer bookId, Book book) {
return databaseClient
.sql("UPDATE book_details SET book_author = :author, book_name = :name WHERE book_id = :id")
.bind("id", bookId)
.bind("name", book.getAuthor())
//.bind("desc", book.getDesc())
//.bind("publiser", book.getPubliser())
.bind("author", book.getAuthor())
.fetch()
.rowsUpdated().
flatMap(rows ->
{
if (rows > 0) {
return Mono.just(book); //Returning the saved employee
} else {
return Mono.error(new BookNotFoundException(AppErrorCode.BOOK_UPDATE_FAILED,"UPDATE OF BOOK NOT POSSIBLE") {
}
);
}
});
}
public Mono<Void> deleteBook(Integer id) {
return databaseClient.sql("DELETE FROM book_details WHERE book_id = :id")
.bind("id", id)
.fetch()
.rowsUpdated().
flatMap(rows ->
{
if (rows > 0) {
return Mono.empty();
} else {
return Mono.error(new BookNotFoundException(AppErrorCode.BOOK_DELETION_FAILED,"Invalid Book data") {
}
);
}
});
}
}
package com.nisum.BookInfo.dto;
import org.springframework.data.relational.core.mapping.Column;
/*@Data
@Getter*/
public class BookDto {
private Integer bookId;
private String name;
private String desc;
private String publiser;
private String author;
public BookDto(Integer bookId, String name, String desc, String publiser, String author) {
this.bookId = bookId;
this.name = name;
this.desc = desc;
this.publiser = publiser;
this.author = author;
}
public BookDto() {
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubliser() {
return publiser;
}
public void setPubliser(String publiser) {
this.publiser = publiser;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
package com.nisum.BookInfo.dto;
//@Data
/*@Builder
@Getter*/
public class ErrorResponseDto {
private String errorCode;
private String errorMessage;
public ErrorResponseDto(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public ErrorResponseDto() {
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
package com.nisum.BookInfo.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
/*@Data
@AllArgsConstructor
@NoArgsConstructor*/
@Table("book_details")
public class Book {
@Id
@Column("book_id")
private Integer bookId;
@Column("book_name")
private String name;
@Column("book_desc")
private String desc;
@Column("book_publiser")
private String publiser;
@Column("book_author")
private String author;
public Book(Integer bookId, String name, String desc, String publiser, String author) {
this.bookId = bookId;
this.name = name;
this.desc = desc;
this.publiser = publiser;
this.author = author;
}
public Book() {
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubliser() {
return publiser;
}
public void setPubliser(String publiser) {
this.publiser = publiser;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
package com.nisum.BookInfo.exception;
import com.nisum.BookInfo.util.AppErrorCode;
public class BookNotFoundException extends RuntimeException{
private AppErrorCode errorCode;
public BookNotFoundException() {
}
public BookNotFoundException(AppErrorCode errorCode,String message) {
super(message);
this.errorCode=errorCode;
}
public AppErrorCode getErrorCode() {
return errorCode;
}
}
package com.nisum.BookInfo.exception;
import com.nisum.BookInfo.util.AppErrorCode;
public class BookValidationException extends RuntimeException{
private AppErrorCode errorCode;
public BookValidationException() {
}
public BookValidationException(AppErrorCode errorCode,String message) {
super(message);
this.errorCode=errorCode;
}
public AppErrorCode getErrorCode() {
return errorCode;
}
/* private final AppErrorCode errorCode;
public BookValidationException(AppErrorCode errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public AppErrorCode getErrorCode() {
return errorCode;
}
*/
}
package com.nisum.BookInfo.globalexception;
import com.nisum.BookInfo.dto.ErrorResponseDto;
import com.nisum.BookInfo.exception.BookNotFoundException;
import com.nisum.BookInfo.exception.BookValidationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class BookAdviceController {
@ExceptionHandler(BookNotFoundException.class)
public ErrorResponseDto handleBookNotFoundException(BookNotFoundException bookNotFoundException){
/*return ErrorResponseDto.builder().errorCode(String.valueOf(HttpStatus.NOT_FOUND))
.errorMessage(bookNotFoundException.getMessage()).build();*/
/* return ErrorResponseDto.builder().errorCode(bookNotFoundException.getErrorCode().getString())
.errorMessage(bookNotFoundException.getMessage()) .build();*/
ErrorResponseDto errorResponseDto=new ErrorResponseDto();
errorResponseDto.setErrorCode(bookNotFoundException.getErrorCode().getString());
errorResponseDto.setErrorMessage(bookNotFoundException.getMessage());
return errorResponseDto;
}
@ExceptionHandler(BookValidationException.class)
public ErrorResponseDto handleBookValidationException(BookValidationException bookValidationException){
/* return ErrorResponseDto.builder().errorCode(bookValidationException.getErrorCode().getString())
.errorMessage(bookValidationException.getMessage()).build();*/
ErrorResponseDto errorResponseDto=new ErrorResponseDto();
errorResponseDto.setErrorCode(bookValidationException.getErrorCode().getString());
errorResponseDto.setErrorMessage(bookValidationException.getMessage());
return errorResponseDto;
}
}
package com.nisum.BookInfo.mapper;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
public class BookMapper {
@Autowired
private BookDto bookDto;
public static Book toEntity(BookDto dto) {
Book book = new Book();
book.setBookId(dto.getBookId());
book.setName(dto.getName());
book.setAuthor(dto.getAuthor());
book.setDesc(dto.getDesc());
book.setPubliser(dto.getPubliser());
return book;
}
public static BookDto toDto(Book book) {
BookDto dto = new BookDto();
dto.setBookId(book.getBookId());
dto.setName(book.getName());
dto.setAuthor(book.getAuthor());
dto.setDesc(book.getDesc());
dto.setPubliser(book.getPubliser());
return dto;
}
}
package com.nisum.BookInfo.repository;
import com.nisum.BookInfo.entity.Book;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
/*@Repository
public interface BookRepo extends ReactiveCrudRepository <Book,Integer>{
}*/
package com.nisum.BookInfo.service;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import org.springframework.web.bind.annotation.PathVariable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface BookService {
/* public Mono<Book> create(Book book);
public Flux<Book> getAllBooks();
public Mono<Book> getBook(Integer bookId);
public Mono<Book> updateBook(Book book,Integer bookId);
public Mono<Void> deleteBook(Integer bookId);
*/
Mono<Book> saveBook(BookDto bookDto) ;
// Get all books
public Flux<Book> getAllBooks();
// Get a book by ID
public Mono<Book> getBookById(Integer id) ;
// Update a book
public Mono<Book> updateBook(Integer id, BookDto bookDto);
public Mono<Void> deleteBook(@PathVariable Integer id) ;
}
package com.nisum.BookInfo.service;
import com.nisum.BookInfo.dao.BookDao;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class BookServiceImpl implements BookService{
// @Autowired
// private BookRepo bookRepo;
@Autowired
private BookDao bookDao;
/* @Autowired
private ModelMapper modelMapper;*/
//saveBook
public Mono<Book> saveBook(BookDto bookDto) {
// Book book= modelMapper.map(bookDto,Book.class); //mapper for BookDto to book
Book book= BookMapper.toEntity(bookDto);
return bookDao.saveBook(book);
}
// Get all books
public Flux<Book> getAllBooks() {
return bookDao.getAllBooks();
}
// Get a book by ID
public Mono<Book> getBookById(Integer id) {
return bookDao.getBookById(id);
}
// Update a book
public Mono<Book> updateBook(Integer bookId, BookDto bookDto) {
// Book book= modelMapper.map(bookDto,Book.class); //mapper for BookDto to book
Book book= BookMapper.toEntity(bookDto);
return bookDao.updateBook(bookId,book);
}
public Mono<Void> deleteBook(Integer id) {
return bookDao.deleteBook(id);
}
}
package com.nisum.BookInfo.util;
import com.fasterxml.jackson.annotation.JsonValue;
public enum AppErrorCode {
BOOK_NOT_FOUND("BOOK_404"),
INVALID_BOOK_DATA("BOOK_400"),
BOOK_CREATION_FAILED("BOOK_500"),
BOOK_UPDATE_FAILED("BOOK_500"),
BOOK_DELETION_FAILED("BOOK_500"),
GENERAL_ERROR("BOOK_500");
private final String errorCode;
// Constructor
private AppErrorCode(String errorCode) {
this.errorCode = errorCode;
}
// Method to return the error code as a string
@JsonValue
public String getString() {
return this.errorCode;
}
}
package com.nisum.BookInfo.validator;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.exception.BookNotFoundException;
import com.nisum.BookInfo.exception.BookValidationException;
import com.nisum.BookInfo.util.AppErrorCode;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
@Component
public class CommonServiceValidator {
//bookId is invalid
public Mono<Boolean> isBookIdValid(Integer id) {
if (id != null) {
return Mono.just(true);
}
return Mono.error(new BookValidationException(AppErrorCode.INVALID_BOOK_DATA, "Book ID cannot be null"));
}
// Validate if Book name is not null or empty
public Mono<Boolean> isBookNameValid(String name) {
if (name != null && !name.trim().isEmpty()) {
return Mono.just(true);
}
return Mono.error(new BookValidationException(AppErrorCode.INVALID_BOOK_DATA ,"Book name cannot be empty or null"));
}
public Mono<Boolean> isBookPubliserValid(String publiserName) {
if (publiserName != null && !publiserName.trim().isEmpty()) {
return Mono.just(true);
}
return Mono.error(new BookNotFoundException(AppErrorCode.BOOK_CREATION_FAILED ,"Not an valid publiser"));
}
public Mono<Boolean> isBookObjectValid(Book book) {
if (book == null) {
return Mono.error(new BookNotFoundException(AppErrorCode.BOOK_NOT_FOUND, "Book object cannot be null"));
}
return isBookIdValid(book.getBookId())
.flatMap(valid -> isBookNameValid(book.getName()));
}
}
#spring.application.name=BookInfo
#
#
#server.port=8081
#spring.r2dbc.url=r2dbc:mysql://localhost:3306/test1
#spring.r2dbc.username=root
#spring.r2dbc.password=root
#spring.r2dbc.driver=mysql
\ No newline at end of file
spring:
r2dbc:
driverClassName: mysql
hostName: localhost
port: 3306
databaseName: test1
url: r2dbc:mysql://localhost:3306/test1
username: root
password: root
\ No newline at end of file
package com.nisum.BookInfo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BookInfoApplicationTests {
@Test
void contextLoads() {
}
}
package com.nisum.BookInfo.controller;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.mapper.BookMapper;
import com.nisum.BookInfo.service.BookService;
import com.nisum.BookInfo.validator.CommonServiceValidator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.client.MockMvcWebTestClient.bindToController;
@SpringBootTest
class BookControllerTest {
@Mock
private BookService bookService; // Mock the BookService
@Mock
private CommonServiceValidator validatorService; // Mock ValidatorService for book validation
@InjectMocks
private BookController bookController; // The controller under test
/* private BookDto validBookDto;
private Book savedBook;*/
@BeforeEach
public void setUp() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
//when(bookDao.saveBook(any(Book.class))).thenReturn(Mono.just(book));
MockitoAnnotations.openMocks(this);
}
@Test
public void createBook_shouldReturnSuccess_whenBookIsValid() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
// Mock the validateBook() and saveBook() methods
when(validatorService.isBookIdValid(bookDto.getBookId())).thenReturn(Mono.just(true)); // Validation passes
when(validatorService.isBookNameValid(bookDto.getName())).thenReturn(Mono.just(true));
when(bookService.saveBook(bookDto)).thenReturn(Mono.just(book)); // Return saved book
// Directly call the controller method (createBook) with the valid BookDto
Mono<?> result = bookController.createBook(Mono.just(bookDto));
// Use StepVerifier to check the result
StepVerifier.create(result)
.expectNextMatches(response -> {
// Assert that the response is a ResponseEntity with the expected message
assertTrue(response instanceof ResponseEntity);
ResponseEntity<?> responseEntity = (ResponseEntity<?>) response;
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
return true;
})
.verifyComplete(); // Ensure the Mono completes without error
}
@Test
public void createBook_shouldReturnError_whenValidationFails() {
// Given: Create an invalid BookDto (for validation failure)
BookDto invalidBookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
when(validatorService.isBookIdValid(invalidBookDto.getBookId())).thenReturn(Mono.just(true)); // Validation passes
when(validatorService.isBookNameValid(invalidBookDto.getName())).thenReturn(Mono.just(true));
// Simulate a validation failure (Mono.error)
when(bookService.saveBook(invalidBookDto)).thenReturn(Mono.error(new IllegalArgumentException("Invalid publiser data")));
// Directly call the controller method with invalid BookDto
Mono<?> result = bookController.createBook(Mono.just(invalidBookDto));
// Use StepVerifier to verify that the error is propagated
StepVerifier.create(result)
.expectError(IllegalArgumentException.class) // Expect the error thrown by validation
.verify();
}
//for update case
@Test
void updateBook_ShouldReturnUpdatedBook_WhenIdIsValid() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
// Mock the validateBook() and saveBook() methods
when(validatorService.isBookIdValid(bookDto.getBookId())).thenReturn(Mono.just(true)); // Validation passes
when(validatorService.isBookNameValid(bookDto.getName())).thenReturn(Mono.just(true));
when(bookService.updateBook(any(Integer.class), any(BookDto.class))).thenReturn(Mono.just(book));
// Make a test call to the controller method
Mono<?> result = bookController.updateBook(1, Mono.just(bookDto));
// StepVerifier to test the result
StepVerifier.create(result)
.expectNextMatches(response -> {
// Assert that the response is a ResponseEntity with the expected message
assertTrue(response instanceof ResponseEntity);
ResponseEntity<?> responseEntity = (ResponseEntity<?>) response;
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
return true;
})
.verifyComplete(); //
}
//for getAllBook
@Test
void getAllBooks_ShouldReturnListOfBooks() {
Book book1 = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
Book book2 = new Book(2, "Java", "This is Java", "Java publiser", "Test Java Author");
when(bookService.getAllBooks()).thenReturn(Flux.just(book1, book2));
// Call the controller method
Flux<Book> result = bookController.getAllBooks();
// Verify the response using StepVerifier
StepVerifier.create(result).
expectNextMatches(book -> book.getBookId().equals(1))
. expectNextMatches(book -> book.getBookId().equals(2))
.verifyComplete(); //
}
//get single book
@Test
void getBookById_ShouldReturnBookWithStatusOk() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
when(validatorService.isBookIdValid(bookDto.getBookId())).thenReturn(Mono.just(true)); // Validation passes
when(validatorService.isBookNameValid(bookDto.getName())).thenReturn(Mono.just(true));
when(bookService.getBookById(1)).thenReturn(Mono.just(book));
// Call the controller method
Mono<?> result = bookController.getBookById(1);
// Verify the response using StepVerifier
StepVerifier.create(result)
.expectNextMatches(response -> {
// Assert that the response is a ResponseEntity with the expected message
assertTrue(response instanceof ResponseEntity);
ResponseEntity<?> responseEntity = (ResponseEntity<?>) response;
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
return true;
})
.verifyComplete(); //
}
//delete
@Test
void deleteBook_ShouldReturnOkWhenDeletedSuccessfully() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
when(validatorService.isBookIdValid(bookDto.getBookId())).thenReturn(Mono.just(true)); // Validation passes
when(validatorService.isBookNameValid(bookDto.getName())).thenReturn(Mono.just(true));
when(bookService.deleteBook(1)).thenReturn(Mono.empty());
// Call the controller method
Mono<?> result = bookController.deleteBook(1);
// Verify the response using StepVerifier
StepVerifier.create(result)
.expectNextMatches(response -> {
// Assert that the response is a ResponseEntity with the expected message
assertTrue(response instanceof ResponseEntity);
ResponseEntity<?> responseEntity = (ResponseEntity<?>) response;
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
return true;
})
.verifyComplete(); //
}
}
package com.nisum.BookInfo.dao;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import com.nisum.BookInfo.service.BookService;
import com.nisum.BookInfo.service.BookServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.mockito.Mockito.*;
@SpringBootTest
class BookDaoTest {
@Mock
private DatabaseClient databaseClient;
@InjectMocks
private BookServiceImpl bookService;
//private Book book;
@BeforeEach
public void setUp() {
// book = new Book(1, "Java Book", "A test description", "Test Publisher", "Test Author");
// BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
// Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
}
@Test
public void testSaveBook_Success() {
BookDto bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
Book book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
DatabaseClient.GenericExecuteSpec executeSpec = mock(DatabaseClient.GenericExecuteSpec.class);
when(databaseClient.sql("INSERT INTO book_details (book_id, book_name, book_desc, book_publiser, book_author) VALUES (:bookId, :name, :desc, :publiser, :author)"))
.thenReturn(executeSpec);
when(executeSpec.bind(1, bookDto.getBookId())).thenReturn(executeSpec);
when(executeSpec.bind("C++", bookDto.getName())).thenReturn(executeSpec);
when(executeSpec.bind("This is c++", bookDto.getDesc())).thenReturn(executeSpec);
when(executeSpec.bind("C publiser", bookDto.getPubliser())).thenReturn(executeSpec);
when(executeSpec.bind("Test Author", bookDto.getAuthor())).thenReturn(executeSpec);
// Call the saveBook method
Mono<Book> result = bookService.saveBook(bookDto);
StepVerifier.create(result)
.expectNext(book) // Expect the book to be returned after saving
.verifyComplete(); // The Mono should complete successfully
}
}
package com.nisum.BookInfo.service;
import com.nisum.BookInfo.dao.BookDao;
import com.nisum.BookInfo.dto.BookDto;
import com.nisum.BookInfo.entity.Book;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
class BookServiceImplTest {
@Mock
private BookDao bookDao; // Mock the BookDao
@InjectMocks
private BookServiceImpl bookService; // Service under test
private BookDto bookDto;
private Book book;
@BeforeEach
public void setUp() {
// Set up test data
bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
//when(bookDao.saveBook(any(Book.class))).thenReturn(Mono.just(book));
MockitoAnnotations.openMocks(this);
}
@Test
public void saveBook_shouldSaveBookAndReturnMonoBook() {
// Call the saveBook method of the service
when(bookDao.saveBook(any(Book.class))).thenReturn(Mono.just(book));
Mono<Book> result = bookService.saveBook(bookDto);
// Verify the result using StepVerifier (for reactive streams)
StepVerifier.create(result)
.expectNextMatches(savedBook -> {
// Assert the values in the saved Book are as expected
assertEquals("C++", savedBook.getName());
assertEquals("Test Author", savedBook.getAuthor());
assertEquals("C publiser", savedBook.getPubliser());
return true;
})
.verifyComplete();
// Verify that bookDao.saveBook was called exactly once
verify(bookDao, times(1)).saveBook(any(Book.class));
}
@Test
public void getAllBooks_shouldReturnFluxOfBooks() {
// Prepare a Flux of books for testing
Book book1 = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
Book book2 = new Book(2, "Java", "This is c++", "C publiser", "Test Author");
Flux<Book> bookFlux = Flux.just(book1, book2);
// Mock the getAllBooks method to return the Flux of books
when(bookDao.getAllBooks()).thenReturn(bookFlux);
Flux<Book> result = bookService.getAllBooks();
// Verify the result using StepVerifier (for reactive streams)
StepVerifier.create(result)
.expectNextMatches(book -> book.getName().equals("C++"))
.expectNextMatches(book -> book.getName().equals("Java"))
.verifyComplete();
// Verify that bookDao.getAllBooks was called exactly once
verify(bookDao, times(1)).getAllBooks();
}
@Test
public void getBookById_shouldReturnBook_whenBookExists() {
//Setup
int bookId = 1;
book = new Book(bookId, "C++", "This is c++", "C publiser", "Test Author");
// Mock the getBookById method to return the expected Mono<Book>
when(bookDao.getBookById(bookId)).thenReturn(Mono.just(book));
//setupend
// Call the getBookById method of the service
Mono<Book> result = bookService.getBookById(bookId);
// Verify the result using StepVerifier (for reactive streams)
StepVerifier.create(result)
.expectNextMatches(savedBook -> {
// Assert the book details
assertEquals(bookId, savedBook.getBookId());
assertEquals("C++", savedBook.getName());
assertEquals("Test Author", savedBook.getAuthor());
assertEquals("C publiser", savedBook.getPubliser());
return true;
})
.verifyComplete();
// Verify that bookDao.getBookById was called exactly once
verify(bookDao, times(1)).getBookById(bookId);
}
@Test
public void getBookById_shouldReturnEmpty_whenBookDoesNotExist() {
//setup
int bookId = 1;
book = new Book(bookId, "C++", "This is c++", "C publiser", "Test Author");
// Mock the getBookById method to return the expected Mono<Book>
when(bookDao.getBookById(bookId)).thenReturn(Mono.just(book));
//setupend
// Mock the DAO method to return an empty Mono when no book is found
when(bookDao.getBookById(999)).thenReturn(Mono.empty());
// Call the getBookById method with a non-existent ID
Mono<Book> result = bookService.getBookById(999);
// Verify the result is empty (no book found)
StepVerifier.create(result)
.expectComplete() // Should complete without emitting anything
.verify();
// Verify that bookDao.getBookById was called exactly once
verify(bookDao, times(1)).getBookById(999);
}
@Test
public void updateBook_shouldReturnUpdatedBook_whenBookExists() {
int bookId = 1;
bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
// Mock the DAO method to return the updated book
when(bookDao.updateBook(eq(bookId), any(Book.class))).thenReturn(Mono.just(book));
// Call the updateBook method of the service
Mono<Book> result = bookService.updateBook(bookId, bookDto);
// Verify the result using StepVerifier
StepVerifier.create(result)
.expectNextMatches(updatedBook -> {
// Assert that the book is updated with the correct fields
assertEquals(bookId, updatedBook.getBookId());
assertEquals("C++", updatedBook.getName());
assertEquals("Test Author", updatedBook.getAuthor());
assertEquals("C publiser", updatedBook.getPubliser());
return true;
})
.verifyComplete();
// Verify that bookDao.updateBook was called with the correct bookId and book
verify(bookDao, times(1)).updateBook(eq(bookId), any(Book.class));
}
@Test
public void updateBook_shouldReturnEmpty_whenBookDoesNotExist() {
int bookId = 1;
bookDto = new BookDto(1, "C++", "This is c++", "C publiser", "Test Author");
book = new Book(1, "C++", "This is c++", "C publiser", "Test Author");
// Mock the DAO method to return an empty Mono (book not found)
when(bookDao.updateBook(eq(999), any(Book.class))).thenReturn(Mono.empty());
// Call the updateBook method with a non-existent bookId
Mono<Book> result = bookService.updateBook(999, bookDto);
// Verify that the result is empty (no book found to update)
StepVerifier.create(result)
.expectComplete() // Should complete without emitting anything
.verify();
// Verify that bookDao.updateBook was called with the non-existent bookId
verify(bookDao, times(1)).updateBook(eq(999), any(Book.class));
}
@Test
public void deleteBook_shouldCompleteSuccessfully_whenBookExists() {
int bookId = 1;
// Mock the DAO method to simulate successful deletion
when(bookDao.deleteBook(bookId)).thenReturn(Mono.empty());
// Call the deleteBook method of the service
Mono<Void> result = bookService.deleteBook(bookId);
// Verify the result using StepVerifier
StepVerifier.create(result)
.verifyComplete(); // Should complete without emitting anything
// Verify that bookDao.deleteBook was called exactly once with the correct bookId
verify(bookDao, times(1)).deleteBook(bookId);
}
@Test
public void deleteBook_shouldCompleteSuccessfully_whenBookDoesNotExist() {
int bookId = 1;
// Mock the DAO method to simulate a case where no book is found
when(bookDao.deleteBook(999)).thenReturn(Mono.empty());
// Call the deleteBook method with a non-existent bookId
Mono<Void> result = bookService.deleteBook(999);
// Verify that the result completes without emitting any value (book not found)
StepVerifier.create(result)
.verifyComplete(); // Should complete without emitting anything
// Verify that bookDao.deleteBook was called exactly once with the non-existent bookId
verify(bookDao, times(1)).deleteBook(999);
}
}
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