From ca9c2c5116778d3b705e6eceddc953be73fd530b Mon Sep 17 00:00:00 2001 From: JanaDupcakova Date: Tue, 30 Jan 2024 20:06:16 +0100 Subject: [PATCH] added GET /upcoming-events endpoint and formated all classes --- .../sportsmatch/SportsmatchApplication.java | 318 ++++++++++-------- .../java/com/sportsmatch/auth/AuthConfig.java | 7 +- .../com/sportsmatch/auth/AuthService.java | 9 +- .../com/sportsmatch/auth/SecurityConfig.java | 53 +-- .../configs/ModelMapperConfig.java | 8 +- .../controllers/APIController.java | 10 +- .../controllers/AuthController.java | 14 +- .../controllers/EventsController.java | 59 ++-- .../com/sportsmatch/dtos/AuthResponseDTO.java | 2 +- .../java/com/sportsmatch/dtos/EventDTO.java | 28 +- .../com/sportsmatch/mappers/EventMapper.java | 49 ++- .../java/com/sportsmatch/models/Event.java | 76 +++-- .../com/sportsmatch/models/EventPlayer.java | 32 +- .../java/com/sportsmatch/models/Gender.java | 14 +- .../java/com/sportsmatch/models/Role.java | 4 +- .../java/com/sportsmatch/models/Sport.java | 22 +- .../com/sportsmatch/models/SportUser.java | 29 +- .../com/sportsmatch/models/SportUserKey.java | 44 +-- .../repositories/EventPlayerRepository.java | 4 +- .../repositories/EventRepository.java | 8 +- .../repositories/SportRepository.java | 2 +- .../repositories/SportUserRepository.java | 3 +- .../repositories/UserRepository.java | 4 +- .../sportsmatch/services/EventService.java | 114 ++++--- .../services/ValidationService.java | 10 +- 25 files changed, 499 insertions(+), 424 deletions(-) diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/SportsmatchApplication.java b/backend/sportsmatch/src/main/java/com/sportsmatch/SportsmatchApplication.java index e4737e26..ae1fbce3 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/SportsmatchApplication.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/SportsmatchApplication.java @@ -10,7 +10,6 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.servlet.config.annotation.EnableWebMvc; - import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; @@ -19,137 +18,192 @@ @SpringBootApplication @OpenAPIDefinition @EnableWebMvc - public class SportsmatchApplication implements CommandLineRunner { - private final UserRepository userRepository; - private final SportRepository sportRepository; - private final SportUserRepository sportUserRepository; - private final EventPlayerRepository eventPlayerRepository; - private final EventRepository eventRepository; - - private final PasswordEncoder passwordEncoder; - - public static void main(String[] args) { - SpringApplication.run(SportsmatchApplication.class, args); - } - - @Override - public void run(String... args) throws Exception { - addData(); - } - - public void addData() { - List sports = addSports(); - List users = addUsers(); - List sportUsers = addSportUsers(sports, users); - List events = addEvents(sports); - List eventPlayers = addEventPlayers(events, users); - } - - public List addEventPlayers(List events, List users) { - eventPlayerRepository.save(new EventPlayer(1, 3, users.get(0), events.get(0))); - eventPlayerRepository.save(new EventPlayer(3, 1, users.get(9), events.get(0))); - eventPlayerRepository.save(new EventPlayer(3, 2, users.get(1), events.get(1))); - eventPlayerRepository.save(new EventPlayer(3, 1, users.get(8), events.get(1))); - eventPlayerRepository.save(new EventPlayer(2, 2, users.get(2), events.get(2))); - eventPlayerRepository.save(new EventPlayer(2, 2, users.get(7), events.get(2))); - eventPlayerRepository.save(new EventPlayer(0, 1, users.get(3), events.get(3))); - eventPlayerRepository.save(new EventPlayer(1, 0, users.get(6), events.get(3))); - eventPlayerRepository.save(new EventPlayer(2, 1, users.get(4), events.get(4))); - eventPlayerRepository.save(new EventPlayer(1, 2, users.get(5), events.get(4))); - return eventPlayerRepository.findAll(); - } - - public List addEvents(List sports) { - eventRepository.save(new Event( - LocalDateTime.of(2024, 5, 1, 14, 30), - LocalDateTime.of(2024, 5, 1, 16, 30), - "Prague, Stadium A", 1200, 2000, - "Badminton match", sports.get(0))); - eventRepository.save(new Event( - LocalDateTime.of(2024, 7, 10, 18, 0), - LocalDateTime.of(2024, 7, 10, 20, 0), - "Brno, Gym", 1500, 2500, - "Boxing event", sports.get(1))); - eventRepository.save(new Event( - LocalDateTime.of(2024, 8, 5, 9, 0), - LocalDateTime.of(2024, 8, 5, 11, 0), - "Prague", 800, 1600, - "Table Tennis for beginners", sports.get(2))); - eventRepository.save(new Event( - LocalDateTime.of(2024, 9, 20, 15, 0), - LocalDateTime.of(2024, 9, 20, 17, 0), - "Prague, Squash Centre", 1400, 2200, - "Squash challenge", sports.get(3))); - eventRepository.save(new Event( - LocalDateTime.of(2024, 6, 15, 10, 0), - LocalDateTime.of(2024, 6, 15, 12, 0), - "Prague Stvanice", 1000, 1800, - "Tennis Open", sports.get(4))); - return eventRepository.findAll(); - } - - public List addSportUsers(List sports, List users) { - sportUserRepository.save(new SportUser(users.get(0), sports.get(0))); - sportUserRepository.save(new SportUser(users.get(9), sports.get(0))); - sportUserRepository.save(new SportUser(users.get(1), sports.get(1))); - sportUserRepository.save(new SportUser(users.get(8), sports.get(1))); - sportUserRepository.save(new SportUser(users.get(2), sports.get(2))); - sportUserRepository.save(new SportUser(users.get(7), sports.get(2))); - sportUserRepository.save(new SportUser(users.get(3), sports.get(3))); - sportUserRepository.save(new SportUser(users.get(6), sports.get(3))); - sportUserRepository.save(new SportUser(users.get(4), sports.get(4))); - sportUserRepository.save(new SportUser(users.get(5), sports.get(4))); - return sportUserRepository.findAll(); - } - - public List addUsers() { - userRepository.save( - new User( - "john.doe@example.com", - passwordEncoder.encode("pass123"), - "johndoe87", - Gender.MALE, - LocalDate.of(1990, 5, 15))); - userRepository.save(new User("alice.smith@example.com", - "securePass", "alice.smith", - Gender.FEMALE, LocalDate.of(1985, 11, 22))); - userRepository.save(new User("bob.jones@example.com", - "b0bPass", "bobjones22", - Gender.MALE, LocalDate.of(1992, 8, 10))); - userRepository.save(new User("emily.white@example.com", - "emilyPass", "em_white", - Gender.FEMALE, LocalDate.of(1988, 4, 3))); - userRepository.save(new User("mike.jackson@example.com", - "mjPass2020", "mikej", - Gender.MALE, LocalDate.of(1995, 12, 18))); - userRepository.save(new User("lisa.martin@example.com", - "lisaPass123", "lisa_m", - Gender.FEMALE, LocalDate.of(1998, 7, 25))); - userRepository.save(new User("chris.brown@example.com", - "cbrownPass", "chris_b", - Gender.MALE, LocalDate.of(1983, 9, 14))); - userRepository.save(new User("sarah.green@example.com", - "greenSarah", "s_green", - Gender.FEMALE, LocalDate.of(1993, 2, 9))); - userRepository.save(new User("ryan.miller@example.com", - "ryanPass456", "ryanm", - Gender.MALE, LocalDate.of(1987, 6, 30))); - userRepository.save(new User("jessica.ward@example.com", - "jessWard789", "jess_ward", - Gender.FEMALE, LocalDate.of(1991, 3, 12))); - - return userRepository.findAll(); - } - - public List addSports() { - sportRepository.save(new Sport("Badminton")); - sportRepository.save(new Sport("Boxing")); - sportRepository.save(new Sport("Table Tennis")); - sportRepository.save(new Sport("Squash")); - sportRepository.save(new Sport("Tennis")); - - return sportRepository.findAll(); - } + private final UserRepository userRepository; + private final SportRepository sportRepository; + private final SportUserRepository sportUserRepository; + private final EventPlayerRepository eventPlayerRepository; + private final EventRepository eventRepository; + + private final PasswordEncoder passwordEncoder; + + public static void main(String[] args) { + SpringApplication.run(SportsmatchApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + addData(); + } + + public void addData() { + List sports = addSports(); + List users = addUsers(); + List sportUsers = addSportUsers(sports, users); + List events = addEvents(sports); + List eventPlayers = addEventPlayers(events, users); + } + + public List addEventPlayers(List events, List users) { + eventPlayerRepository.save(new EventPlayer(1, 3, users.get(0), events.get(0))); + eventPlayerRepository.save(new EventPlayer(3, 1, users.get(9), events.get(0))); + eventPlayerRepository.save(new EventPlayer(3, 2, users.get(1), events.get(1))); + eventPlayerRepository.save(new EventPlayer(3, 1, users.get(8), events.get(1))); + eventPlayerRepository.save(new EventPlayer(2, 2, users.get(2), events.get(2))); + eventPlayerRepository.save(new EventPlayer(2, 2, users.get(7), events.get(2))); + eventPlayerRepository.save(new EventPlayer(0, 1, users.get(3), events.get(3))); + eventPlayerRepository.save(new EventPlayer(1, 0, users.get(6), events.get(3))); + eventPlayerRepository.save(new EventPlayer(2, 1, users.get(4), events.get(4))); + eventPlayerRepository.save(new EventPlayer(1, 2, users.get(5), events.get(4))); + return eventPlayerRepository.findAll(); + } + + public List addEvents(List sports) { + eventRepository.save( + new Event( + LocalDateTime.of(2024, 5, 1, 14, 30), + LocalDateTime.of(2024, 5, 1, 16, 30), + "Prague, Stadium A", + 1200, + 2000, + "Badminton match", + sports.get(0))); + eventRepository.save( + new Event( + LocalDateTime.of(2024, 7, 10, 18, 0), + LocalDateTime.of(2024, 7, 10, 20, 0), + "Brno, Gym", + 1500, + 2500, + "Boxing event", + sports.get(1))); + eventRepository.save( + new Event( + LocalDateTime.of(2024, 8, 5, 9, 0), + LocalDateTime.of(2024, 8, 5, 11, 0), + "Prague", + 800, + 1600, + "Table Tennis for beginners", + sports.get(2))); + eventRepository.save( + new Event( + LocalDateTime.of(2024, 9, 20, 15, 0), + LocalDateTime.of(2024, 9, 20, 17, 0), + "Prague, Squash Centre", + 1400, + 2200, + "Squash challenge", + sports.get(3))); + eventRepository.save( + new Event( + LocalDateTime.of(2024, 6, 15, 10, 0), + LocalDateTime.of(2024, 6, 15, 12, 0), + "Prague Stvanice", + 1000, + 1800, + "Tennis Open", + sports.get(4))); + return eventRepository.findAll(); + } + + public List addSportUsers(List sports, List users) { + sportUserRepository.save(new SportUser(users.get(0), sports.get(0))); + sportUserRepository.save(new SportUser(users.get(9), sports.get(0))); + sportUserRepository.save(new SportUser(users.get(1), sports.get(1))); + sportUserRepository.save(new SportUser(users.get(8), sports.get(1))); + sportUserRepository.save(new SportUser(users.get(2), sports.get(2))); + sportUserRepository.save(new SportUser(users.get(7), sports.get(2))); + sportUserRepository.save(new SportUser(users.get(3), sports.get(3))); + sportUserRepository.save(new SportUser(users.get(6), sports.get(3))); + sportUserRepository.save(new SportUser(users.get(4), sports.get(4))); + sportUserRepository.save(new SportUser(users.get(5), sports.get(4))); + return sportUserRepository.findAll(); + } + + public List addUsers() { + userRepository.save( + new User( + "john.doe@example.com", + passwordEncoder.encode("pass123"), + "johndoe87", + Gender.MALE, + LocalDate.of(1990, 5, 15))); + userRepository.save( + new User( + "alice.smith@example.com", + "securePass", + "alice.smith", + Gender.FEMALE, + LocalDate.of(1985, 11, 22))); + userRepository.save( + new User( + "bob.jones@example.com", + "b0bPass", + "bobjones22", + Gender.MALE, + LocalDate.of(1992, 8, 10))); + userRepository.save( + new User( + "emily.white@example.com", + "emilyPass", + "em_white", + Gender.FEMALE, + LocalDate.of(1988, 4, 3))); + userRepository.save( + new User( + "mike.jackson@example.com", + "mjPass2020", + "mikej", + Gender.MALE, + LocalDate.of(1995, 12, 18))); + userRepository.save( + new User( + "lisa.martin@example.com", + "lisaPass123", + "lisa_m", + Gender.FEMALE, + LocalDate.of(1998, 7, 25))); + userRepository.save( + new User( + "chris.brown@example.com", + "cbrownPass", + "chris_b", + Gender.MALE, + LocalDate.of(1983, 9, 14))); + userRepository.save( + new User( + "sarah.green@example.com", + "greenSarah", + "s_green", + Gender.FEMALE, + LocalDate.of(1993, 2, 9))); + userRepository.save( + new User( + "ryan.miller@example.com", + "ryanPass456", + "ryanm", + Gender.MALE, + LocalDate.of(1987, 6, 30))); + userRepository.save( + new User( + "jessica.ward@example.com", + "jessWard789", + "jess_ward", + Gender.FEMALE, + LocalDate.of(1991, 3, 12))); + + return userRepository.findAll(); + } + + public List addSports() { + sportRepository.save(new Sport("Badminton")); + sportRepository.save(new Sport("Boxing")); + sportRepository.save(new Sport("Table Tennis")); + sportRepository.save(new Sport("Squash")); + sportRepository.save(new Sport("Tennis")); + + return sportRepository.findAll(); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthConfig.java b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthConfig.java index 92e492d6..c6a79cc7 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthConfig.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthConfig.java @@ -1,6 +1,6 @@ package com.sportsmatch.auth; -import com.sportsmatch.repos.UserRepository; +import com.sportsmatch.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,8 +36,9 @@ public AuthenticationProvider authenticationProvider() { } @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { - return config.getAuthenticationManager(); + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) + throws Exception { + return config.getAuthenticationManager(); } @Bean diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthService.java b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthService.java index 1411f847..35d31c0c 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthService.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/AuthService.java @@ -4,7 +4,7 @@ import com.sportsmatch.dtos.AuthResponseDTO; import com.sportsmatch.mappers.UserMapper; import com.sportsmatch.models.User; -import com.sportsmatch.repos.UserRepository; +import com.sportsmatch.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; @@ -31,11 +31,10 @@ public void register(AuthRequestDTO authRequestDTO) { public AuthResponseDTO authenticate(AuthRequestDTO authRequestDTO) { authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken(authRequestDTO.getEmail(), authRequestDTO.getPassword())); + new UsernamePasswordAuthenticationToken( + authRequestDTO.getEmail(), authRequestDTO.getPassword())); User user = userRepository.findByEmail(authRequestDTO.getEmail()).orElseThrow(); String jwtToken = jwtService.generateToken(user); - return AuthResponseDTO.builder() - .token(jwtToken) - .build(); + return AuthResponseDTO.builder().token(jwtToken).build(); } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/SecurityConfig.java b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/SecurityConfig.java index cec0e267..b8b340d7 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/auth/SecurityConfig.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/auth/SecurityConfig.java @@ -19,28 +19,33 @@ @RequiredArgsConstructor public class SecurityConfig { - private static final String[] WHITE_LIST_URL = { - "/api/v1/auth/**", - "/h2-console/**", - "/v3/api-docs", - "/v3/api-docs/**", - "/swagger-ui/**" - // add endpoints that are not authenticated - }; - private final JwtAuthFilter jwtAuthFilter; - private final AuthenticationProvider authenticationProvider; - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // set which endpoints are authenticated and not - http - .csrf(AbstractHttpConfigurer::disable) - .headers(h -> h.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) // remove in production - .authorizeHttpRequests(r -> r - .requestMatchers(WHITE_LIST_URL) - .permitAll() - .anyRequest().authenticated()) - .sessionManagement(s -> s.sessionCreationPolicy(STATELESS)) - .authenticationProvider(authenticationProvider) - .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); - return http.build(); - } + private static final String[] WHITE_LIST_URL = { + "/api/v1/auth/**", + "/h2-console/**", + "/v3/api-docs", + "/v3/api-docs/**", + "/swagger-ui/**", + "/api/v1/event/{id}", + "/api/v1/event/upcoming-events", + "/api/v1/event/", + // add endpoints that are not authenticated + }; + private final JwtAuthFilter jwtAuthFilter; + private final AuthenticationProvider authenticationProvider; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) + throws Exception { // set which endpoints are authenticated and not + http.csrf(AbstractHttpConfigurer::disable) + .headers( + h -> + h.frameOptions( + HeadersConfigurer.FrameOptionsConfig::disable)) // remove in production + .authorizeHttpRequests( + r -> r.requestMatchers(WHITE_LIST_URL).permitAll().anyRequest().authenticated()) + .sessionManagement(s -> s.sessionCreationPolicy(STATELESS)) + .authenticationProvider(authenticationProvider) + .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/configs/ModelMapperConfig.java b/backend/sportsmatch/src/main/java/com/sportsmatch/configs/ModelMapperConfig.java index 5af961cd..1cccb729 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/configs/ModelMapperConfig.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/configs/ModelMapperConfig.java @@ -7,8 +7,8 @@ @Configuration public class ModelMapperConfig { - @Bean - public ModelMapper modelMapper() { - return new ModelMapper(); - } + @Bean + public ModelMapper modelMapper() { + return new ModelMapper(); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/APIController.java b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/APIController.java index f6a41a23..17fc661e 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/APIController.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/APIController.java @@ -10,9 +10,9 @@ @RequestMapping("/api/v1") public class APIController { - @GetMapping("/hello") - public String hello(Authentication authentication) { - User user = (User) authentication.getPrincipal(); - return "Welcome "+ user.getName() + " to Secured Endpoint "; - } + @GetMapping("/hello") + public String hello(Authentication authentication) { + User user = (User) authentication.getPrincipal(); + return "Welcome " + user.getName() + " to Secured Endpoint "; + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/AuthController.java b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/AuthController.java index cc9b8ce7..767b9b4b 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/AuthController.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/AuthController.java @@ -21,12 +21,11 @@ public class AuthController { private final ValidationService validationService; /** - * * @param authRequestDTO The authentication request containing user details. * @param bindingResult The result of the validation process. - * @return ResponseEntity indicating the success or failure of the registration. - * Returns a 400 Bad Request with validation errors (List) if input is invalid. - * Returns a 200 OK if registration is successful. + * @return ResponseEntity indicating the success or failure of the registration. Returns a 400 Bad + * Request with validation errors (List) if input is invalid. Returns a 200 OK if + * registration is successful. */ @PostMapping("/register") public ResponseEntity register( @@ -39,12 +38,11 @@ public ResponseEntity register( } /** - * * @param authRequestDTO The authentication request containing user credentials. * @param bindingResult The result of the validation process. - * @return ResponseEntity indicating the success or failure of the authentication. - * Returns a 400 Bad Request with validation errors if input is invalid. - * Returns a 200 OK with authentication details if authentication is successful. + * @return ResponseEntity indicating the success or failure of the authentication. Returns a 400 + * Bad Request with validation errors if input is invalid. Returns a 200 OK with + * authentication details if authentication is successful. */ @PostMapping("/authenticate") public ResponseEntity authenticate( diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/EventsController.java b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/EventsController.java index d577a7f4..496fd042 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/EventsController.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/controllers/EventsController.java @@ -8,34 +8,41 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import java.util.List; + @RestController @RequestMapping("/api/v1/event") public class EventsController { - private final EventService eventService; - - - public EventsController(EventService eventService) { - this.eventService = eventService; - - } - - @GetMapping("/{id}") - public ResponseEntity getEvent(@PathVariable("id") Long id) { - EventDTO eventDTO = eventService.getEventDTObyEventId(id); - return ResponseEntity.ok().body(eventDTO); - } - - @PostMapping("") - public ResponseEntity addEvent(@RequestBody @Valid EventDTO eventDTO) { - Event newEvent = eventService.createEvent(eventDTO); - return ResponseEntity.status(HttpStatus.CREATED).body(eventService.getEventDTObyEventId(newEvent.getId())); - } - - @DeleteMapping("/{id}") - public ResponseEntity deleteEvent(@PathVariable("id") Long id) { - Event eventById = eventService.getEventById(id); - eventService.deleteEventFromDatabase(eventById); - return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); - } + private final EventService eventService; + + public EventsController(EventService eventService) { + this.eventService = eventService; + } + + @GetMapping("/{id}") + public ResponseEntity getEvent(@PathVariable("id") Long id) { + EventDTO eventDTO = eventService.getEventDTObyEventId(id); + return ResponseEntity.ok().body(eventDTO); + } + + @PostMapping("") + public ResponseEntity addEvent(@RequestBody @Valid EventDTO eventDTO) { + Event newEvent = eventService.createEvent(eventDTO); + return ResponseEntity.status(HttpStatus.CREATED) + .body(eventService.getEventDTObyEventId(newEvent.getId())); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteEvent(@PathVariable("id") Long id) { + Event eventById = eventService.getEventById(id); + eventService.deleteEventFromDatabase(eventById); + return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); + } + + @GetMapping("/upcoming-events") + public ResponseEntity getUpcomingEvents(@RequestBody List sportsIds) { + List listOfEvents = eventService.getEventsBySports(sportsIds); + return ResponseEntity.ok().body(listOfEvents); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/AuthResponseDTO.java b/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/AuthResponseDTO.java index 94b35c97..0ad2bb55 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/AuthResponseDTO.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/AuthResponseDTO.java @@ -11,5 +11,5 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class AuthResponseDTO { - private String token; + private String token; } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/EventDTO.java b/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/EventDTO.java index dd3c12eb..2d04db68 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/EventDTO.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/dtos/EventDTO.java @@ -18,24 +18,16 @@ @NoArgsConstructor public class EventDTO { - private Long id; + private Long id; - @NotNull - private LocalDateTime dateStart; - @NotNull - private LocalDateTime dateEnd; - @NotBlank - private String location; - @NotNull - private Integer minElo; - @NotNull - private Integer maxElo; - @NotBlank - private String title; - - private Long player1Id; - private Long player2Id; - @NotBlank - private String sport; + @NotNull private LocalDateTime dateStart; + @NotNull private LocalDateTime dateEnd; + @NotBlank private String location; + @NotNull private Integer minElo; + @NotNull private Integer maxElo; + @NotBlank private String title; + private Long player1Id; + private Long player2Id; + @NotBlank private String sport; } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/mappers/EventMapper.java b/backend/sportsmatch/src/main/java/com/sportsmatch/mappers/EventMapper.java index b31d4dbd..9f448856 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/mappers/EventMapper.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/mappers/EventMapper.java @@ -12,32 +12,29 @@ @Component public class EventMapper { - private ModelMapper modelMapper; - - @Autowired - public EventMapper(ModelMapper modelMapper){ - this.modelMapper = modelMapper; - this.modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); - } - - public EventDTO convertEventToEventDTO(Event event){ - EventDTO eventDTO = modelMapper.map(event, EventDTO.class); - List eventPlayers = event.getPlayers().stream().toList(); - if (eventPlayers.size() > 0) { - eventDTO.setPlayer1Id(eventPlayers.get(0).getPlayer().getId()); - } - if (eventPlayers.size() > 1) { - eventDTO.setPlayer2Id(eventPlayers.get(1).getPlayer().getId()); - } - eventDTO.setSport(event.getSport().getName()); - return eventDTO; + private ModelMapper modelMapper; + + @Autowired + public EventMapper(ModelMapper modelMapper) { + this.modelMapper = modelMapper; + this.modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); + } + + public EventDTO convertEventToEventDTO(Event event) { + EventDTO eventDTO = modelMapper.map(event, EventDTO.class); + List eventPlayers = event.getPlayers().stream().toList(); + if (eventPlayers.size() > 0) { + eventDTO.setPlayer1Id(eventPlayers.get(0).getPlayer().getId()); } - - public Event convertEventDTOtoEvent(EventDTO eventDTO){ - modelMapper.typeMap(EventDTO.class, Event.class) - .addMappings(e -> e.skip(Event::setId)); - return modelMapper.map(eventDTO, Event.class); + if (eventPlayers.size() > 1) { + eventDTO.setPlayer2Id(eventPlayers.get(1).getPlayer().getId()); } - - + eventDTO.setSport(event.getSport().getName()); + return eventDTO; + } + + public Event convertEventDTOtoEvent(EventDTO eventDTO) { + modelMapper.typeMap(EventDTO.class, Event.class).addMappings(e -> e.skip(Event::setId)); + return modelMapper.map(eventDTO, Event.class); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Event.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Event.java index 6e208375..a48f7252 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Event.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Event.java @@ -18,39 +18,45 @@ @AllArgsConstructor public class Event { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column(name = "date_start") - private LocalDateTime dateStart; - - @Column(name = "date_end") - private LocalDateTime dateEnd; - - private String location; - - @Column(name = "min_elo") - private Integer minElo; - - @Column(name = "max_elo") - private Integer maxElo; - - private String title; - - @OneToMany(cascade = CascadeType.ALL, mappedBy = "event") - private Set players = new HashSet<>(); - - @ManyToOne - private Sport sport; - - public Event(LocalDateTime dateStart, LocalDateTime dateEnd, String location, Integer minElo, Integer maxElo, String title, Sport sport) { - this.dateStart = dateStart; - this.dateEnd = dateEnd; - this.location = location; - this.minElo = minElo; - this.maxElo = maxElo; - this.title = title; - this.sport = sport; - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "date_start") + private LocalDateTime dateStart; + + @Column(name = "date_end") + private LocalDateTime dateEnd; + + private String location; + + @Column(name = "min_elo") + private Integer minElo; + + @Column(name = "max_elo") + private Integer maxElo; + + private String title; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "event") + private Set players = new HashSet<>(); + + @ManyToOne private Sport sport; + + public Event( + LocalDateTime dateStart, + LocalDateTime dateEnd, + String location, + Integer minElo, + Integer maxElo, + String title, + Sport sport) { + this.dateStart = dateStart; + this.dateEnd = dateEnd; + this.location = location; + this.minElo = minElo; + this.maxElo = maxElo; + this.title = title; + this.sport = sport; + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/EventPlayer.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/EventPlayer.java index 0c23b9a5..2db507f0 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/EventPlayer.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/EventPlayer.java @@ -14,26 +14,24 @@ @AllArgsConstructor public class EventPlayer { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Column(name = "my_score") - private Integer myScore; + @Column(name = "my_score") + private Integer myScore; - @Column(name = "opponent_score") - private Integer opponentScore; + @Column(name = "opponent_score") + private Integer opponentScore; - @ManyToOne - private User player; + @ManyToOne private User player; - @ManyToOne - private Event event; + @ManyToOne private Event event; - public EventPlayer(Integer myScore, Integer opponentScore, User player, Event event) { - this.myScore = myScore; - this.opponentScore = opponentScore; - this.player = player; - this.event = event; - } + public EventPlayer(Integer myScore, Integer opponentScore, User player, Event event) { + this.myScore = myScore; + this.opponentScore = opponentScore; + this.player = player; + this.event = event; + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Gender.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Gender.java index 2293948f..fae2a09f 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Gender.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Gender.java @@ -4,12 +4,12 @@ @Getter public enum Gender { - MALE("Male"), - FEMALE("Female"), - OTHER("Other"); - private final String displayValue; + MALE("Male"), + FEMALE("Female"), + OTHER("Other"); + private final String displayValue; - Gender(String displayValue) { - this.displayValue = displayValue; - } + Gender(String displayValue) { + this.displayValue = displayValue; + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Role.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Role.java index af4110f4..3ab52124 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Role.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Role.java @@ -1,6 +1,6 @@ package com.sportsmatch.models; public enum Role { - USER, - ADMIN + USER, + ADMIN } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Sport.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Sport.java index 09e27563..415fd682 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/Sport.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/Sport.java @@ -16,19 +16,19 @@ @NoArgsConstructor @AllArgsConstructor public class Sport { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - private String name; + private String name; - @OneToMany(cascade = CascadeType.ALL, mappedBy = "sport") - private Set sportUsers = new HashSet<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "sport") + private Set sportUsers = new HashSet<>(); - @OneToMany(cascade = CascadeType.ALL, mappedBy = "sport") - private Set events = new HashSet<>(); + @OneToMany(cascade = CascadeType.ALL, mappedBy = "sport") + private Set events = new HashSet<>(); - public Sport(String name) { - this.name = name; - } + public Sport(String name) { + this.name = name; + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUser.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUser.java index c2a0f4f7..58176e62 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUser.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUser.java @@ -13,22 +13,21 @@ @Entity @Table(name = "sports_users") public class SportUser { - @EmbeddedId - private SportUserKey id; + @EmbeddedId private SportUserKey id; - @ManyToOne - @MapsId("userId") - @JoinColumn(name = "user_id") - private User user; + @ManyToOne + @MapsId("userId") + @JoinColumn(name = "user_id") + private User user; - @ManyToOne - @MapsId("sportId") - @JoinColumn(name = "sport_id") - private Sport sport; + @ManyToOne + @MapsId("sportId") + @JoinColumn(name = "sport_id") + private Sport sport; - public SportUser(User user, Sport sport) { - this.user = user; - this.sport = sport; - this.id = new SportUserKey(user.getId(), sport.getId()); - } + public SportUser(User user, Sport sport) { + this.user = user; + this.sport = sport; + this.id = new SportUserKey(user.getId(), sport.getId()); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUserKey.java b/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUserKey.java index 586edabc..df3df83f 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUserKey.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/models/SportUserKey.java @@ -15,26 +15,26 @@ @Embeddable public class SportUserKey implements Serializable { - @Column(name = "user_id") - private Long userId; - - @Column(name = "sport_id") - private Long sportId; - - public SportUserKey(Long userId, Long sportId) { - this.userId = userId; - this.sportId = sportId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SportUserKey that)) return false; - return Objects.equals(userId, that.userId) && Objects.equals(sportId, that.sportId); - } - - @Override - public int hashCode() { - return Objects.hash(userId, sportId); - } + @Column(name = "user_id") + private Long userId; + + @Column(name = "sport_id") + private Long sportId; + + public SportUserKey(Long userId, Long sportId) { + this.userId = userId; + this.sportId = sportId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SportUserKey that)) return false; + return Objects.equals(userId, that.userId) && Objects.equals(sportId, that.sportId); + } + + @Override + public int hashCode() { + return Objects.hash(userId, sportId); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventPlayerRepository.java b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventPlayerRepository.java index 68dd0df8..5a125630 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventPlayerRepository.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventPlayerRepository.java @@ -8,7 +8,7 @@ @Repository public interface EventPlayerRepository extends JpaRepository { - EventPlayer findEventPlayerById(Long id); + EventPlayer findEventPlayerById(Long id); - EventPlayer findEventPlayerByPlayer(User player); + EventPlayer findEventPlayerByPlayer(User player); } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventRepository.java b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventRepository.java index 2c05933b..c5d44dc1 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventRepository.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/EventRepository.java @@ -1,12 +1,18 @@ package com.sportsmatch.repositories; import com.sportsmatch.models.Event; + +import java.util.List; import java.util.Optional; + +import com.sportsmatch.models.Sport; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface EventRepository extends JpaRepository { - Optional findEventById(Long id); + Optional findEventById(Long id); + + List findAllBySportIdIn(List sport_id); } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportRepository.java b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportRepository.java index 255ebc60..20409e84 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportRepository.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportRepository.java @@ -8,5 +8,5 @@ @Repository public interface SportRepository extends JpaRepository { - Optional findSportByName(String name); + Optional findSportByName(String name); } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportUserRepository.java b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportUserRepository.java index f2a634f4..88ec8619 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportUserRepository.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/SportUserRepository.java @@ -6,5 +6,4 @@ import org.springframework.stereotype.Repository; @Repository -public interface SportUserRepository extends JpaRepository { -} +public interface SportUserRepository extends JpaRepository {} diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/UserRepository.java b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/UserRepository.java index 2d1c3e35..0ac3a8dc 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/UserRepository.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/repositories/UserRepository.java @@ -10,7 +10,7 @@ @Repository public interface UserRepository extends JpaRepository { - Optional findUserById(Long id); + Optional findUserById(Long id); - Optional findByEmail(String email); + Optional findByEmail(String email); } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/services/EventService.java b/backend/sportsmatch/src/main/java/com/sportsmatch/services/EventService.java index 2355c5ad..17faaab4 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/services/EventService.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/services/EventService.java @@ -22,65 +22,79 @@ @Service @AllArgsConstructor public class EventService { - private EventRepository eventRepository; - private EventMapper eventMapper; - private UserRepository userRepository; - private SportRepository sportRepository; - private EventPlayerRepository eventPlayerRepository; + private EventRepository eventRepository; + private EventMapper eventMapper; + private UserRepository userRepository; + private SportRepository sportRepository; + private EventPlayerRepository eventPlayerRepository; - public Event getEventById(Long id) { - return eventRepository.findEventById(id).orElseThrow(() -> new ResponseStatusException( - HttpStatus.BAD_REQUEST)); - } + public Event getEventById(Long id) { + return eventRepository + .findEventById(id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST)); + } - public EventDTO getEventDTObyEventId(Long id) { - Event event = - eventRepository.findEventById(id).orElseThrow(() -> new ResponseStatusException( - HttpStatus.BAD_REQUEST)); - EventDTO eventDTO = eventMapper.convertEventToEventDTO(event); - return eventDTO; - } + public EventDTO getEventDTObyEventId(Long id) { + Event event = + eventRepository + .findEventById(id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST)); + EventDTO eventDTO = eventMapper.convertEventToEventDTO(event); + return eventDTO; + } - public List getAllEvents() { - List eventList = eventRepository.findAll(); - List eventDTOList = new ArrayList<>(); - for (Event event : eventList) { - eventDTOList.add(getEventDTObyEventId(event.getId())); - } - return eventDTOList; + public List getAllEvents() { + List eventList = eventRepository.findAll(); + List eventDTOList = new ArrayList<>(); + for (Event event : eventList) { + eventDTOList.add(getEventDTObyEventId(event.getId())); } + return eventDTOList; + } - public EventPlayer addPlayerToEvent(Long playerId, Long eventId) { - EventPlayer eventPlayer = new EventPlayer(); - eventPlayer.setPlayer( - userRepository.findUserById(playerId).orElseThrow(() -> new ResponseStatusException( - HttpStatus.BAD_REQUEST))); - eventPlayer.setEvent( - eventRepository.findEventById(eventId).orElseThrow(() -> new ResponseStatusException( - HttpStatus.BAD_REQUEST)) - ); - return eventPlayerRepository.save(eventPlayer); + public List getEventsBySports(List sportsIds) { + List eventDTOList = new ArrayList<>(); + List eventListBySport = eventRepository.findAllBySportIdIn(sportsIds); + for (Event event : eventListBySport) { + eventDTOList.add(getEventDTObyEventId(event.getId())); } + return eventDTOList; + } - public Event createEvent(EventDTO eventDTO) { - Event newEvent = eventMapper.convertEventDTOtoEvent(eventDTO); - newEvent.setSport(sportRepository.findSportByName(eventDTO.getSport()).orElseThrow( - () -> new ResponseStatusException(HttpStatus.BAD_REQUEST))); - newEvent = eventRepository.save(newEvent); + public EventPlayer addPlayerToEvent(Long playerId, Long eventId) { + EventPlayer eventPlayer = new EventPlayer(); + eventPlayer.setPlayer( + userRepository + .findUserById(playerId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST))); + eventPlayer.setEvent( + eventRepository + .findEventById(eventId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST))); + return eventPlayerRepository.save(eventPlayer); + } - Set players = new HashSet<>(); - if (eventDTO.getPlayer1Id() != null) { - players.add(addPlayerToEvent(eventDTO.getPlayer1Id(), newEvent.getId())); - } - if (eventDTO.getPlayer2Id() != null) { - players.add(addPlayerToEvent(eventDTO.getPlayer2Id(), newEvent.getId())); - } + public Event createEvent(EventDTO eventDTO) { + Event newEvent = eventMapper.convertEventDTOtoEvent(eventDTO); + newEvent.setSport( + sportRepository + .findSportByName(eventDTO.getSport()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST))); + newEvent = eventRepository.save(newEvent); - newEvent.setPlayers(players); - return newEvent; + Set players = new HashSet<>(); + if (eventDTO.getPlayer1Id() != null) { + players.add(addPlayerToEvent(eventDTO.getPlayer1Id(), newEvent.getId())); } - - public void deleteEventFromDatabase(Event eventById) { - eventRepository.deleteById(eventById.getId()); + if (eventDTO.getPlayer2Id() != null) { + players.add(addPlayerToEvent(eventDTO.getPlayer2Id(), newEvent.getId())); } + + newEvent.setPlayers(players); + return newEvent; + } + + public void deleteEventFromDatabase(Event eventById) { + eventRepository.deleteById(eventById.getId()); + } } diff --git a/backend/sportsmatch/src/main/java/com/sportsmatch/services/ValidationService.java b/backend/sportsmatch/src/main/java/com/sportsmatch/services/ValidationService.java index 9cb5baf8..9914dc9e 100644 --- a/backend/sportsmatch/src/main/java/com/sportsmatch/services/ValidationService.java +++ b/backend/sportsmatch/src/main/java/com/sportsmatch/services/ValidationService.java @@ -9,9 +9,9 @@ @Service public class ValidationService { - public List getAllErrors(BindingResult bindingResult) { - return bindingResult.getAllErrors() - .stream().map(DefaultMessageSourceResolvable::getDefaultMessage) - .toList(); - } + public List getAllErrors(BindingResult bindingResult) { + return bindingResult.getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .toList(); + } }