Commit ba61a2a6 authored by ppapili's avatar ppapili

Added Exception handling code and lombok changes

parent 2394afc8
...@@ -62,6 +62,14 @@ ...@@ -62,6 +62,14 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId> <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.poc.kafka.mongo.controller; package com.poc.kafka.mongo.controller;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.Optional;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
...@@ -18,6 +17,7 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -18,6 +17,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.poc.kafka.mongo.exception.EmployeeException;
import com.poc.kafka.mongo.model.Emp; import com.poc.kafka.mongo.model.Emp;
import com.poc.kafka.mongo.service.EmployeeService; import com.poc.kafka.mongo.service.EmployeeService;
...@@ -29,8 +29,9 @@ public class EmployeeController { ...@@ -29,8 +29,9 @@ public class EmployeeController {
private EmployeeService employeeService; private EmployeeService employeeService;
@PostMapping(produces = "application/json", consumes = "application/json", path = "/produce") @PostMapping(produces = "application/json", consumes = "application/json", path = "/produce")
public void publishEmployee(@Valid @RequestBody Emp emp) throws InterruptedException, ExecutionException { public ResponseEntity<String> publishEmployee(@Valid @RequestBody Emp emp) {
employeeService.send(emp); employeeService.send(emp);
return new ResponseEntity<>("Employee details published", HttpStatus.OK);
} }
@GetMapping(produces = "application/json", consumes = "application/json", path = "/empId/{empId}") @GetMapping(produces = "application/json", consumes = "application/json", path = "/empId/{empId}")
......
package com.poc.kafka.mongo.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
public class EmployeeException extends RuntimeException {
private String errorCode;
private String errorDescription;
private String message;
private static final long serialVersionUID = 1L;
public EmployeeException(String exception) {
super(exception);
}
public EmployeeException(String errorCode, String errorDescription) {
super();
this.errorCode = errorCode;
this.errorDescription = errorDescription;
}
}
package com.poc.kafka.mongo.exception;
import java.util.Date;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.poc.kafka.mongo.model.ErrorDetails;
import com.poc.kafka.mongo.util.ErrorEnum;
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(EmployeeException.class)
public final ResponseEntity<ErrorDetails> handleUserNotFoundException(EmployeeException ex, WebRequest request) {
ErrorDetails error = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true),ex.getErrorDescription(),ex.getErrorCode());
if(error.getErrorCode().equalsIgnoreCase(ErrorEnum.EC_2.name())) {
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}else {
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails error = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(error, HttpStatus.METHOD_NOT_ALLOWED);
}
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails error = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(error, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
ErrorDetails error = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails error = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
/**
* For handling spring validation errors
*
*/
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
FieldError ers = ex.getBindingResult().getFieldError();
ErrorDetails error = new ErrorDetails(new Date(), ers.getDefaultMessage(), request.getDescription(true));
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}
package com.poc.kafka.mongo.model;
import java.util.Date;
import org.springframework.lang.Nullable;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
private String errorDescription;
@Nullable private String errorCode;
public ErrorDetails(Date timestamp, String message, String details){
this.timestamp=timestamp;
this.message=message;
this.details=details;
}
}
\ No newline at end of file
...@@ -5,8 +5,16 @@ import java.util.List; ...@@ -5,8 +5,16 @@ import java.util.List;
import com.poc.kafka.mongo.model.Emp; import com.poc.kafka.mongo.model.Emp;
public interface EmployeeService { public interface EmployeeService {
/**
*
* @param e
*/
public void send(Emp e); public void send(Emp e);
/**
*
* @param message
*/
public void receive(String message); public void receive(String message);
/** /**
...@@ -15,34 +23,40 @@ public interface EmployeeService { ...@@ -15,34 +23,40 @@ public interface EmployeeService {
* @return * @return
*/ */
public Emp findByEmpId(Long empId); public Emp findByEmpId(Long empId);
/** /**
* *
* @param id * @param id
* @return * @return
*/ */
public Emp findById(String id); public Emp findById(String id);
/** /**
* *
* @return * @return
*/ */
public List<Emp> findAll(); public List<Emp> findAll();
/** /**
* *
* @param emp * @param emp
* @return * @return
*/ */
public Emp save(Emp emp); public Emp save(Emp emp);
/** /**
* *
* @param emp * @param emp
*/ */
public void saveOrUpdate(Emp emp); public void saveOrUpdate(Emp emp);
/** /**
* *
* @param sal * @param sal
* @return * @return
*/ */
public List<Emp> findBySalary(Double sal); public List<Emp> findBySalary(Double sal);
/** /**
* *
* @param empId * @param empId
...@@ -50,5 +64,4 @@ public interface EmployeeService { ...@@ -50,5 +64,4 @@ public interface EmployeeService {
*/ */
public Long deleteByEmpId(Long empId); public Long deleteByEmpId(Long empId);
} }
...@@ -17,10 +17,13 @@ import org.springframework.util.concurrent.ListenableFutureCallback; ...@@ -17,10 +17,13 @@ import org.springframework.util.concurrent.ListenableFutureCallback;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.poc.kafka.mongo.entity.Employee; import com.poc.kafka.mongo.entity.Employee;
import com.poc.kafka.mongo.exception.EmployeeException;
import com.poc.kafka.mongo.mapper.EmployeeMapper; import com.poc.kafka.mongo.mapper.EmployeeMapper;
import com.poc.kafka.mongo.model.Emp; import com.poc.kafka.mongo.model.Emp;
import com.poc.kafka.mongo.repository.EmployeeMongoRepository; import com.poc.kafka.mongo.repository.EmployeeMongoRepository;
import com.poc.kafka.mongo.repository.EmployeeRepository; import com.poc.kafka.mongo.repository.EmployeeRepository;
import com.poc.kafka.mongo.util.ErrorEnum;
@Service @Service
public class EmployeeServiceImpl implements EmployeeService { public class EmployeeServiceImpl implements EmployeeService {
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class); private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);
...@@ -39,7 +42,6 @@ public class EmployeeServiceImpl implements EmployeeService { ...@@ -39,7 +42,6 @@ public class EmployeeServiceImpl implements EmployeeService {
@Autowired @Autowired
private EmployeeRepository employeeRepository; private EmployeeRepository employeeRepository;
@Override @Override
public void send(Emp emp) { public void send(Emp emp) {
...@@ -49,6 +51,8 @@ public class EmployeeServiceImpl implements EmployeeService { ...@@ -49,6 +51,8 @@ public class EmployeeServiceImpl implements EmployeeService {
@Override @Override
public void onFailure(Throwable ex) { public void onFailure(Throwable ex) {
logger.info("Unable to send message=[ {} ] due to : {}", request, ex.getMessage()); logger.info("Unable to send message=[ {} ] due to : {}", request, ex.getMessage());
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
ex.getMessage());
} }
@Override @Override
...@@ -61,65 +65,123 @@ public class EmployeeServiceImpl implements EmployeeService { ...@@ -61,65 +65,123 @@ public class EmployeeServiceImpl implements EmployeeService {
@Override @Override
@KafkaListener(topics = { "${spring.kafka.topics}" }) @KafkaListener(topics = { "${spring.kafka.topics}" })
public void receive(String emp) { public void receive(String emp) {
logger.info("Kafka event consumed is:{} " , emp); logger.info("Kafka event consumed is:{} ", emp);
Emp e = gson.fromJson(emp, Emp.class); Emp e = gson.fromJson(emp, Emp.class);
logger.info("converted value:{} " , e.toString()); logger.info("converted value:{} ", e.toString());
/** /**
* To send to mongo database after listening the record from kafka * To send to mongo database after listening the record from kafka
*/ */
saveOrUpdate(e); saveOrUpdate(e);
} }
@Override @Override
public Emp findByEmpId(Long empId) { public Emp findByEmpId(Long empId) {
return (Emp)employeeMapper.mapEntityToPojo(employeeMongoRepository.findByEmpId(empId)); try {
Object e = employeeMapper.mapEntityToPojo(employeeMongoRepository.findByEmpId(empId));
if (e == null) {
throw new EmployeeException(ErrorEnum.EC_1.name(), ErrorEnum.getDesription(ErrorEnum.EC_1.name()));
}
return (Emp) e;
} catch (EmployeeException e) {
throw e;
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
} }
@Override @Override
public Emp findById(String id) { public Emp findById(String id) {
return (Emp)employeeMapper.mapEntityToPojo(employeeMongoRepository.findById(id).orElse(new Employee())); try {
Object e = employeeMapper.mapEntityToPojo(employeeMongoRepository.findById(id));
if (e == null) {
throw new EmployeeException(ErrorEnum.EC_1.name(), ErrorEnum.getDesription(ErrorEnum.EC_1.name()));
}
return (Emp) e;
} catch (EmployeeException e) {
throw e;
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
} }
@Override @Override
public List<Emp> findAll() { public List<Emp> findAll() {
List<Employee> list= employeeMongoRepository.findAll(); List<Employee> list = employeeMongoRepository.findAll();
List<Emp> empList= list.stream() try {
.map(e->employeeMapper.mapEntityToPojo(e)) if (list.isEmpty()) {
.map(e->(Emp)e) throw new EmployeeException(ErrorEnum.EC_1.name(), ErrorEnum.getDesription(ErrorEnum.EC_1.name()));
.collect(Collectors.toList()); }
return empList; return list.stream().map(e -> employeeMapper.mapEntityToPojo(e)).map(e -> (Emp) e)
.collect(Collectors.toList());
} catch (EmployeeException e) {
throw e;
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
} }
@Override @Override
public Emp save(Emp emp) { public Emp save(Emp emp) {
Employee employee = (Employee) employeeMapper.mapPojoToEntity(emp); Employee employee = (Employee) employeeMapper.mapPojoToEntity(emp);
return (Emp)employeeMapper.mapEntityToPojo(employeeMongoRepository.save(employee)); try {
return (Emp) employeeMapper.mapEntityToPojo(employeeMongoRepository.save(employee));
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
} }
@Override @Override
public void saveOrUpdate(Emp emp) { public void saveOrUpdate(Emp emp) {
Employee employee = (Employee) employeeMapper.mapPojoToEntity(emp); Employee employee = (Employee) employeeMapper.mapPojoToEntity(emp);
employeeRepository.saveOrUpdate(employee); try {
employeeRepository.saveOrUpdate(employee);
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
} }
@Override @Override
public List<Emp> findBySalary(Double sal) { public List<Emp> findBySalary(Double sal) {
List<Emp> empList= null; List<Emp> empList = null;
try (Stream<Employee> stream = employeeMongoRepository.findBySalary(sal)) { try (Stream<Employee> stream = employeeMongoRepository.findBySalary(sal)) {
List<Employee> list = stream.collect(Collectors.toList()); List<Employee> list = stream.collect(Collectors.toList());
empList= list.stream() if (list.isEmpty()) {
.map(e->(Emp)employeeMapper.mapEntityToPojo(e)) throw new EmployeeException(ErrorEnum.EC_1.name(), ErrorEnum.getDesription(ErrorEnum.EC_1.name()));
.collect(Collectors.toList()); }
empList = list.stream().map(e -> (Emp) employeeMapper.mapEntityToPojo(e)).collect(Collectors.toList());
} catch (EmployeeException e) {
throw e;
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
} }
return empList; return empList;
} }
@Override @Override
public Long deleteByEmpId(Long empId) { public Long deleteByEmpId(Long empId) {
return employeeMongoRepository.deleteByEmployeeId(empId); try {
} Long id = employeeMongoRepository.deleteByEmployeeId(empId);
if (id == 0) {
throw new EmployeeException(ErrorEnum.EC_1.name(), ErrorEnum.getDesription(ErrorEnum.EC_1.name()));
}
logger.info("Deleted emp id:{}", id);
return id;
} catch (EmployeeException e) {
throw e;
} catch (Exception e) {
throw new EmployeeException(ErrorEnum.EC_2.name(), ErrorEnum.getDesription(ErrorEnum.EC_2.name()),
e.getMessage());
}
}
} }
package com.poc.kafka.mongo.util;
import java.util.HashMap;
import java.util.Map;
public enum ErrorEnum {
EC_1("Record not found"), EC_2("Unexpected Exception");
private String errDes;
private ErrorEnum(String s) {
errDes = s;
}
private static final Map<String, String> BY_LABEL = new HashMap<>();
static {
for (ErrorEnum e : values()) {
BY_LABEL.put(e.name(), e.errDes);
}
}
public static String getDesription(String name) {
return BY_LABEL.get(name);
}
}
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