Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created 5 API, added few of the validation, project level exception, JUNit test for few methods of controller and service #309

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions java-spring-api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ repositories {

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.7.2'
implementation 'org.springframework.boot:spring-boot-starter-validation:2.7.2'
runtimeOnly 'org.springframework.boot:spring-boot-devtools:2.7.2'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.7.2'
}

test {
useJUnitPlatform()
}

group = 'com.elsevier'
version = '1.0-SNAPSHOT'
description = 'java-sprin-api'
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.elsevier.javaspringapi.controller;

import com.elsevier.javaspringapi.exception.PatientNotFoundException;
import com.elsevier.javaspringapi.models.Patient;
import com.elsevier.javaspringapi.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/patients")
public class PatientsController {

@Autowired
private PatientService patientService;


@GetMapping()
public ResponseEntity<List<Patient>> fetchPatient() {
List<Patient> patientList = patientService.fetchPatientList();
if (!CollectionUtils.isEmpty(patientList)) {
return new ResponseEntity<>(patientService.fetchPatientList(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

@GetMapping("/{id}")
public ResponseEntity<Patient> fetchPatientByID(@PathVariable("id") UUID id) throws PatientNotFoundException {
return new ResponseEntity<>(patientService.fetchPatientById(id), HttpStatus.OK);
}

@PostMapping()
public ResponseEntity<String> savePatient(@Valid @RequestBody Patient patient) {
patientService.savePatient(patient);
return new ResponseEntity<>("Patient saved Successfully!!", HttpStatus.OK);
}

@PatchMapping("/{id}")
public ResponseEntity<String> updatePatients(@Valid @RequestBody Patient patient, @PathVariable("id") UUID id) throws PatientNotFoundException {
patientService.updatePatients(patient, id);
return new ResponseEntity<>("Patient Updated Successfully!!", HttpStatus.OK);
}

@DeleteMapping("/{id}")
public ResponseEntity<String> deletePatientById(@PathVariable("id") UUID id) throws PatientNotFoundException {
patientService.deletePatientById(id);
return new ResponseEntity<>("Patient deleted Successfully!!", HttpStatus.OK);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.elsevier.javaspringapi.exception;

public class PatientNotFoundException extends Exception {
public PatientNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.elsevier.javaspringapi.exceptionhandler;

import com.elsevier.javaspringapi.exception.PatientNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
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 MainExceptionHandler {

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
Map<String, String> errorMap = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errorMap.put(error.getField(), error.getDefaultMessage());
});
return errorMap;
}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(PatientNotFoundException.class)
public Map<String, String> handleBusinessException(PatientNotFoundException ex) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put("errorMessage", ex.getMessage());
return errorMap;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,106 @@
package com.elsevier.javaspringapi.models;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.UUID;

// TODO: implement this model

public class Patient {
public Patient() {}

//id* (uuid) Cannot have 2 ids equal
@NotNull(message = "id shouldn't be null")
private UUID id;

//firstName* (string)
@NotBlank(message = "firstName shouldn't be null or empty")
private String firstName;

//lastName* (string - dID)
@NotBlank(message = "lastName shouldn't be null or empty")
private String lastName;
@NotNull(message = "DOB shouldn't be null")
@Past(message = "The date of birth must be in the past.")
private Date dob;

@NotBlank(message = "SSN shouldn't be null or empty")
private String ssn;

@Pattern(regexp = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$", message = "Enter a valid phone number")
private String phoneNumber;

public Patient() {
}

public UUID getId() {
return id;
}

public void setId(UUID id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Date getDob() {
return dob;
}

public void setDob(Date dob) {
this.dob = dob;
}

public String getSsn() {
return ssn;
}

public void setSsn(String ssn) {
this.ssn = ssn;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public Patient(UUID id, String firstName, String lastName, Date dob, String ssn, String phoneNumber) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.ssn = ssn;
this.phoneNumber = phoneNumber;
}

@Override
public String toString() {
return "Patient{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dob=" + dob +
", ssn='" + ssn + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,67 @@
package com.elsevier.javaspringapi.repositories;

import com.elsevier.javaspringapi.models.Patient;
import jdk.jshell.spi.ExecutionControl;
import com.elsevier.javaspringapi.util.PatientUtils;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Repository
public class PatientRepository {

// TODO: Once the patient model is complete add some test patients here, 3 should be fine.
private List<Patient> patients = new ArrayList<>(){{
add(new Patient());
add(new Patient());
add(new Patient());

private List<Patient> patients = new ArrayList<>() {{
try {
add(new Patient(UUID.fromString("4ced7ec1-0048-4907-a871-d93bfb933ece"), "Rakesh", "Singha", PatientUtils.generateDate("01-01-1900"), "SSN", "123-321-3456"));
add(new Patient(UUID.fromString("2742971e-175f-41cd-a7d7-70d74eb70f30"), "Amit", "Kar", PatientUtils.generateDate("01-01-1980"), "SSN", "123-321-3456"));
add(new Patient(UUID.fromString("fb61d092-953c-4c72-b382-205377d4c9ea"), "Pramod", "Das", PatientUtils.generateDate("01-01-2020"), "SSN", "123-321-3456"));

} catch (ParseException e) {
throw new RuntimeException(e);
}
}};

// TODO: Implement these methods

public List<Patient> getPatients() {
return null;
return patients;
}

public Patient getPatient(UUID id) {
return null;
return patients.stream().filter(patient -> patient.getId().equals(id)).findFirst().get();
}

public void save(Patient patient) {

Patient newPatient = new Patient();
newPatient.setId(patient.getId());
newPatient.setFirstName(patient.getFirstName());
newPatient.setLastName(patient.getLastName());
newPatient.setDob(patient.getDob());
newPatient.setSsn(patient.getSsn());
newPatient.setPhoneNumber(patient.getPhoneNumber());
patients.add(newPatient);
}

public void delete(UUID id) {
public boolean delete(UUID id) {
return patients.removeIf(patient -> patient.getId().equals(id));
}

public Patient updatePatients(Patient patient, UUID id) {
for (Patient patients : patients) {
if (patients.getId().equals(id)) {
patients.setFirstName(patient.getFirstName());
patients.setId(patient.getId());
patients.setFirstName(patient.getLastName());
return patients;
}
}
return null;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.elsevier.javaspringapi.service;

import com.elsevier.javaspringapi.exception.PatientNotFoundException;
import com.elsevier.javaspringapi.models.Patient;

import java.util.List;
import java.util.UUID;

public interface PatientService {
public List<Patient> fetchPatientList();

public void savePatient(Patient patient);

void deletePatientById(UUID id) throws PatientNotFoundException;

Patient fetchPatientById(UUID id) throws PatientNotFoundException;

void updatePatients(Patient patient, UUID id) throws PatientNotFoundException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.elsevier.javaspringapi.service;

import com.elsevier.javaspringapi.exception.PatientNotFoundException;
import com.elsevier.javaspringapi.models.Patient;
import com.elsevier.javaspringapi.repositories.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

@Service
public class PatientServiceImpl implements PatientService {

@Autowired
private PatientRepository patientRepository;

@Override
public List<Patient> fetchPatientList() {
return patientRepository.getPatients();
}

@Override
public void savePatient(Patient patient) {
patientRepository.save(patient);
}

@Override
public void deletePatientById(UUID id) throws PatientNotFoundException {
if (!patientRepository.delete(id)) {
throw new PatientNotFoundException("Patient Not Available to delete with Id:" + id);
}
}

@Override
public Patient fetchPatientById(UUID id) throws PatientNotFoundException {
Optional<Patient> patient = null;
try {
patient = Optional.ofNullable(patientRepository.getPatient(id));
} catch (Exception ex) {
throw new PatientNotFoundException("Patient Not Available with Id:" + id);
}
return patient.get();
}

@Override
public void updatePatients(Patient patient, UUID id) throws PatientNotFoundException {
Patient newPatient = patientRepository.updatePatients(patient, id);
if (!Objects.nonNull(newPatient)) {
throw new PatientNotFoundException("Patient Not Available to update with Id:" + id);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.elsevier.javaspringapi.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PatientUtils {


//This method is created to generate Date based upon Input
public static Date generateDate(String dateValue) throws ParseException {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
return df.parse(dateValue);
}
}
Loading