Commit e5c688eb authored by Abdul Mujeeb Mohammed's avatar Abdul Mujeeb Mohammed

adding Employee Service, first commit

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?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>2.7.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nisum</groupId>
<artifactId>EmployeeService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>EmployeeService</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!-- <spring-cloud.version>2021.0.5</spring-cloud.version>-->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
<!-- </dependency>-->
</dependencies>
<!-- <dependencyManagement>-->
<!-- <dependencies>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-dependencies</artifactId>-->
<!-- <version>${spring-cloud.version}</version>-->
<!-- <type>pom</type>-->
<!-- <scope>import</scope>-->
<!-- </dependency>-->
<!-- </dependencies>-->
<!-- </dependencyManagement>-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<!-- depending on your project -->
<target>1.8</target>
<!-- depending on your project -->
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
<!-- other annotation processors -->
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.nisum.employee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
@Bean
//@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
package com.nisum.employee.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.sql.DataSource;
@Configuration
@ConfigurationProperties("spring.datasource")
// @Profile({"dev","qa"}) - Using Profile at Class Level
public class DBConfiguration {
private String driverClassName;
private String url;
private String username;
private String password;
@Bean
@Profile("dev")
public DataSource devDatabaseConnection(){
DataSource dataSource = null;
// implementation
return dataSource;
}
@Bean
@Profile("qa")
public String qaDatabaseConnection(){
return "qa";
}
@Bean
@Profile("prod")
public String prodDatabaseConnection(){
return "prod";
}
}
package com.nisum.employee.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SpringFoxConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
\ No newline at end of file
package com.nisum.employee.controller;
import com.nisum.employee.dto.EmployeeDto;
import com.nisum.employee.dto.EmployeeWithDepartment;
import com.nisum.employee.entities.Employee;
import com.nisum.employee.service.EmployeeService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.rmi.NoSuchObjectException;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
@Slf4j
public class EmployeeController {
@Autowired
private EmployeeService service;
/**
* Creates new employee into the employee db and return the created object.
*
* @param employee employee request body
* @return response body of employee object
*/
@PostMapping("/employees")
public ResponseEntity<EmployeeDto> saveEmployee(@Valid @RequestBody(required = false) EmployeeDto employee) {
log.info("Employee is created");
return ResponseEntity.ok(service.saveEmployee(employee));
}
/**
* Gets an employee based on the employee id input.
*
* @param id employee id
* @return response employee
*/
@GetMapping("/emp/{id}")
public Employee findEmployee(@PathVariable("id") Long id){
log.info("find method of Employee Controller class");
return service.findEmployee(id);
}
/**
* Gets an employee with Department based on the employee id input.
*
* @param empId employee empId
* @return response employee with Department Object
*/
@GetMapping("/{id}")
public ResponseEntity<EmployeeWithDepartment> getEmployee(@NonNull @PathVariable("id") long empId){
log.info("Employee get method");
EmployeeWithDepartment withDepartment = service.getEmployee(empId);
return new ResponseEntity<EmployeeWithDepartment>(withDepartment, HttpStatus.OK);
}
/**
* Reading Request Headers
* @param language
* @return
*/
@GetMapping("/employeeMessage")
public ResponseEntity<String> greeting(@RequestHeader(HttpHeaders.ACCEPT_LANGUAGE) String language) {
// code that uses the language variable
return new ResponseEntity<String>("", HttpStatus.OK);
}
}
package com.nisum.employee.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;
@Data
public class ApiError {
private HttpStatus status;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
private String message;
private String debugMessage;
private ApiError() {
timestamp = LocalDateTime.now();
}
public ApiError(HttpStatus status) {
this();
this.status = status;
}
public ApiError(HttpStatus status, Throwable ex) {
this();
this.status = status;
this.message = "Unexpected error";
this.debugMessage = ex.getLocalizedMessage();
}
public ApiError(HttpStatus status, String message, Throwable ex) {
this();
this.status = status;
this.message = message;
this.debugMessage = ex.getLocalizedMessage();
}
}
\ No newline at end of file
package com.nisum.employee.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentDto {
private long departmentId;
private String departmentName;
private String depatmentAddress;
private String DepartmentCode;
}
package com.nisum.employee.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDto {
private long employeeId;
private String empName;
private String emapSalary;
private String Password;
private long empDepartmentId;
private String email;
private LocalDateTime createdTime;
private LocalDateTime updatedTime;
private ApiError apiError;
}
\ No newline at end of file
package com.nisum.employee.dto;
import com.nisum.employee.entities.Employee;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeWithDepartment {
private EmployeeDto employee;
private DepartmentDto department;
}
package com.nisum.employee.dto;
import lombok.Data;
import java.util.Date;
@Data
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
}
\ No newline at end of file
package com.nisum.employee.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.*;
import java.time.LocalDateTime;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long employeeId;
@NotBlank(message = "Name is mandatory")
private String empName;
private String emapSalary;
@NotNull
@Size(min=7, message="Password should have atleast 8 characters")
private String password;
@NotNull
private long empDepartmentId;
@Email
private String email;
private LocalDateTime createdTime;
private LocalDateTime updatedTime;
}
package com.nisum.employee.exception;
import com.nisum.employee.dto.ApiError;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@RestControllerAdvice
public class ControllerAdviceException extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoDataFoundException.class)
public ResponseEntity<Object> handleNoDataException(NoDataFoundException nde, WebRequest request){
Map<String, Object> map = new LinkedHashMap<>();
map.put("message","No Data found");
map.put("timestamp", LocalDateTime.now());
return new ResponseEntity<>(map, NOT_FOUND);
}
@ExceptionHandler(value = EmployeeAlreadyExistsException.class)
public ResponseEntity<Object> handleEmployeeAlreadyExistsException(EmployeeAlreadyExistsException empAlreadyExistsException) {
return new ResponseEntity<Object>("Employee already exists", HttpStatus.CONFLICT);
}
/**
* If there is no Entity present in the object
*/
@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(EntityNotFoundException ex,WebRequest request) {
ApiError apiError = new ApiError(NOT_FOUND);
apiError.setMessage(ex.getMessage());
return new ResponseEntity<Object>(apiError, NOT_FOUND);
}
/**
* Unable to instantiate bean for this method
* Need to check and resolve
*/
// @ExceptionHandler(value = MethodArgumentNotValidException.class)
// public ResponseEntity<ApiError> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
//
// ApiError errorDetails = new ApiError(BAD_REQUEST);
// errorDetails.setMessage(ex.getMessage());
// errorDetails.setTimestamp(LocalDateTime.now());
// return new ResponseEntity<ApiError>(errorDetails, HttpStatus.BAD_REQUEST);
// }
}
package com.nisum.employee.exception;
public class EmployeeAlreadyExistsException extends RuntimeException {
private String message;
public EmployeeAlreadyExistsException(String message){
this.message=message;
}
public EmployeeAlreadyExistsException(){
}
}
package com.nisum.employee.exception;
public class NoDataFoundException extends RuntimeException {
public NoDataFoundException(long id) {
super(String.valueOf(id));
}
}
package com.nisum.employee.repository;
import com.nisum.employee.entities.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByEmployeeId(long employeeId);
}
package com.nisum.employee.service;
import com.nisum.employee.dto.EmployeeDto;
import com.nisum.employee.entities.Employee;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface EmployeeMapperService {
EmployeeMapperService MAPPER = Mappers.getMapper(EmployeeMapperService.class);
EmployeeDto employeeEntityToDto(Employee employee);
Employee employeeDtoToEntity(EmployeeDto employee);
}
package com.nisum.employee.service;
import com.nisum.employee.dto.DepartmentDto;
import com.nisum.employee.dto.EmployeeDto;
import com.nisum.employee.dto.EmployeeWithDepartment;
import com.nisum.employee.entities.Employee;
import com.nisum.employee.exception.EmployeeAlreadyExistsException;
import com.nisum.employee.exception.NoDataFoundException;
import com.nisum.employee.repository.EmployeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.persistence.EntityNotFoundException;
import java.util.Optional;
@Service
@Slf4j
public class EmployeeService {
@Autowired
private EmployeeRepository repository;
@Autowired
private RestTemplate restTemplate;
/**
* savng employee from employee object
* @param employee
* @return
*/
public EmployeeDto saveEmployee(EmployeeDto employee) {
Optional.of(employee).orElseThrow(()->new NoDataFoundException(employee.getEmployeeId()));
Employee emp = EmployeeMapperService.MAPPER.employeeDtoToEntity(employee);
log.info("save method of Employee Service class");
if (repository.existsById(emp.getEmployeeId())) {
throw new EmployeeAlreadyExistsException();
}
Employee saved = repository.save(emp);
return EmployeeMapperService.MAPPER.employeeEntityToDto(saved);
}
public EmployeeWithDepartment getEmployee(long employeeId) {
log.info("get method of Employee Service class");
EmployeeWithDepartment empDep = new EmployeeWithDepartment();
//empId
//db
Employee employee = Optional.ofNullable(repository.findByEmployeeId(employeeId)).orElseThrow(() -> new EntityNotFoundException());
EmployeeDto employeeDto = EmployeeMapperService.MAPPER.employeeEntityToDto(employee);
//department not present
DepartmentDto department = restTemplate.getForObject("http://localhost:9001/department/" + employee.getEmpDepartmentId(), DepartmentDto.class);
empDep.setEmployee(employeeDto);
empDep.setDepartment(department);
return empDep;
}
public Employee findEmployee(long id){
log.info("find method of Employee Service class");
return repository.findById(id).orElseThrow(()-> new NoDataFoundException(id));
}
}
#DEV ENVIRONMENT
##DB , Connecting to H2 Database
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:http://localhost:8082/h2-console
spring.datasource.username=System_Dev
spring.datasource.password=System
\ No newline at end of file
#PROD ENVIRONMENT
##DB Connecting Prod Environment
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=Root_Prod
spring.datasource.password=System
\ No newline at end of file
server.port=9002
spring.profile.active=dev
spring.application.name=EMPLOYEE-SERVICE
# for enabling swagger documentation
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
#eureka:
# client:
# register-with-eureka: true
# fetch-registry: true
# service-url:
# default-zone: http://localhost:8761/eureka/
# instance:
# hostname: localhost
\ No newline at end of file
package com.nisum.employee;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EmployeeServiceApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment