You are on page 1of 39

package com.capgemini.

employeepayrollJDBC;

public class CustomSQLException extends Exception {

enum Exception_Type{

CONNECTION_FAILED,

QUERY_FAILED,

ADD_FAILED,

READ_FAILED,

UPDATE_FAILED,

READ_IN_DATERANGE_FAILED

public Exception_Type type;

public CustomSQLException(String message,Exception_Type type)

super(message);

this.type = type;

package com.capgemini.employeepayrollJDBC;

import java.util.*;

import java.util.stream.Collectors;

import java.util.stream.Stream;

import java.io.*;

import java.nio.file.*;
public class EmployeeFile {

public String DATA_FILE = "PayRollData.txt";

EmployeeFile() {

public void writeData(List<EmployeePayRoll> empPayRollList) {

StringBuffer data = new StringBuffer();

for (EmployeePayRoll e : empPayRollList) {

data.append(e.toString() + "\n");

Path filePath = Paths.get(DATA_FILE);

try {

Files.write(filePath, data.toString().getBytes());

} catch (IOException e1) {

e1.printStackTrace();

public int noOfEntries() {

int count = 0;

Path filePath = Paths.get(DATA_FILE);

try {

count = (int) Files.lines(filePath).count();

} catch (IOException e) {

e.printStackTrace();

}
return count;

public void printData() {

Path filePath = Paths.get(DATA_FILE);

try {

Stream<String> stringStream = Files.lines(filePath);

} catch (IOException e) {

e.printStackTrace();

public List<EmployeePayRoll> readData() {

List<String[]> listOfElements = null;

List<EmployeePayRoll> empPayRoll = new ArrayList<EmployeePayRoll>();

Path filePath = Paths.get(DATA_FILE);

String[] data = new String[3];

int i = 0;

try {

Stream<String> stringStr = Files.lines(filePath);

listOfElements = stringStr.map(s -> s.split(", ")).collect(Collectors.toList());

for (String[] e : listOfElements) {

for (String s : e) {

data[i] = e[i].split("=")[1];

i += 1;

i = 0;
empPayRoll.add(new EmployeePayRoll(Integer.parseInt(data[0]), data[1],
Double.parseDouble(data[2])));

return empPayRoll;

} catch (IOException e) {

e.printStackTrace();

return null;

package com.capgemini.employeepayrollJDBC;

import java.time.LocalDate;

import java.util.List;

public class EmployeePayRoll {

public int id;

public String name;

public double salary;

public int companyId;

public String gender;

public List<String> departmentName;

public List<LocalDate> startDate;

public EmployeePayRoll(int id, String name, double salary) {

this.id = id;

this.name = name;
this.salary = salary;

public EmployeePayRoll(int id, String name, String gender, double salary, int companyId,

List<String> departmentName, List<LocalDate> startDate) {

this(id, name, salary);

this.gender = gender;

this.companyId = companyId;

this.departmentName = departmentName;

this.startDate = startDate;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getSalary() {


return salary;

public void setSalary(double salary) {

this.salary = salary;

public String toString() {

return "id=" + id + ", name=" + name + ", salary=" + salary;

public int getCompanyId() {

return companyId;

public void setCompanyId(int companyId) {

this.companyId = companyId;

public List<String> getDepartmentName() {

return departmentName;

public void setDepartmentName(List<String> departmentName) {

this.departmentName = departmentName;

public List<LocalDate> getStartDate() {

return startDate;
}

public void setStartDate(List<LocalDate> startDate) {

this.startDate = startDate;

public String getGender() {

return gender;

public void setGender(String gender) {

this.gender = gender;

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + companyId;

result = prime * result + ((departmentName == null) ? 0 : departmentName.hashCode());

result = prime * result + ((gender == null) ? 0 : gender.hashCode());

result = prime * result + id;

result = prime * result + ((name == null) ? 0 : name.hashCode());

long temp;

temp = Double.doubleToLongBits(salary);

result = prime * result + (int) (temp ^ (temp >>> 32));

result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());

return result;

}
@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

EmployeePayRoll other = (EmployeePayRoll) obj;

if (companyId != other.companyId)

return false;

if (departmentName == null) {

if (other.departmentName != null)

return false;

} else if (!departmentName.equals(other.departmentName))

return false;

if (gender == null) {

if (other.gender != null)

return false;

} else if (!gender.equals(other.gender))

return false;

if (id != other.id)

return false;

if (name == null) {

if (other.name != null)

return false;

} else if (!name.equals(other.name))

return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))

return false;

if (startDate == null) {

if (other.startDate != null)

return false;

} else if (!startDate.equals(other.startDate))

return false;

return true;

package com.capgemini.employeepayrollJDBC;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.time.LocalDate;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

public class EmployeePayrollDBService {

private PreparedStatement preparedStatement;


private static EmployeePayrollDBService employeePayRollDBService;

private EmployeePayrollDBService() {

public static EmployeePayrollDBService getInstance() {

if (employeePayRollDBService == null)

employeePayRollDBService = new EmployeePayrollDBService();

return employeePayRollDBService;

public List<EmployeePayRoll> readData() throws CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();

String query = "select * from employee_payroll where is_active = true";

Statement statement;

ResultSet result = null;

try (Connection connection = this.getConnection();) {

statement = connection.createStatement();

result = statement.executeQuery(query);

employeePayRollList = getDatafromResultset(result);

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.READ_FAILED);

return employeePayRollList;

public int updateSalary(int n, String name, Double salary) throws CustomSQLException {

if (n == 1)
return this.updateSalaryUsingStatement(name, salary);

else

return this.updateSalaryUsingPreparedStatement(name, salary);

private int updateSalaryUsingPreparedStatement(String name, Double salary) throws


CustomSQLException {

try (Connection connection = this.getConnection();) {

preparedStatement = connection

.prepareStatement("update employee_payroll set salary = ? where name = ? and is_active =


true");

preparedStatement.setDouble(1, salary);

preparedStatement.setString(2, name);

int result = preparedStatement.executeUpdate();

return result;

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.UPDATE_FAILED);

private int updateSalaryUsingStatement(String name, Double salary) throws CustomSQLException {

String query = String.format(

"update employee_payroll set salary = %.2f where name = '%s' and is_active = true ;", salary,
name);

Statement statement;

int result = 0;

try (Connection connection = this.getConnection();) {

statement = connection.createStatement();

result = statement.executeUpdate(query);
return result;

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.UPDATE_FAILED);

public EmployeePayRoll preparedStatementReadData(String name) throws CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();

try (Connection connection = this.getConnection();) {

preparedStatement = connection

.prepareStatement("select * from employee_payroll where name = ? and is_active = true");

preparedStatement.setString(1, name);

ResultSet result = preparedStatement.executeQuery();

employeePayRollList = getDatafromResultset(result);

return employeePayRollList.get(0);

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.READ_FAILED);

public List<EmployeePayRoll> getDataInDateRange(String startDate, String endDate) throws


CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();

try (Connection connection = this.getConnection();) {

preparedStatement = connection.prepareStatement(

"select * from employee_payroll where is_active = true and id in (select emp_id from
employee_department where start_date between cast(? as date) and cast(? as date))");

preparedStatement.setString(1, startDate);
preparedStatement.setString(2, endDate);

ResultSet result = preparedStatement.executeQuery();

employeePayRollList = getDatafromResultset(result);

return employeePayRollList;

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.READ_IN_DATERANGE_FAILED);

public HashMap<String, Double> getMinMaxSumAvgCount() throws CustomSQLException {

HashMap<String, Double> functionMap = new HashMap<String, Double>();

List<Double> min = getDataBasedOnQuery(

"select min(salary),gender from employee_payroll where is_active = true group by gender");

List<Double> max = getDataBasedOnQuery(

"select max(salary),gender from employee_payroll where is_active = true group by gender");

List<Double> sum = getDataBasedOnQuery(

"select sum(salary),gender from employee_payroll where is_active = true group by gender");

List<Double> avg = getDataBasedOnQuery(

"select avg(salary),gender from employee_payroll where is_active = true group by gender;");

List<Double> count = getDataBasedOnQuery(

"select count(*),gender from employee_payroll where is_active = true group by gender;");

functionMap.put("minMale", min.get(0));

functionMap.put("minFemale", min.get(1));

functionMap.put("maxMale", max.get(0));

functionMap.put("maxFemale", max.get(1));

functionMap.put("sumMale", sum.get(0));

functionMap.put("sumFemale", sum.get(1));

functionMap.put("avgMale", avg.get(0));
functionMap.put("avgFemale", avg.get(1));

functionMap.put("countMale", count.get(0));

functionMap.put("countFemale", count.get(1));

return functionMap;

public List<Double> getDataBasedOnQuery(String query) throws CustomSQLException {

List<Double> functionList = new ArrayList<Double>();

Statement statement;

ResultSet result;

try (Connection connection = this.getConnection();) {

statement = connection.createStatement();

result = statement.executeQuery(query);

int i = 0;

while (result.next()) {

i = i + 1;

functionList.add(result.getDouble(1));

return functionList;

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.QUERY_FAILED);

public EmployeePayRoll addEmployee(String name, String gender, double salary, LocalDate startDate)

throws CustomSQLException {

int employeeId = 0;

EmployeePayRoll employee = null;


String query = String.format(

"insert into employee_payroll(name,gender,salary,startdate) " + "values('%s','%s',%s,'%s')",


name,

gender, salary, startDate);

try (Connection connection = this.getConnection();) {

Statement statement = connection.createStatement();

int rowAffected = statement.executeUpdate(query, statement.RETURN_GENERATED_KEYS);

if (rowAffected == 1) {

ResultSet result = statement.getGeneratedKeys();

if (result.next())

employeeId = result.getInt(1);

return employee;

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.ADD_FAILED);

public EmployeePayRoll addEmployeeAndPayRoll(String name, String gender, double salary, int


companyId,

List<String> departments, List<LocalDate> dates) throws CustomSQLException {

String departmentName = departments.get(0);

LocalDate startDate = dates.get(0);

int employeeId = 0;

EmployeePayRoll employee = null;

String query = String.format(

"insert into employee_payroll(name,gender,salary,company_id) " + "values('%s','%s',%s,'%s')",


name,

gender, salary, companyId);


Connection connection = null;

try {

connection = this.getConnection();

connection.setAutoCommit(false);

} catch (SQLException e2) {

e2.printStackTrace();

try (Statement statement = connection.createStatement();) {

int rowAffected = statement.executeUpdate(query, statement.RETURN_GENERATED_KEYS);

if (rowAffected == 1) {

ResultSet result = statement.getGeneratedKeys();

if (result.next())

employeeId = result.getInt(1);

} catch (SQLException e) {

try {

connection.rollback();

return employee;

} catch (SQLException e1) {

e1.printStackTrace();

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.ADD_FAILED);

int departmentId = 0;

try {

query = String.format("select * from department where name = '%s'", departmentName);


Statement statement = connection.createStatement();

ResultSet result3 = statement.executeQuery(query);

while (result3.next()) {

departmentId = (result3.getInt("id"));

} catch (SQLException e2) {

try {

connection.rollback();

} catch (SQLException e1) {

e1.printStackTrace();

throw new CustomSQLException(e2.getMessage(),


CustomSQLException.Exception_Type.ADD_FAILED);

query = String.format("insert into employee_department(emp_id,dept_id,start_date) " +


"values('%s',%s,'%s')",

employeeId, departmentId, startDate);

try (Statement statement = connection.createStatement();) {

int rowAffected = statement.executeUpdate(query);

} catch (SQLException e) {

try {

connection.rollback();

} catch (SQLException e1) {

e1.printStackTrace();

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.ADD_FAILED);

try (Statement statement = connection.createStatement();) {


double basic_pay = salary;

double deductions = salary * 0.2;

double taxablePay = salary - deductions;

double tax = taxablePay * 0.1;

double netPay = salary - tax;

query = String.format("insert into


payroll_details(emp_id,basic_pay,deductions,taxable_pay,tax,net_pay) "

+ "values(%s,%s,%s,%s,%s,%s)", employeeId, basic_pay, deductions, taxablePay, tax, netPay);

int rowAffected = statement.executeUpdate(query);

if (rowAffected == 1) {

List<String> departmentNameList = new ArrayList<String>();

departmentNameList.add(departmentName);

List<LocalDate> startDates = new ArrayList<LocalDate>();

startDates.add(startDate);

employee = new EmployeePayRoll(employeeId, name, gender, salary, companyId,


departmentNameList,

startDates);

} catch (SQLException e) {

try {

connection.rollback();

} catch (SQLException e1) {

e1.printStackTrace();

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.ADD_FAILED);

try {

connection.commit();

} catch (SQLException e1) {


e1.printStackTrace();

} finally {

if (connection != null)

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

return employee;

public List<EmployeePayRoll> deleteEmployee(String name) throws CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();

String query = String.format("update employee_payroll set is_active = false where name = '%s'",
name);

Statement statement;

int result = 0;

try (Connection connection = this.getConnection();) {

statement = connection.createStatement();

result = statement.executeUpdate(query);

employeePayRollList = readData();

for (int i = 0; i < employeePayRollList.size(); i++) {

EmployeePayRoll employee = employeePayRollList.get(i);

if (employee.getName().equals(name)) {

employeePayRollList.remove(employee);

return employeePayRollList;
} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.READ_FAILED);

private Connection getConnection() throws CustomSQLException {

String jdbcURL = "jdbc:mysql://localhost:3306/employee_payroll_service?useSSL=false";

String userName = "root";

String password = "Manasi@1998";

Connection connection = null;

try {

connection = DriverManager.getConnection(jdbcURL, userName, password);

} catch (SQLException e) {

throw new CustomSQLException(e.getMessage(),


CustomSQLException.Exception_Type.CONNECTION_FAILED);

return connection;

public EmployeePayRoll getEmployee(String name) throws CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();

employeePayRollList = this.readData();

return employeePayRollList.stream().filter(e -> e.getName().equals(name)).findFirst().orElse(null);

public List<EmployeePayRoll> getDatafromResultset(ResultSet result) throws CustomSQLException {

List<EmployeePayRoll> employeePayRollList = new ArrayList<EmployeePayRoll>();


try {

while (result.next()) {

List<LocalDate> startDates = new ArrayList<LocalDate>();

List<Integer> department_id = new ArrayList<Integer>();

List<String> department_name = new ArrayList<String>();

try (Connection connection = this.getConnection();) {

PreparedStatement preparedStatement1 = connection

.prepareStatement("select * from employee_department where emp_id = ?");

preparedStatement1.setInt(1, result.getInt("id"));

ResultSet result1 = preparedStatement1.executeQuery();

while (result1.next()) {

startDates.add(result1.getDate("start_date").toLocalDate());

department_id.add(result1.getInt("dept_id"));

for (int i : department_id) {

PreparedStatement preparedStatement2 = connection

.prepareStatement("select * from department where id = ?");

preparedStatement2.setInt(1, i);

ResultSet result2 = preparedStatement2.executeQuery();

while (result2.next()) {

department_name.add(result2.getString("name"));

employeePayRollList.add(

new EmployeePayRoll(result.getInt("id"), result.getString("name"),


result.getString("gender"),
result.getDouble("salary"), result.getInt("company_id"), department_name,
startDates));

} catch (SQLException e) {

e.printStackTrace();

return employeePayRollList;

package com.capgemini.employeepayrollJDBC;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Enumeration;

import com.mysql.cj.jdbc.Driver;

public class EmployeePayrollJDBC {

static String url = "jdbc:mysql://localhost:3306/employee_payroll?useSSL=false";

static String userName = "root";

static String password = "Manasi@1998";

private static Connection con = null;

public static Connection getConnection() {

try {

Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, userName, password);

System.out.println("Connection Successful");

} catch (ClassNotFoundException e) {

throw new IllegalStateException("cannot find the driver");

} catch (SQLException e) {

e.printStackTrace();

listAllDrivers();

try {

System.out.println("Connecting to database" + url);

con = DriverManager.getConnection(url, userName, password);

System.out.println("Connected successfully " + con);

} catch (Exception e) {

e.printStackTrace();

return con;

private static void listAllDrivers() {

Enumeration<java.sql.Driver> driverList = DriverManager.getDrivers();

while (driverList.hasMoreElements()) {

Driver driver = (Driver) driverList.nextElement();

System.out.println(" " + driver.getClass().getName());

package com.capgemini.employeepayrollJDBC;
import java.time.LocalDate;

import java.util.*;

public class EmployeePayService {

private static List<EmployeePayRoll> empPayRollList;

private static EmployeePayrollDBService EmployeePayrollDBService;

private static Scanner sc = new Scanner(System.in);

public EmployeePayService(List<EmployeePayRoll> empPayRollList) {

this();

this.empPayRollList = empPayRollList;

public EmployeePayService() {

EmployeePayrollDBService = EmployeePayrollDBService.getInstance();

public static void main(String[] args) {

ArrayList<EmployeePayRoll> empPayRollList = new ArrayList<EmployeePayRoll>();

EmployeePayService empPayRollService = new EmployeePayService(empPayRollList);

empPayRollService.readData();

empPayRollService.writeData("Console");

public static void readData() {

System.out.println("Please Enter the following details :");


System.out.println("Enter ID");

int id = sc.nextInt();

sc.nextLine();

System.out.println("Enter Name :");

String name = sc.nextLine();

System.out.println("Enter Salary :");

double salary = sc.nextDouble();

EmployeePayRoll empPayRollObject = new EmployeePayRoll(id, name, salary);

empPayRollList.add(empPayRollObject);

public int readData(String source) throws CustomSQLException {

if (source.equals("File")) {

empPayRollList = new EmployeeFile().readData();

return empPayRollList.size();

} else if (source.equals("DB")) {

empPayRollList = EmployeePayrollDBService.readData();

return empPayRollList.size();

return 0;

public void updateSalary(int n, String name, Double salary) throws CustomSQLException {

int success = EmployeePayrollDBService.updateSalary(n, name, salary);

if (success == 1) {

for (EmployeePayRoll e : empPayRollList) {

if (e.getName().equals(name)) {

e.setSalary(salary);
}

public void writeData(String destination) {

if (destination.equals("Console"))

System.out.println("Employee Pay Roll Data : \n" + empPayRollList.get(0).toString());

else if (destination.equals("File"))

new EmployeeFile().writeData(empPayRollList);

public int noOfEntries(String destination) {

if (destination.equals("Console"))

return empPayRollList.size();

else if (destination.equals("File"))

return new EmployeeFile().noOfEntries();

return 0;

public void printData(String destination) {

if (destination.equals("Console"))

for (EmployeePayRoll e : empPayRollList) {

System.out.println(e.toString() + "\n");

else if (destination.equals("File"))

new EmployeeFile().printData();

}
public boolean checkDBInSyncWithList(String name) throws CustomSQLException {

EmployeePayRoll employeeDB = EmployeePayrollDBService.getEmployee(name);

EmployeePayRoll employeeList = getEmployee(name);

return employeeDB.equals(employeeList);

private EmployeePayRoll getEmployee(String name) {

return empPayRollList.stream().filter(e -> e.getName().equals(name)).findFirst().orElse(null);

public EmployeePayRoll preparedStatementReadData(String name) throws CustomSQLException {

return EmployeePayrollDBService.preparedStatementReadData(name);

public List<EmployeePayRoll> getDataInDateRange(String startDate, String endDate) throws


CustomSQLException {

return EmployeePayrollDBService.getDataInDateRange(startDate, endDate);

public HashMap<String, Double> getMinMaxSumAvgCount() throws CustomSQLException {

return EmployeePayrollDBService.getMinMaxSumAvgCount();

public void addEmployee(String name, String gender, double salary, LocalDate startDate) throws
CustomSQLException {

EmployeePayRoll employee = EmployeePayrollDBService.addEmployee(name, gender, salary,


startDate);

if (employee != null)

empPayRollList.add(employee);
}

public void addEmployeeAndPayRoll(String name, String gender, double salary, int companyId,

List<String> departmentName, List<LocalDate> startDate) throws CustomSQLException {

EmployeePayRoll employee = EmployeePayrollDBService.addEmployeeAndPayRoll(name, gender,


salary, companyId,

departmentName, startDate);

if (employee != null)

empPayRollList.add(employee);

public void deleteEmployee(String name) throws CustomSQLException {

empPayRollList = EmployeePayrollDBService.deleteEmployee(name);

public boolean checkIFDeletedFromList(String name) {

boolean result = false;

for (EmployeePayRoll e : empPayRollList) {

if (e.getName().equals(name)) {

System.out.println(e.getName());

result = true;

return result;

public int addEmployeeAndPayRoll(List<EmployeePayRoll> employeeList) {

employeeList.forEach(e -> {
System.out.println("Employee adding : " + e.getName());

try {

this.addEmployeeAndPayRoll(e.name, e.gender, e.salary, e.companyId, e.departmentName,


e.startDate);

} catch (CustomSQLException e1) {

e1.printStackTrace();

System.out.println("Employee added : " + e.getName());

});

System.out.println(empPayRollList.size());

return empPayRollList.size();

public int addEmployeeAndPayRollWithThread(List<EmployeePayRoll> employeeList) {

HashMap<Integer, Boolean> additionStatus = new HashMap<Integer, Boolean>();

employeeList.forEach(e -> {

Runnable task = () -> {

additionStatus.put(e.hashCode(), false);

System.out.println("Employee adding : " + Thread.currentThread().getName());

try {

this.addEmployeeAndPayRoll(e.name, e.gender, e.salary, e.companyId, e.departmentName,


e.startDate);

} catch (CustomSQLException e1) {

e1.printStackTrace();

additionStatus.put(e.hashCode(), true);

System.out.println("Employee added : " + Thread.currentThread().getName());

};
Thread thread = new Thread(task, e.name);

thread.start();

});

while (additionStatus.containsValue(false)) {

try {

Thread.sleep(10);

} catch (InterruptedException e) {

e.printStackTrace();

return empPayRollList.size();

package com.capgemini.employeepayrollJDBC;

import org.junit.*;

import java.time.Duration;

import java.time.Instant;

import java.time.LocalDate;

import java.util.*;

public class EmployeePayrollJDBCTest {

@Test

public void given3Employees_StoreToFile_ShouldPassTest() {

ArrayList<EmployeePayRoll> empPayRoll = new ArrayList<EmployeePayRoll>();


empPayRoll.add(new EmployeePayRoll(1, "Bill Gates", 1000000));

empPayRoll.add(new EmployeePayRoll(2, "Mark Zuckerburg", 500000));

EmployeePayService empPayRollService = new EmployeePayService(empPayRoll);

empPayRollService.writeData("File");

empPayRollService.printData("File");

int entries = empPayRollService.noOfEntries("File");

boolean result = entries == 2 ? true : false;

Assert.assertTrue(result);

@Test

public void readingFromFile_NoOfEntries_ShouldMatchActual() {

EmployeePayService empPayRollService = new EmployeePayService();

int entries;

try {

entries = empPayRollService.readData("File");

boolean result = entries == 2 ? true : false;

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void readingFromDB_NoOfEntries_ShouldMatchActual() {

EmployeePayService empPayRollService = new EmployeePayService();

int entries;

try {

entries = empPayRollService.readData("DB");
boolean result = entries == 7 ? true : false;

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenNewSalary_UpdatinginDB_ShouldMatch() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

empPayRollService.updateSalary(1, "Bill Gates", 90000.0);

boolean result = empPayRollService.checkDBInSyncWithList("Bill Gates");

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenNewSalary_UpdatinginDB_UsingPreparedStatement_ShouldMatch() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

empPayRollService.updateSalary(2, "Bill Gates", 80000.0);

boolean result = empPayRollService.checkDBInSyncWithList("Bill Gates");

Assert.assertTrue(result);

} catch (CustomSQLException e) {
e.printStackTrace();

@Test

public void giveName_RetreiveDataFromDB_UsingPreparedStatement_ShouldMatch() {

EmployeePayRoll employee;

LocalDate startDate = LocalDate.parse("2020-04-29");

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

employee = empPayRollService.preparedStatementReadData("Mark");

boolean result = employee.getStartDate().contains(startDate);

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void giveDateRange_RetreiveDataFromDB_UsingPreparedStatement_ShouldMatch() {

List<EmployeePayRoll> empPayRoll = new ArrayList<EmployeePayRoll>();

EmployeePayService empPayRollService = new EmployeePayService();

try {

empPayRoll = empPayRollService.getDataInDateRange("2010-04-29", "2018-04-29");

boolean result = empPayRoll.size() == 3;

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();
}

@Test

public void findMinMaxSumAvgcount_GroupedByGender_ShouldMatch() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

HashMap<String, Double> output = empPayRollService.getMinMaxSumAvgCount();

boolean result = output.get("minMale").equals(60000.0) &&


output.get("maxMale").equals(200000.0)

&& output.get("sumMale").equals(660000.0) && output.get("avgMale").equals(110000.0)

&& output.get("minFemale").equals(90000.0) && output.get("sumFemale").equals(90000.0)

&& output.get("countMale").equals(6.0) && output.get("countFemale").equals(1.0);

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenNewEmployee_WhenAdded_ShouldSyncWithDB() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

LocalDate startDate = LocalDate.parse("2008-09-01");

int companyId = 3;

String departmentName = "Management";

empPayRollService.addEmployeeAndPayRoll("Surya", "M", 100000.0, companyId,


Arrays.asList(departmentName),
Arrays.asList(startDate));

boolean result = empPayRollService.checkDBInSyncWithList("Surya");

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenNewEmployee_WhenAddedWithPayrollData_ShouldSyncWithDB() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

LocalDate startDate = LocalDate.parse("2016-11-04");

int companyId = 3;

String departmentName = "Sales";

empPayRollService.addEmployeeAndPayRoll("Suraj", "M", 60000.0, companyId,


Arrays.asList(departmentName),

Arrays.asList(startDate));

boolean result = empPayRollService.checkDBInSyncWithList("Suraj");

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenNewEmployee_WhenAddedWithPayrollDataNewERDiagram_ShouldSyncWithDB() {

EmployeePayService empPayRollService = new EmployeePayService();


try {

int entries = empPayRollService.readData("DB");

LocalDate startDate = LocalDate.parse("2019-01-29");

int companyId = 4;

String departmentName = "Sales";

empPayRollService.addEmployeeAndPayRoll("Rita", "F", 200000.0, companyId,


Arrays.asList(departmentName),

Arrays.asList(startDate));

boolean result = empPayRollService.checkDBInSyncWithList("Rita");

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test

public void givenEmployeeName_ShouldRemoveFromListAndDB() {

EmployeePayService empPayRollService = new EmployeePayService();

List<EmployeePayRoll> empPayRoll = new ArrayList<EmployeePayRoll>();

try {

int entries = empPayRollService.readData("DB");

System.out.println("before " + entries);

empPayRollService.deleteEmployee("Rita");

int entrie = empPayRollService.readData("DB");

System.out.println("after " + entrie);

boolean result = empPayRollService.checkIFDeletedFromList("Rita");

Assert.assertFalse(result);

} catch (CustomSQLException e) {

e.printStackTrace();
}

@Test

public void givenMultipleEmployee_WhenAddedToDB_ShouldMatchCountOfEntries() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

String departmentName = "Management";

EmployeePayRoll[] employeeArray = {

new EmployeePayRoll(0, "Manasi", "F", 130000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2018-05-21"))),

new EmployeePayRoll(0, "rinal", "F", 100000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2016-07-29"))),

new EmployeePayRoll(0, "Riya", "F", 70000.0, 4, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2015-08-07"))),

new EmployeePayRoll(0, "Kunal", "M", 60000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2017S-04-29"))) };

Instant start = Instant.now();

int countOfEntries = empPayRollService.addEmployeeAndPayRoll(Arrays.asList(employeeArray));

Instant end = Instant.now();

System.out.println("Duration without Thread : " + Duration.between(start, end));

boolean result = countOfEntries == 7 ? true : false;

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

@Test
public void givenMultipleEmployeeWithThreads_WhenAddedToDB_ShouldMatchCountOfEntries() {

EmployeePayService empPayRollService = new EmployeePayService();

try {

int entries = empPayRollService.readData("DB");

String departmentName = "Management";

EmployeePayRoll[] employeeArray = {

new EmployeePayRoll(0, "Ranju", "F", 400000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2008-05-01"))),

new EmployeePayRoll(0, "Kanika", "F", 200000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2011-07-29"))),

new EmployeePayRoll(0, "Sunita", "F", 90000.0, 4, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2017-07-07"))),

new EmployeePayRoll(0, "Soni", "F", 60000.0, 3, Arrays.asList(departmentName),

Arrays.asList(LocalDate.parse("2020-04-29"))) };

Instant start = Instant.now();

empPayRollService.addEmployeeAndPayRoll(Arrays.asList(employeeArray));

Instant end = Instant.now();

System.out.println("Duration without Thread : " + Duration.between(start, end));

Instant startThread = Instant.now();

int countOfEntries =
empPayRollService.addEmployeeAndPayRollWithThread(Arrays.asList(employeeArray));

Instant endThread = Instant.now();

System.out.println("Duration with Thread : " + Duration.between(startThread, endThread));

boolean result = countOfEntries == 11 ? true : false;

Assert.assertTrue(result);

} catch (CustomSQLException e) {

e.printStackTrace();

}
}

You might also like