0% found this document useful (0 votes)
23 views13 pages

EXPERIMENT11 Ejava

Uploaded by

o8799621
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views13 pages

EXPERIMENT11 Ejava

Uploaded by

o8799621
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

EXPERIMENT -11

AIM OF THE EXPERIMENT: Spring Boot Book Inventory System.

Create a basic book inventory system using Spring Boot to help a small library
manage itsbook collection. The system should allow librarians to add new books,
update existing book details, remove books from inventory, and search for books
by title, author, or category.

Code
configure

package [Link];

import [Link];
import [Link]; import
[Link];
import [Link];
import [Link].log4j.Log4j2;
import [Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];
import [Link]; import
[Link];
import [Link]; import
[Link]; import
[Link];

/**
* Common Exception Handler
*
* @author Dhiraj
*/
@ControllerAdvice
@Log4j2
public class GenericExceptionHandler extends ResponseEntityExceptionHandler {

@NonNull
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
@NonNull HttpHeaders headers,
@NonNull HttpStatus status,
@NonNull WebRequest request) {
[Link]("handleMethodArgumentNotValid():{} -> {}", [Link](), [Link]());
BindingResult bindingResult = [Link]();
String description = [Link]().stream()
.map(
objectError ->
[Link](" : ", [Link](), [Link]()))
.collect([Link](", ")); ErrorDTO
err =
[Link]()
.error("invalid_input")
.error_description(description)
.status(HttpStatus.BAD_REQUEST.value())
.timestamp([Link]())
.build();
return [Link]().body(err);
}

@NonNull
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex,
Object body,
@NonNull HttpHeaders headers,
HttpStatus status,
@NonNull WebRequest request) {
[Link]("handleExceptionInternal():{} -> {}", [Link](), ex);
ErrorDTO err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status([Link]())
.timestamp([Link]())
.build();
return [Link](status).body(err);
}

@ExceptionHandler({[Link]})
private ResponseEntity<ErrorDTO> handleGeneric(GenericException ex) { [Link](
"handleGeneric():{} -> {} : status: {}", [Link](), [Link](), [Link]());
ErrorDTO err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status([Link]())
.timestamp([Link]())
.build();
return [Link]([Link]()).body(err);
}

@ExceptionHandler({[Link]}) private
ResponseEntity<ErrorDTO>
handleIllegalArgumentException(IllegalArgumentException ex) { ErrorDTO
err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status(HttpStatus.BAD_REQUEST.value())
.timestamp([Link]())
.build();
return [Link]().body(err);
}

@ExceptionHandler({[Link]})
private ResponseEntity<ErrorDTO> handleException(Exception ex) {
[Link]("handleException():", ex);
ErrorDTO err =
[Link]()
.error("server_error")
.error_description("Something went wrong")
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.timestamp([Link]())
.build();
return [Link](HttpStatus.INTERNAL_SERVER_ERROR).body(err);
}
}
[Link]
package [Link];

import [Link];
import [Link]; import
[Link];
import [Link]; import
[Link]; import
[Link] er;
import [Link]; import
[Link] ilter;
/**
* Security Configuration to protect from non internal calls
*
* @author Dhiraj
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${[Link]}") private
String clientKey;

@Override
protected void configure(HttpSecurity http) throws Exception {

AbstractPreAuthenticatedProcessingFilter filter = getApiAuthenticatingFilter();

[Link]()
.disable()
.addFilter(filter)
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy([Link])
.and()
.formLogin()
.disable();
}

private AbstractPreAuthenticatedProcessingFilter getApiAuthenticatingFilter() {


AbstractPreAuthenticatedProcessingFilter filter =
new AbstractPreAuthenticatedProcessingFilter() {
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return
[Link]("lms-key");
}

@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { return
"";
}
};
[Link]( aut
hentication -> {
Object principal = [Link]();
if (clientKey == null || ![Link](principal)) { throw new
BadCredentialsException("Invalid Api Key");
}
[Link](true); return
authentication;
});
return filter;
}
}
Book Inventory Management

Control
package [Link];

import [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link];
import [Link]; import
[Link].slf4j.Slf4j;
import [Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];
import [Link]; import
[Link]; import
[Link]; import
[Link];

/**
* REST controller for Auth Service
*
* @author Dhiraj
*/
@RestController
@RequestMapping("/v1")
@RequiredArgsConstructor @Slf4j
public class AuthController {
private final AuthService authService;

@PostMapping(
value = "/token/authenticate",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AuthResponseDTO> authenticateUser(
@RequestBody @Valid AuthRequestDTO authDTO) throws GenericException {
[Link]("Authenticating............");
AuthResponseDTO authenticate = [Link](authDTO);
[Link]("Authenticated : {}", authenticate);
return [Link]().body(authenticate);
}

@PostMapping(
value = "/token/verify",
produces = MediaType.APPLICATION_JSON_VALUE, consumes =
MediaType.APPLICATION_JSON_VALUE) public
ResponseEntity<AuthResponseDTO> verifyToken(
@RequestHeader(value = [Link]) String token) throws GenericException {
[Link]("Verification token {} ", token);
[Link](token, "token cannot be null");
if([Link]("Bearer ")){
token = [Link](7);
}else{
throw new IllegalArgumentException("Bearer token missing");
}
return [Link]([Link](token));
}
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link rel="icon" href="<%= BASE_URL %>[Link]" />
<title>LMS</title>
<link
rel="stylesheet"
href="[Link]
/>
<link
rel="stylesheet"
href="[Link]
/>
</head>
<body>
<noscript>
<strong
>We're sorry but Library Management System doesn't work properly without JavaScript
enabled. Please enable it to continue.</strong
>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
Model
package [Link];

import [Link];
import [Link];
import [Link]; import
[Link];
import [Link];
import [Link].log4j.Log4j2;
import [Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];
import [Link]; import
[Link];
import [Link]; import
[Link]; import
[Link];

/**
* Common Exception Handler
*
* @author Dhiraj
*/
@ControllerAdvice
@Log4j2
public class GenericExceptionHandler extends ResponseEntityExceptionHandler { @NonNull

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
@NonNull HttpHeaders headers,
@NonNull HttpStatus status,
@NonNull WebRequest request) {
[Link]("handleMethodArgumentNotValid():{} -> {}", [Link](), [Link]());
BindingResult bindingResult = [Link]();
String description = [Link]().stream()
.map(
objectError ->
[Link](" : ", [Link](), [Link]()))
.collect([Link](", ")); ErrorDTO
err =
[Link]()
.error("invalid_input")
.error_description(description)
.status(HttpStatus.BAD_REQUEST.value())
.timestamp([Link]())
.build();
return [Link]().body(err);
}

@NonNull
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex,
Object body,
@NonNull HttpHeaders headers,
HttpStatus status,
@NonNull WebRequest request) {
[Link]("handleExceptionInternal():{} -> {}", [Link](), ex);
ErrorDTO err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status([Link]())
.timestamp([Link]())
.build();
return [Link](status).body(err);
}

@ExceptionHandler({[Link]})
private ResponseEntity<ErrorDTO> handleInventoryNotFound(Exception ex) {
[Link]("handleNotFound():{} -> {}", [Link](), [Link]()); ErrorDTO err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status(HttpStatus.NOT_FOUND.value())
.timestamp([Link]())
.build();
return [Link](HttpStatus.NOT_FOUND).body(err);
}

@ExceptionHandler({[Link]})
private ResponseEntity<ErrorDTO> handleGeneric(GenericException ex) { [Link](
"handleGeneric():{} -> {} : status: {}", [Link](), [Link](), [Link]());
ErrorDTO err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status([Link]())
.timestamp([Link]())
.build();
return [Link]([Link]()).body(err);
}

@ExceptionHandler({[Link]}) private
ResponseEntity<ErrorDTO>
handleIllegalArgumentException(IllegalArgumentException ex) { ErrorDTO
err =
[Link]()
.error("invalid_request")
.error_description([Link]())
.status(HttpStatus.BAD_REQUEST.value())
.timestamp([Link]())
.build();
return [Link]().body(err);
}

@ExceptionHandler({[Link]})
private ResponseEntity<ErrorDTO> handleException(Exception ex) {
[Link]("handleException()", ex);
ErrorDTO err =
[Link]()
.error("server_error")
.error_description("Something went wrong")
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.timestamp([Link]())
.build();
return [Link](HttpStatus.INTERNAL_SERVER_ERROR).body(err);
}
}

Book Inventory Management


Services
package [Link];

import [Link]; import


[Link];
import [Link]; import
[Link];

/**
* Service for {@link InventoryDTO}
*
* @author Dhiraj
*/
public interface InventoryService {

/**
* Find all inventory details by book id
*
* @param bookId -
* @return List of inventory for existing book id
*/
List<InventoryDTO> findAllBook(Long bookId);

/**
* Check if any book reference for a book id is available in LMS If yes mark the first book as
* unavailable and return the marked book
*
* @param bookId -
* @return first available book
* @throws InventoryNotFoundException if none of the books are available for a book id
*/
InventoryDTO orderBookIfAvailable(Long bookId) throws InventoryNotFoundException;

/**
* Mark the book with corresponding reference as available in inventory
*
* @param bookId -
* @param bookReferenceId -
* @return true if book is present in LMS and marking the book as available was successful
*/
boolean returnBook(Long bookId, String bookReferenceId);

/**
* Count of books available
*
* @param bookId -
* @return total number of book available for requested book id
*/
long getAvailableCount(Long bookId);

/**
* Add {@literal 'count'} number of books. Generates unique reference number for each book
*
* @param inventory DTO containing the book id , isbn , category for the new book
* @param count total inventory to add
* @throws GenericException if a book with combination of book id and book reference is already
* present
*/
List<InventoryDTO> add(InventoryDTO inventory, Integer count) throws GenericException;

/**
* Delete an inventory of all books by book id
*
* @param bookId -
* @throws InventoryNotFoundException if no inventory present with book id
*/
void delete(Long bookId) throws InventoryNotFoundException;

/**
* Delete specific book reference of a book type
*
* @param bookId -
* @param bookReferenceId -
* @throws InventoryNotFoundException in case no book is present wih combination of book id and
* book reference id
*/
void delete(Long bookId, List<String> bookReferenceId) throws InventoryNotFoundException;
}

Book Inventory

TASK
package [Link];

import [Link]; import


[Link]; import
[Link];
import [Link]; import
[Link]; import
[Link];
import [Link];
import [Link]; import
[Link]; import
[Link];
import [Link];
import [Link]; import
[Link];
import [Link]; import
[Link].slf4j.Slf4j;
import [Link]; import
[Link];
import [Link]; import
[Link];

/**
* Implementation for {@link InventoryService}
*
* @author Dhiraj
*/
@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class InventoryServiceImpl implements InventoryService {
private final InventoryRepository inventoryRepository;
private final ModelMapper modelMapper;

@Override
public List<InventoryDTO> findAllBook(Long bookId) {
return [Link](bookId).stream()
.map(this::mapToDTO)
.collect([Link]());
}

@Override
public InventoryDTO orderBookIfAvailable(Long bookId) throws InventoryNotFoundException
{
InventoryDTO inventoryDTO =
[Link](bookId).stream()
.filter(Inventory::getAvailable)
.findFirst()
.map(this::mapToDTO)
.orElseThrow( (
) ->
new InventoryNotFoundException(
"No inventory available for book id: " + bookId));
[Link](
[Link](), [Link](), false); return
inventoryDTO;
}

@Override
public boolean returnBook(Long bookId, String bookReferenceId) {
return [Link](bookId, bookReferenceId, true) > 0;
}

@Override
public long getAvailableCount(Long bookId) {
return [Link](bookId, true);
}

@Override
@Transactional(rollbackOn = [Link])
public List<InventoryDTO> add(InventoryDTO inventoryDTO, Integer count) throws GenericException {
[Link](inventoryDTO, "Inventory cannot be null"); count
= count != null && count > 0 ? count : 1; Set<Inventory> set =
new HashSet<>(count); SecureRandom secureRandom = new
SecureRandom(); while (count-- > 0) {
Inventory inventory = [Link](inventoryDTO);

[Link]().setBookReferenceId([Link]([Link](Integer.MAX_VALU E)));
[Link](true);
[Link](inventory);
}
try { [Link](set);
} catch (Exception e) {
throw new GenericException(
"Error while saving inventory", HttpStatus.INTERNAL_SERVER_ERROR.value());
}
return [Link]().map(this::mapToDTO).collect([Link]());
}

@Override
public void delete(Long bookId) throws InventoryNotFoundException { List<Inventory>
bookInventory = [Link](bookId); if
([Link]()) {
return;
}
long count = [Link]().filter(inventory -> ![Link]()).count(); if (count
> 0) {
throw new InventoryNotFoundException(
"Some books of book id " + bookId + " are loaned and cannot be deleted ");
}
[Link](bookId);
}

@Override
@Transactional(rollbackOn = [Link])
public void delete(Long bookId, List<String> bookReferenceIdList) throws
InventoryNotFoundException {
for(String bookReferenceId: bookReferenceIdList) {
Optional<Inventory> inventory =
[Link](bookId, bookReferenceId); if
([Link]()) {
throw new InventoryNotFoundException(
[Link]("No Book found with id %s and reference id %s", bookId, bookReferenceId));
}
if (![Link]().getAvailable()) {
throw new InventoryNotFoundException(
[Link](
"Book with id %s and reference id %s is loaned and cannot be deleted", bookId,
bookReferenceId));
}
[Link](bookId, bookReferenceId);
}
}
private InventoryDTO mapToDTO(Inventory inventory) { return
[Link](inventory, [Link]);
}

private Inventory mapToEntity(InventoryDTO inventoryDTO) { return


[Link](inventoryDTO, [Link]);
}
}
}

Book Inventory Management

spackage [Link];

import [Link]; import


[Link]; import
[Link];
import [Link]; import
[Link];

/**
* Service for {@link BookOrder}
*
* @author Dhiraj
*/
public interface BookOrderService {
/**
* Find a book order by id
*
* @param id - order id
* @return order details
* @throws OrderNotFoundException if no order present with corresponding id
*/
BookOrderDTO findById(Long id) throws OrderNotFoundException;

/**
* Find all orders of a user
*
* @param userId -
* @return list of orders or empty list if none found
*/
List<BookOrderDTO> findAllByUser(Long userId);

/**
* Find all orders for a book
*
* @param bookId -
* @return list of orders or empty list if none found
*/
List<BookOrderDTO> findAllByBook(Long bookId);

/**
* Find all orders for which the returned date is overdue
*
* @return list of
*/
List<BookOrderDTO> findAllReturnOverdue();

/**
* Find all orders for which the returned date is overdue for a user
*
* @param userId
* @return
*/
List<BookOrderDTO> findAllReturnOverdueForUser(Long userId);

/**
* Find all order for which collection date is overdue
*
* @return
*/
List<BookOrderDTO> findAllCollectionOverdue();

/**
* Find all orders for which collection date is overdue for a user
*
* @param userId
* @return
*/
List<BookOrderDTO> findAllCollectionOverdueForUser(Long userId);

/**
* Order a new book, Connects with Inventory service to fnd if book is available
*
* @param orderDTO order details to add if possible
* @return new order with generated id
* @throws GenericException if order cannot be placed due to book/service unavailability
*/
BookOrderDTO orderBook(BookOrderDTO orderDTO) throws GenericException;

/**
* Mark a order as collected
*
* @param id - order id
* @return order detail with collectedAt date marked as present datetime
* @throws OrderNotFoundException if no order present with id
*/
BookOrderDTO collectBook(Long id) throws OrderNotFoundException;

/**
* Mark the book as returned, Connects with inventory servie to return the book and deletes the
* order and adds it to order history
*
* @param id order id
* @throws OrderNotFoundException if no order present with id
* @throws GenericException if order cannot be returned due to book/service unavailability
*/
BookOrderDTO returnBook(Long id) throws OrderNotFoundException, GenericException;

/**
* Delete an order
*
* @param id
* @throws OrderNotFoundException
*/
void delete(Long id) throws OrderNotFoundException;

} Book Inventory Management

NAME- KUSAGRA RAJ


Reg.- 2201030103
GROUP- 5A
BRANCH- CSE

You might also like