0% found this document useful (0 votes)
759 views

Mini Project Spring Boot Project

This document contains code snippets from 6 Java files that define controllers and models for a medical appointment booking application. The ApplicationUserController handles user authentication and profile management. The AppointmentController manages appointment booking, viewing and deletion. The PatientController manages patient registration, listing, and deletion. The ApplicationUser, Appointment, and Patient models define the properties and relationships for users, appointments, and patients respectively.

Uploaded by

Hjhghh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
759 views

Mini Project Spring Boot Project

This document contains code snippets from 6 Java files that define controllers and models for a medical appointment booking application. The ApplicationUserController handles user authentication and profile management. The AppointmentController manages appointment booking, viewing and deletion. The PatientController manages patient registration, listing, and deletion. The ApplicationUser, Appointment, and Patient models define the properties and relationships for users, appointments, and patients respectively.

Uploaded by

Hjhghh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 18

01.ApplicationUserController.

java

package com.example.project.controller;

import com.example.project.Model.ApplicationUser;

import com.example.project.security.JwtUtil;
import com.example.project.service.ApplicationUserService;
import com.example.project.service.UserAuthService;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.web.bind.annotation.*;

@RestController
public class ApplicationUserController {

@Autowired
private ApplicationUserService applicationUserService;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserAuthService userAuthService;

@PostMapping("/register")
public String registerUser(@RequestBody ApplicationUser applicationUser) {

ApplicationUser user =
this.applicationUserService.createUser(applicationUser);
if (user != null) {
return "Registration successful";
}
return "Password or username policy failed";
}

@PostMapping("/signin")
public ResponseEntity<ApiResponse> signin(@RequestBody JwtAuthRequest request)
throws Exception {
System.out.println("USERNAME:"+request.getUsername());
this.authenticate(request.getUsername(), request.getPassword());
UserDetails
userDetails=this.userAuthService.loadUserByUsername(request.getUsername());
System.out.println("USERDetails:"+userDetails);
String token=this.jwtUtil.generateToken(userDetails);

if (token!=null){
ApplicationUser
user=applicationUserService.findUserByUsername(request.getUsername());
return new ResponseEntity<ApiResponse>(
new ApiResponse("Authentication
successful",token,user.getUser_name())
,HttpStatus.OK);
}
else{
return new ResponseEntity<ApiResponse>(new ApiResponse("Username or Password is
incorrect"),HttpStatus.CONFLICT);
}
}

@GetMapping("/viewprofile/{userId}")
public ApplicationUser getUserDetails(@PathVariable("userId") String user_name)
{
return this.applicationUserService.fetchApplicationUser(user_name);
}

@PutMapping("/editprofile/{userId}")
public ApplicationUser updateUser(@PathVariable("userId") String
user_name,@RequestBody ApplicationUser user){
return this.applicationUserService.editUser(user,user_name);
}

public void authenticate(String username,String password) throws Exception {


UsernamePasswordAuthenticationToken authenticationToken=new
UsernamePasswordAuthenticationToken(username, password);
System.out.println("USERNAME:"+username);
try {
this.authenticationManager.authenticate(authenticationToken);
}
catch (BadCredentialsException e) {
throw new Exception("Invalid username or password");

}
}

}
@Data
class ApiResponse{
private String message;
private String token;
private String userId;

public ApiResponse(String message, String token, String userId) {


this.message = message;
this.token = token;
this.userId = userId;
}

public ApiResponse(String message) {


}
}
@Data
class JwtAuthRequest {

private String username;


private String password;
}

02. AppointmentController.java

package com.example.project.controller;

import com.example.project.Model.Appointment;
import com.example.project.service.AppointmentService;
import com.example.project.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/appointment")
public class AppointmentController {

@Autowired
private AppointmentService appointmentService;

@Autowired
private PatientService patientService;

@PostMapping("/register")
public String registerAppointment(@RequestBody Appointment appointment) {
if (this.appointmentService.checkPatient(appointment.getPatientId())) {
this.appointmentService.addAppointment(appointment);
return "Booking successful";
} else {
return "Booking failure";
}
}

@GetMapping("/list")
public List<Appointment> getAllAppointments(){
return this.appointmentService.getAllAppointments();
}

@GetMapping("/view/{appointmentId}")
public Appointment getAppointment(@PathVariable("appointmentId") String
appointmentId){
return this.appointmentService.findAppointmentById(appointmentId);
}

@GetMapping("/list/{patientId}")
public List<Appointment> getAppointmentsByPatientId(@PathVariable("patientId")
String patientId){
return this.appointmentService.findAppointmentsByPatientId(patientId);
}

@DeleteMapping("/{appointmentId}")
public void deleteAppointment(@PathVariable("appointmentId") String
appointmentId){
this.appointmentService.deleteAppointment(appointmentId);
}
}

03. PatientController.java

package com.example.project.controller;

import com.example.project.Model.Patient;
import com.example.project.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

@Autowired
private PatientService patientService;

@PostMapping("/register")
public String registerPatient(@RequestBody Patient patient) {

Patient patient1 = this.patientService.registerPatient(patient);


if (patient1 != null) {
return "Registration Successful";
}
return "Registration failure";
}

@GetMapping("/list")
public List<Patient> getPatientsList() {
return this.patientService.fetchPatients();
}

@GetMapping("/view/{Id}")
public Patient getPatientDetails(@PathVariable("Id") String patientId) {
return this.patientService.fetchPatient(patientId);
}

@DeleteMapping("/delete/{Id}")
public void deletePatient(@PathVariable("Id") String patient_Id) {
this.patientService.deletePatient(patient_Id);
}
}
04. ApplicationUser.java

package com.example.project.Model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Collection;

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class ApplicationUser implements UserDetails {

@Id
public String user_name;
public String user_email;
public String password;

public String user_mobile;


public String location;

public ApplicationUser(String user_name, String password) {


this.user_name = user_name;
this.password = password;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}

@Override
public String getUsername() {
return this.user_name;
}

@Override
public String getPassword() {
return this.password;
}

@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
}

05. Appointment.java

package com.example.project.Model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Appointment {

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String booking_id;

private String disease;

private Date tentativeDate;


private String priority;
private String patientId;
private Date bookingTime;

public Appointment(String disease, Date tentativeDate, String priority, String


patientId) {
this.disease = disease;
this.tentativeDate = tentativeDate;
this.priority = priority;
this.patientId = patientId;

06. Patient.java

package com.example.project.Model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Patient {

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String patient_Id;

private String patient_name;


private String patient_email;
private String patient_mobile;
private Date registeredDate;

public Patient(String patient_name, String patient_email, String


patient_mobile, Date registeredDate) {
this.patient_name = patient_name;
this.patient_email = patient_email;
this.patient_mobile = patient_mobile;
this.registeredDate = registeredDate;

}
07. ApplicationUserRepository.java

package com.example.project.repository;

import com.example.project.Model.ApplicationUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

public interface ApplicationUserRepository extends


JpaRepository<ApplicationUser,String> {

@Query("select u from ApplicationUser u where u.user_name= :user_name")


Optional<ApplicationUser> findByUser_name(String user_name);
}

08. AppointmentRepository.java

package com.example.project.repository;

import com.example.project.Model.Appointment;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface AppointmentRepository extends JpaRepository<Appointment,String> {


List<Appointment> findAppointmentByPatientId(String patientId);
}

09. PatientRepository.java

package com.example.project.repository;

import com.example.project.Model.Patient;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PatientRepository extends JpaRepository<Patient,String> {


}
10. ApiAuthenticationEntryPoint.java

package com.example.project.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException,
ServletException {

response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied");

}
}

11. ApiSecurityConfig.java

package com.example.project.security;

import com.example.project.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import
org.springframework.security.config.annotation.method.configuration.EnableGlobalMet
hodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigu
rerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilte
r;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

public static final String[] PUBLIC_URLS = {

"/register",
"/h2-console/*",
"/signin"
};
@Autowired
private UserAuthService userAuthService;
@Autowired
private ApiAuthenticationEntryPoint apiAuthenticationEntryPoint;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {

http
.csrf()
.disable()
.authorizeRequests()
.antMatchers(PUBLIC_URLS).permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(this.apiAuthenticatio
nEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(this.jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.userDetailsService(this.userAuthService).passwordEncoder(passwordEncoder());

@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {

return super.authenticationManagerBean();
}

12. JwtAuthenticationFilter.java

package com.example.project.security;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import
org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private JwtUtil jwtUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {

// get token
String requestToken = request.getHeader("Authorization");

String username = null;

String token = null;

if (requestToken!= null && requestToken.startsWith("Bearer")) {


token = requestToken.substring(7);

try {
username = this.jwtUtil.getUsernameFromToken(token);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT token");
} catch (ExpiredJwtException e) {
System.out.println("Jwt tokn has expired");
} catch (MalformedJwtException e) {
System.out.println("Invalid JWT token");
}
} else {
System.out.println("JWT Token doesn't begin with bearer");
}

// once we get the token , now validate


if (username != null &&
SecurityContextHolder.getContext().getAuthentication() == null) {

UserDetails userDetails =
this.userDetailsService.loadUserByUsername(username);

if (this.jwtUtil.validateToken(token, userDetails)) {

UsernamePasswordAuthenticationToken
usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthentication
Token);

} else {
System.out.println("Invalid token");
}

} else {
System.out.println("Username is null or contect is not null");
}

filterChain.doFilter(request, response);
}
}

13. JwtUtil.java

package com.example.project.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtil {

private int jwtExpirationInMs;

private String secret;

@Value("${jwt.token.validity}")
public void setJwtExpirationInMs(int jwtExpirationInMs) {
this.jwtExpirationInMs = jwtExpirationInMs;
}

@Value("${jwt.secret}")
public void setSecret(String secret) {
this.secret = secret;
}

// retriev username from token


public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}

// retrieve expriration date from jwt token


public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}

public <T> T getClaimFromToken(String token, Function<Claims, T>


claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}

// for retrieving any information from token we will need the secret key
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}

// check if the token is expired


private boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}

// generate token for user


public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {

return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new
Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis()
+jwtExpirationInMs ))
.signWith(SignatureAlgorithm.HS512, secret).compact();
}

// ValidateToken
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !
isTokenExpired(token));
}

14. ApplicationUserService.java

package com.example.project.service;

import com.example.project.Model.ApplicationUser;
import com.example.project.repository.ApplicationUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class ApplicationUserService {
@Autowired
private ApplicationUserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;

public ApplicationUser createUser(ApplicationUser applicationUser) {

applicationUser.setPassword(this.passwordEncoder.encode(applicationUser.getPassword
()));
return userRepository.save(applicationUser);
}

public ApplicationUser fetchApplicationUser(String userId) {


ApplicationUser user = this.userRepository.findById(userId)
.orElseThrow(() -> new UsernameNotFoundException("user not
found"));
return user;
}
public ApplicationUser editUser(ApplicationUser user, String userId) {
ApplicationUser applicationUser = this.userRepository.findById(userId)
.orElseThrow(() -> new UsernameNotFoundException("user not
found"));
applicationUser.setUser_email(user.getUser_email());
applicationUser.setUser_name(user.getUser_name());
applicationUser.setUser_mobile(user.getUser_mobile());
applicationUser.setLocation(user.getLocation());
applicationUser.setPassword(user.getPassword());
return userRepository.save(applicationUser);
}

public ApplicationUser findUserByUsername(String username) {


ApplicationUser user=this.userRepository.findByUser_name(username).get();
return user;
}
}

15. AppointmentService.java

package com.example.project.service;

import com.example.project.Model.Appointment;
import com.example.project.Model.Patient;
import com.example.project.repository.AppointmentRepository;
import com.example.project.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

@Service
public class AppointmentService {

@Autowired
private AppointmentRepository appointmentRepository;

@Autowired
private PatientService patientService;

@Autowired
private PatientRepository patientrepository;

public Appointment addAppointment(Appointment appointment) {


return this.appointmentRepository.save(appointment);
}

public void deleteAppointment(String booking_id) {


Appointment appointment =findAppointmentById(booking_id);
this.appointmentRepository.delete(appointment);
}

public List<Appointment> getAllAppointments() {

return appointmentRepository.findAll();
}

public Appointment findAppointmentById(String booking_id) {


Appointment appointment = appointmentRepository.findById(booking_id)
.orElseThrow(() -> new NoSuchElementException("No appointment find
for given id"));
return appointment;
}

public List<Appointment> findAppointmentsByPatientId(String patient_id) {


List<Appointment> appointmentList = new ArrayList<>();
if (checkPatient(patient_id)) {
appointmentList =
this.appointmentRepository.findAppointmentByPatientId(patient_id);
}
return appointmentList;

public boolean checkPatient(String patient_id){


Optional<Patient> patient=this.patientrepository.findById(patient_id);
if (patient.isPresent()){
return true;
}
return false;
}
}

16. PatientService.java

package com.example.project.service;

import com.example.project.Model.Patient;
import com.example.project.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class PatientService {

@Autowired
private PatientRepository patientrepository;
public Patient registerPatient(Patient patient) {
return patientrepository.save(patient);
}

public Patient fetchPatient(String patientId) {


System.out.println("patientId:"+patientId);
Optional<Patient> patient = this.patientrepository.findById(patientId);
if (!patient.isPresent()) {
System.out.println("Patient not found");
}
return patient.get();

public List<Patient> fetchPatients() {


return patientrepository.findAll();
}

public void deletePatient(String patient_id) {


Patient patient = fetchPatient(patient_id);
this.patientrepository.delete(patient);
}

17. UserAuthService.java

package com.example.project.service;

import com.example.project.Model.ApplicationUser;
import com.example.project.repository.ApplicationUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserAuthService implements UserDetailsService {

@Autowired
private ApplicationUserRepository userRepo;

@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
ApplicationUser user = this.userRepo.findByUser_name(username)
.orElseThrow(() -> new UsernameNotFoundException("Username not
found"));
return user;
}
}
12. ApplicationUserRepository.java

package com.example.project.repository;

import com.example.project.Model.ApplicationUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

public interface ApplicationUserRepository extends


JpaRepository<ApplicationUser,String> {

@Query("select u from ApplicationUser u where u.user_name= :user_name")


Optional<ApplicationUser> findByUser_name(String user_name);
}

You might also like