Food Order System : Customer Service

 Domain 


Customer


package com.customer.Domain;


import jakarta.persistence.Entity;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Entity
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer customerId;

@NotNull(message = "firstName field should not be null")
@Size(min = 3,max=30,message = "name of min length should be 3 and max be 30")
private String firstName;

@NotNull(message = "lastName field should not be null")
@Size(min = 3,max=30,message = "name of min length should be 3 and max be 30")
private String lastname;

@NotNull(message = "age field should not be null")
@Max(100)
private Integer age;

@NotNull(message = "gender field should not be null")
private String gender;

@NotNull(message = "mobileNumber field should not be null")
private String mobileNumber;

@Email
private String email;

@NotNull(message = "Address field should not be null")
@OneToOne(cascade = CascadeType.ALL)
private Address address;

@NotNull(message = "Address field should not be null")
@Size(min = 8,max=15,message = "Password size of min length should be 3 and max be 30")
@Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$", message = "Invalid Password pattern. Password must contain 8 to 20 characters at least one digit, lower, upper case and one special character.")
private String password;




}



Address

package com.customer.Domain;

import jakarta.persistence.*;
import lombok.*;





import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Entity
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Address {


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer addressId;


private String buildingName;

private String streetNo;

private String area;

private String city;

private String state;

private String country;

private String pinCode;



}



--------------------

Controller

  

CustomerController


package com.customer.controller;


import com.customer.Domain.Customer;
import com.customer.exception.CustomerNotFound;
import com.customer.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RequestMapping("/Customers")
@RestController
public class CustomerController {

private static final Logger logInfo = LoggerFactory.getLogger(Customer.class);


@Autowired
private CustomerService cs;


@PostMapping("/AddCustomer")
// public ResponseEntity<String> addCustomer(@RequestBody Customer customer) throws CustomerNotFound
public ResponseEntity<String> addCustomer(@RequestBody Customer customer)
{
Customer addcustomer = cs.addCustomer(customer);
if(addcustomer != null)
{
logInfo.info("Customer Info logging is Enabled");
logInfo.debug("Customer Debug logging is Enabled");


return new ResponseEntity<>("Customer Added..", HttpStatus.CREATED);
}
return new ResponseEntity<>("Customer fail to Add", HttpStatus.NOT_FOUND);
}

@PutMapping("/updateCustomer/{id}")
public ResponseEntity<String> updateCustomer(@PathVariable int id ,@RequestBody Customer customer) throws CustomerNotFound
{

boolean addcustomer = cs.updateCustomer(customer,id);
if(addcustomer)
{
return new ResponseEntity<>("Customer Updated", HttpStatus.CREATED);
}
return new ResponseEntity<>(id+" - Customer Not available ",HttpStatus.NOT_FOUND);
}


@DeleteMapping("/removeCustomer/{id}")
public ResponseEntity<String> deleteCustomer(@PathVariable int id) throws CustomerNotFound
{
Customer deleteCustomer = cs.removeCustomer(id);

if(deleteCustomer != null)
{
return new ResponseEntity<>("Customer Deleted with :"+id , HttpStatus.OK);

}
return new ResponseEntity<>(id+" with Customer Not available ", HttpStatus.NOT_FOUND);
}


@GetMapping("viewCustomer/{id}")
public ResponseEntity<Customer> getCustomerById(@PathVariable int id) throws CustomerNotFound
{
Customer getCustomer = cs.viewCustomer(id);
if(getCustomer != null)
{
return new ResponseEntity<>(getCustomer, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@GetMapping("/viewAllCustomer")
public ResponseEntity<List<Customer>> getAllCustomer() throws CustomerNotFound
{
List<Customer> allCustomer = cs.viewAllCustomer();
if(allCustomer != null)
{
return new ResponseEntity<>(allCustomer, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}



} 




-------------

DTO


CustomerDTO


package com.customer.dto;

import com.customer.Domain.Address;
import com.customer.Domain.Customer;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;


@Data
public class CustomerDTO {

private Customer customer;
private Address address;


}



-------------

Exception


CustomerNotFound


package com.customer.exception;

public class CustomerNotFound extends Exception{

public CustomerNotFound() {
}

public CustomerNotFound(String arg0) {
super(arg0);
}


}



GlobalExceptionHandler


package com.customer.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(CustomerNotFound.class)
public ResponseEntity<String> handleCustomerNotFoundException(CustomerNotFound ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}


//@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
// @ExceptionHandler(CustomerNotFound.class)
// public Map<String, String> handleCustomerNotFoundException(CustomerNotFound ex) {
// Map<String, String> errMap = new HashMap<>();
// errMap.put("errorMessage",ex.getMessage());
// return errMap;
// }


@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage( );
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}

}



------------------

repository


package com.customer.repository;

import com.customer.Domain.Customer;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;


public interface CustomerRepo extends JpaRepositoryImplementation<Customer, Integer> {

public Customer findByEmail(String email);

public Customer findByMobileNumber(String mobileNo);

}



---------------------

Service


CustomerService


package com.customer.service;

import com.customer.Domain.Customer;
import com.customer.exception.CustomerNotFound;

import java.util.List;

public interface CustomerService {

public Customer addCustomer(Customer customer);

public Customer updateCustomer(Customer customer );
public Boolean updateCustomer(Customer customer, Integer id );



public Customer removeCustomer(Integer customerId);

public Customer viewCustomer(Integer customerId) throws CustomerNotFound;

public List<Customer> viewAllCustomer();


}



CustomerImpl


package com.customer.service.Impl;

import com.customer.Domain.Customer;
import com.customer.exception.CustomerNotFound;
import com.customer.repository.CustomerRepo;
import com.customer.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class CustomerServiceImpl implements CustomerService {


@Autowired
private CustomerRepo customerRepo;


@Override
// public Customer addCustomer(Customer customer) throws CustomerNotFound {
public Customer addCustomer(Customer customer) {

Customer cust = null;
if(customer != null)
{
cust = customerRepo.save(customer);
}

return cust;

// else {
// throw new CustomerNotFound("Customer Detail are not available");
// }
}


@Override
public Customer updateCustomer(Customer customer) {
Optional<Customer> optional = customerRepo.findById(customer.getCustomerId());

Customer updatedCustomer = null;
if (optional.isPresent()) {
updatedCustomer = customerRepo.save(customer);
}
return updatedCustomer;
}


@Override
public Boolean updateCustomer(Customer customer, Integer id) {

Optional<Customer> optional = customerRepo.findById(id);
if(optional.isPresent()) {

Customer c = optional.get();
c.setFirstName(customer.getFirstName());
c.setLastname(customer.getLastname());
c.setAge(customer.getAge());
c.setGender(customer.getGender());
c.setMobileNumber(customer.getMobileNumber());
c.setEmail(customer.getEmail());
c.setAddress(customer.getAddress());
c.setPassword(customer.getPassword());

customerRepo.save(c);
return true;
}
return false;
}


@Override
public Customer removeCustomer(Integer customerId) {

Optional<Customer> opt = customerRepo.findById(customerId);

Customer deletedCustomer = null;
if(opt.isPresent())
{
deletedCustomer = opt.get();
customerRepo.delete(deletedCustomer);
}
return deletedCustomer;
}

@Override
public Customer viewCustomer(Integer customerId) throws CustomerNotFound {

Optional<Customer> byId = customerRepo.findById(customerId);
Customer viewCustomer = null;
if(byId.isPresent())
{
viewCustomer = byId.get();
return viewCustomer;

}else {
throw new CustomerNotFound("Customer Not Available of id : "+customerId);
}

}

@Override
public List<Customer> viewAllCustomer() {
List<Customer> allCustomer = customerRepo.findAll();
return allCustomer;
}

}






Resource 


application.properties 




spring.application.name=FOS-Customer-Service



server.port=8081

#h2 properties
#spring.h2.console.enabled=true
#spring.datasource.url= jdbc:h2:mem:test
#spring.jpa.show-sql=true
#spring.jpa.hibernate.ddl-auto=update


spring.datasource.url=jdbc:mysql://localhost:3306/FOS_Customer_Service
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true


#logging.level.com.customer.controller=DEBUG
debug=true






----


logback.xml


<?xml version="1.0" encoding="UTF-8"?>

<configuration>

<!-- Include default Spring Boot Logback configuration -->
<include resource="org/springframework/boot/logging/logback/default.xml"/>

<!-- Define log pattern for console -->
<property name="CONSOLE_LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}] [%thread] %-5level %logger{36} - %msg%n"/>
<property name="CONSOLE_LOG_CHARSET" value="UTF-8"/>

<!-- Console appender configuration -->
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

<!-- Define log file location -->
<property name="LOG_FILE" value="log/app.log"/>

<!-- File appender configuration -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${LOG_FILE}.%i</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
</appender>

<!-- Root logger configuration -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>

<!-- Custom logger configuration -->
<logger name="com.customer.controller" level="DEBUG"/>

</configuration>




main class


package com.customer;

//import io.swagger.v3.oas.annotations.OpenAPIDefinition;
//import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@OpenAPIDefinition(info = @Info(title = "Customer-Service-API", version = "2.0", description = "Customer Microservice Description"))
public class FosCustomerServiceApplication {

public static void main(String[] args) {
SpringApplication.run(FosCustomerServiceApplication.class, args);
}

}



Postman 


post : http://localhost:8081/Customers/AddCustomer

{
    // "customerId": 3,
    "firstName": "datta2",
    "lastname": "sirsath2",
    "age": 24,
    "gender": "Male",
    "mobileNumber": "7498767134",
    "email": "datta@gmail.com",
    "address": {
        "buildingName" :"Wonder Kids",
        "streetNo": "4152",
        "area" : "Pradhikaran",
        "city" : "Pune",
        "state" : "Maharashtra",
        "country" : "India",
        "pinCode" : "411044"
    },
    "password": "Datta@123"
}



Get : http://localhost:8081/Customers/viewCustomer/1



Put : http://localhost:8081/Customers/updateCustomer/1


{
    // "customerId": 3,
    "firstName": "datta Bhauuuu",
    "lastname": "sirsath2",
    "age": 24,
    "gender": "Male",
    "mobileNumber": "7498767134",
    "email": "datta@gmail.com",
    // "address": "",
    "password": "datta123"
}



Delete : http://localhost:8081/Customers/removeCustomer/3











Comments

Popular posts from this blog

1. Microservices Interview Question

2. Random Interview Question