Changeset 0f5aa27 for src/main/java/com


Ignore:
Timestamp:
02/04/24 16:57:49 (10 months ago)
Author:
darsov2 <62809499+darsov2@…>
Branches:
master
Children:
efaa053
Parents:
07f4e8b
Message:

ouath, mailing impl

Location:
src/main/java/com/tourMate
Files:
22 added
4 deleted
27 edited

Legend:

Unmodified
Added
Removed
  • src/main/java/com/tourMate/TourMateApplication.java

    r07f4e8b r0f5aa27  
    33import org.springframework.boot.SpringApplication;
    44import org.springframework.boot.autoconfigure.SpringBootApplication;
     5import org.springframework.context.annotation.Bean;
     6import org.springframework.mail.javamail.JavaMailSender;
     7import org.springframework.mail.javamail.JavaMailSenderImpl;
     8import org.springframework.scheduling.annotation.EnableScheduling;
     9import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
     10import org.springframework.security.crypto.password.PasswordEncoder;
    511import org.springframework.transaction.annotation.EnableTransactionManagement;
     12
     13import java.util.Properties;
    614
    715@SpringBootApplication
    816@EnableTransactionManagement
     17@EnableScheduling
    918public class TourMateApplication {
    1019
     
    1322        }
    1423
     24        @Bean
     25        public PasswordEncoder passwordEncoder() {
     26                return new BCryptPasswordEncoder();
     27        }
     28
     29        @Bean
     30        public JavaMailSender getJavaMailSender() {
     31                JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
     32                mailSender.setHost("smtp.gmail.com");
     33                mailSender.setPort(587);
     34
     35                mailSender.setUsername("trip2mk@gmail.com");
     36                mailSender.setPassword("xarb ggqg mvmr zciw");
     37
     38                Properties props = mailSender.getJavaMailProperties();
     39                props.put("mail.transport.protocol", "smtp");
     40                props.put("mail.smtp.auth", "true");
     41                props.put("mail.smtp.starttls.enable", "true");
     42                props.put("mail.debug", "true");
     43
     44                return mailSender;
     45        }
     46
    1547}
  • src/main/java/com/tourMate/config/SecurityConfig.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.config;
    22
    3 import com.fasterxml.jackson.databind.ObjectMapper;
    4 import jakarta.servlet.http.HttpServletResponse;
     3import com.tourMate.config.oauth2.CustomOAuth2FailureHandler;
     4import com.tourMate.config.oauth2.CustomOAuth2SuccessHandler;
     5import com.tourMate.config.oauth2.CustomOAuth2UserDetailService;
     6import org.springframework.beans.factory.annotation.Autowired;
    57import org.springframework.context.annotation.Bean;
    68import org.springframework.context.annotation.Configuration;
     
    1012import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    1113import org.springframework.security.config.http.SessionCreationPolicy;
    12 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    13 import org.springframework.security.crypto.password.PasswordEncoder;
    1414import org.springframework.security.web.SecurityFilterChain;
    1515import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
     
    2626
    2727    private final UserSecurity userSecurity;
     28    @Autowired
     29    private CustomOAuth2UserDetailService customOAuth2UserDetailService;
     30    @Autowired
     31    private CustomOAuth2FailureHandler oAuth2FailureHandler;
     32    @Autowired
     33    private CustomOAuth2SuccessHandler oAuth2SuccessHandler;
    2834
    2935    public SecurityConfig(UserSecurity userSecurity) {
     
    5662        return bean;
    5763    }
    58     @Bean
    59     public PasswordEncoder passwordEncoder() {
    60         return new BCryptPasswordEncoder();
    61     }
    6264
    6365    @Bean
     
    7678                                        .requestMatchers(new AntPathRequestMatcher("/upload")).permitAll()
    7779                                        .requestMatchers(new AntPathRequestMatcher("/business/approve/*")).hasAnyAuthority("SUPERADMIN")
     80                                        .requestMatchers(new AntPathRequestMatcher("/users/unlock/*")).hasAnyAuthority("SUPERADMIN")
     81                                        .requestMatchers(new AntPathRequestMatcher("/users/approve/*")).hasAnyAuthority("SUPERADMIN")
     82                                        .requestMatchers(new AntPathRequestMatcher("/business/unapproved")).hasAnyAuthority("SUPERADMIN")
    7883                                        .requestMatchers(new AntPathRequestMatcher("/business/add/*")).authenticated()
    7984                                        .requestMatchers(new AntPathRequestMatcher("/*/user/{userId}")).access(userSecurity)
    80                                         .anyRequest().permitAll()
    81 //                                        .anyRequest().authenticated()
     85//                                        .anyRequest().permitAll()
     86                                        .anyRequest().authenticated()
     87                                        .and()
     88                                        .oauth2Login()
     89                                        .loginPage("/login")
     90                                        .permitAll()
     91                                        .userInfoEndpoint(x -> x.userService(customOAuth2UserDetailService))
     92//                                        .userService(customOAuth2UserDetailService)
     93                                        .successHandler(oAuth2SuccessHandler)
     94                                        .failureHandler(oAuth2FailureHandler)
    8295                                        .and()
    8396                                        .formLogin()
    84                                         .loginProcessingUrl("/api/login").usernameParameter("username").passwordParameter("password")
    85                                         .successHandler((request, response, authentication) -> {
    86                                             response.setStatus(HttpServletResponse.SC_OK);
    87                                             response.setCharacterEncoding("UTF-8");
    88                                             response.setContentType("application/json");
    89                                             response.getWriter().print("{\"message\": \"Login successful\",");
    90                                             response.getWriter().print("\"auth\":" + new ObjectMapper().writeValueAsString(authentication) + "}");
    91                                             response.getWriter().flush();
    92                                         })
    93                                         .failureHandler((request, response, exception) -> {
    94                                             response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    95                                             response.sendRedirect("/login");
    96                                             response.getWriter().print("Neuspesna najava\n" + exception.getMessage());
    97                                             response.getWriter().flush();
    98                                         })
     97                                        .loginPage("/login")
     98                                        .successHandler(oAuth2SuccessHandler)
     99                                        .permitAll()
    99100                                        .permitAll()
    100101                                        .and()
  • src/main/java/com/tourMate/config/UserSecurity.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.config;
    22
     3import com.tourMate.config.oauth2.CustomOAuth2UserDetailService;
     4import com.tourMate.config.oauth2.OAuth2UserDetailsCustom;
    35import com.tourMate.entities.Hotels;
    46import com.tourMate.entities.User;
     
    2527    public boolean hasUserId(Authentication authentication, Long userId) {
    2628        System.out.println(userId);
    27         User user = (User) authentication.getPrincipal();
    28         System.out.println(user.getUserID());
    29         System.out.println(authentication.getPrincipal());
    30         return userId == user.getUserID();
     29        Long id;
     30        if(authentication.getPrincipal() instanceof OAuth2UserDetailsCustom oAuth2UserDetailsCustom)
     31        {
     32            id = oAuth2UserDetailsCustom.getId();
     33        }
     34        else
     35        {
     36            User user = (User) authentication.getPrincipal();
     37            id = user.getUserID();
     38        }
     39        return userId == id;
    3140    }
    3241
  • src/main/java/com/tourMate/controllers/HotelController.java

    r07f4e8b r0f5aa27  
    3535            return ResponseEntity.ok(hoteli);
    3636        } catch (Exception e) {
    37             // Handle the exception, log it, and return an error response
    3837            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    3938        }
     
    4140
    4241    @GetMapping(path = "/hotel/user/{id}")
    43     public ResponseEntity<List<Hotels>> getHotelsForUser (@PathVariable(name = "id") long userId)
    44     {
    45         try {
    46 
     42    public ResponseEntity<List<Hotels>> getHotelsForUser(@PathVariable(name = "id") long userId) {
     43        try {
    4744            List<Hotels> hoteli = hotelManager.getHotelsForUser(userId);
    4845            return ResponseEntity.ok(hoteli);
     
    5350
    5451    @GetMapping(path = "/hotel/{id}/list")
    55     public ResponseEntity<Hotels> getHotelById (@PathVariable(name = "id") long hotelId)
    56     {
    57         try {
    58 
     52    public ResponseEntity<Hotels> getHotelById(@PathVariable(name = "id") long hotelId) {
     53        try {
    5954            return ResponseEntity.ok(hotelManager.findHotelByID(hotelId));
    6055        } catch (Exception e) {
     
    6560
    6661    @PostMapping(path = "/hotel/edit")
    67     public void edit(@RequestBody Hotels hotel)
    68     {
     62    public void edit(@RequestBody Hotels hotel) {
    6963        hotelManager.editHotel(hotel.getHotelId(), hotel.getHotelName(), hotel.getHotelDescripiton(), hotel.getHotelLocation(), hotel.getHotelEDBS(), hotel.getParking(), hotel.getPetFriendly(), hotel.getInternetAvailable());
    7064    }
     
    7266    @GetMapping(path = "/hotel/delete")
    7367    public ResponseEntity remove(@RequestParam(name = "hotelId") long hotelId) {
    74         try
    75         {
     68        try {
    7669            hotelManager.deleteHotel(hotelId);
    7770            return new ResponseEntity(HttpStatus.OK);
    78         }
    79         catch (Exception exception)
    80         {
    81             return new ResponseEntity(HttpStatus.NOT_FOUND);
    82         }
    83     }
    84 
     71        } catch (Exception exception) {
     72            return new ResponseEntity(HttpStatus.NOT_FOUND);
     73        }
     74    }
    8575
    8676
     
    9080            hotelManager.deleteHotelImage(hotelId);
    9181            return new ResponseEntity(HttpStatus.OK);
    92         }
    93         catch (Exception exception) {
     82        } catch (Exception exception) {
    9483            return new ResponseEntity(HttpStatus.NOT_FOUND);
    9584        }
     
    9786
    9887    @GetMapping(path = "/hotel/{id}/room")
    99     public List<HotelRoom> getHotelRooms(@PathVariable(value = "id") long hotelId)
    100     {
     88    public List<HotelRoom> getHotelRooms(@PathVariable(value = "id") long hotelId) {
    10189        System.out.println("ovde so id: " + hotelId);
    10290        return hotelManager.getRoomsOfHotel(hotelId);
     
    10896    public void addRoom(@RequestBody HotelRoom room,
    10997                        @RequestParam(name = "hotelId") long hotelId) {
    110         Hotels h = hotelManager.findHotelByID(hotelId);
    111         hotelManager.createRoom(h, room.getHotelRoomDescription(), room.getHotelRoomName(), room.getKitchenAvailable(), room.getAirConditioning(), room.getBalcony(), room.getPrice(), room.getNumOfBeds());
     98        hotelManager.createRoom(hotelId, room.getHotelRoomDescription(), room.getHotelRoomName(), room.getKitchenAvailable(), room.getAirConditioning(), room.getBalcony(), room.getPrice(), room.getNumOfBeds());
    11299    }
    113100
     
    119106    @GetMapping(path = "/hotel/rooms/delete")
    120107    public ResponseEntity removeRoom(@RequestParam(name = "hotelRoomId") long hotelRoomId) {
    121         try
    122         {
     108        try {
    123109            hotelManager.deleteRoom(hotelRoomId);
    124110            return new ResponseEntity(HttpStatus.OK);
    125         }
    126         catch (Exception exception)
    127         {
     111        } catch (Exception exception) {
    128112            return new ResponseEntity(HttpStatus.NOT_FOUND);
    129113        }
     
    139123    @GetMapping(path = "/hotel/rooms/reservation/delete")
    140124    public ResponseEntity removeReservation(@RequestParam(name = "hotelRoomReservationId") long hotelRoomReservationId) {
    141         try
    142         {
     125        try {
    143126            hotelManager.deleteReservation(hotelRoomReservationId);
    144127            return new ResponseEntity(HttpStatus.OK);
    145         }
    146         catch (Exception exception)
    147         {
    148             return new ResponseEntity(HttpStatus.NOT_FOUND);
    149         }
    150     }
    151 
    152         //HOTEL AVAILABILITY CRUD
     128        } catch (Exception exception) {
     129            return new ResponseEntity(HttpStatus.NOT_FOUND);
     130        }
     131    }
     132
     133    //HOTEL AVAILABILITY CRUD
    153134    @PostMapping(path = "/hotel/rooms/available/{id}/add")
    154135    public void addRoomAvailible(@RequestBody HotelRoomAvailable hotelRoomAvailable,
    155                                  @PathVariable long id)
    156     {
    157         HotelRoom hotelRoom = hotelManager.findRoomById(id);
    158         hotelManager.createRoomAvailible(hotelRoom, hotelRoomAvailable.getDateFrom(), hotelRoomAvailable.getDateTo(), hotelRoomAvailable.getNumberOfBeds());
     136                                 @PathVariable long id) {
     137
     138        hotelManager.createRoomAvailible(id, hotelRoomAvailable.getDateFrom(), hotelRoomAvailable.getDateTo(), hotelRoomAvailable.getNumberOfBeds());
    159139    }
    160140
    161141    @PostMapping(path = "/hotel/rooms/available/edit")
    162     public void editRoomAvailible(@RequestBody HotelRoomAvailable hotelRoomAvailable)
    163     {
     142    public void editRoomAvailible(@RequestBody HotelRoomAvailable hotelRoomAvailable) {
    164143        hotelManager.editRoomAvailible(hotelRoomAvailable.getHotelRoomAvailableId(), hotelRoomAvailable.getHotelRoom(), hotelRoomAvailable.getDateFrom(), hotelRoomAvailable.getDateTo(), hotelRoomAvailable.getNumberOfBeds());
    165144    }
    166145
    167146    @GetMapping(path = "/hotel/rooms/available/remove")
    168     public ResponseEntity removeRoomAvailible(@RequestParam(name = "hotelRoomAvailibleId") long hotelRoomAvailibleId)
    169     {
    170         try
    171         {
     147    public ResponseEntity removeRoomAvailible(@RequestParam(name = "hotelRoomAvailibleId") long hotelRoomAvailibleId) {
     148        try {
    172149            hotelManager.deleteRoomAvailible(hotelRoomAvailibleId);
    173150            return new ResponseEntity(HttpStatus.OK);
    174         }
    175         catch (Exception ex)
    176         {
     151        } catch (Exception ex) {
    177152            return new ResponseEntity(HttpStatus.NOT_FOUND);
    178153        }
     
    180155
    181156    @GetMapping(path = "hotel/rooms/{id}/available")
    182     public List<HotelRoomAvailable> getRoomAvailability(@PathVariable Long id)
    183     {
     157    public List<HotelRoomAvailable> getRoomAvailability(@PathVariable Long id) {
    184158        return hotelManager.getRoomsAvailableById(id);
    185159    }
     
    190164                                               @RequestParam(name = "dateTo") @DateTimeFormat(pattern = "yyyy-MM-dd") Date dateTo,
    191165                                               @RequestParam(name = "numBeds") int numBeds,
    192                                                @RequestParam(name = "flexible") Boolean flexible)
    193     {
    194         System.out.println(flexible);
    195         System.out.println(dateFrom + " " + dateTo);
     166                                               @RequestParam(name = "flexible") Boolean flexible) {
    196167        return hotelManager.getRoomsAvailibilityByDateAndLocation(hotelLocation, dateFrom, dateTo, numBeds, flexible);
    197168    }
    198169
    199170    @PostMapping(path = "/hotel/reserve")
    200     public void reserveHotelRoom(@RequestParam(name = "hotelRoomId")Long hotelRoomId,
     171    public void reserveHotelRoom(@RequestParam(name = "hotelRoomId") Long hotelRoomId,
    201172                                 @RequestParam(name = "userId") Long userId,
    202173                                 @RequestParam(name = "hotelRoomAvailableId") Long hotelRoomAvailableId,
    203174                                 @RequestParam(name = "numberOfBeds") Integer numberOfBeds,
    204175                                 @RequestParam(name = "from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
    205                                  @RequestParam(name = "to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to){
    206 
     176                                 @RequestParam(name = "to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to) {
    207177
    208178
     
    211181
    212182    @GetMapping(path = "/hotel/{id}/reservations/active")
    213     public List<HotelReservationDto> getActiveReservationsForHotel(@PathVariable Long id)
    214     {
     183    public List<HotelReservationDto> getActiveReservationsForHotel(@PathVariable Long id) {
    215184        return hotelManager.findVaidReseravtionsByHotel(id);
    216185    }
    217186
    218187    @GetMapping(path = "/hotel/reservations/user/{id}")
    219     public List<HotelReservationUserDto> getActiveReservationsForUser(@PathVariable Long id)
    220     {
     188    public List<HotelReservationUserDto> getActiveReservationsForUser(@PathVariable Long id) {
    221189        return hotelManager.findValidHotelReservationsByUser(id);
    222190    }
    223191
    224192    @GetMapping(path = "/hotel/reservations/user/{id}/past")
    225     public List<HotelReservationUserDto> getPastReservationsForUser(@PathVariable Long id)
    226     {
     193    public List<HotelReservationUserDto> getPastReservationsForUser(@PathVariable Long id) {
    227194        return hotelManager.findPastHotelReservationsByUser(id);
    228195    }
    229196
    230197    @GetMapping(path = "/hotel/{id}/images")
    231     public List<HotelsImages> getImagesForHotel(@PathVariable Long id)
    232     {
     198    public List<HotelsImages> getImagesForHotel(@PathVariable Long id) {
    233199        return hotelManager.getHotelImages(id);
    234200    }
    235201
    236202    @GetMapping(path = "/room/{id}/images")
    237     public List<HotelRoomImages> getImagesForHotelRoom(@PathVariable Long id)
    238     {
     203    public List<HotelRoomImages> getImagesForHotelRoom(@PathVariable Long id) {
    239204        return hotelManager.getRoomImages(id);
    240205    }
    241206
    242207    @PostMapping("/hotel/{id}/cancel")
    243     public void cancelHotelReservation(@PathVariable Long id){
     208    public void cancelHotelReservation(@PathVariable Long id) {
    244209        hotelManager.deleteReservation(id);
    245210    }
  • src/main/java/com/tourMate/controllers/RestaurantController.java

    r07f4e8b r0f5aa27  
    66import com.tourMate.dto.RestaurantReservationUserDto;
    77import com.tourMate.entities.*;
     8import com.tourMate.services.MenuManager;
    89import com.tourMate.services.RestaurantManager;
    910import org.springframework.beans.factory.annotation.Autowired;
     
    2324    @Autowired
    2425    RestaurantManager restaurantManager;
     26    @Autowired
     27    MenuManager menuManager;
    2528
    2629    @PostMapping(path = "/restaurant/add")
     
    3437    public void addMenu(@PathVariable(name = "id") long restaurantId, @RequestBody Menu menu) {
    3538        restaurantManager.addMenuToRestaurant(restaurantId, menu);
     39    }
     40
     41    @PostMapping(path = "/menu/{id}/edit")
     42    public void editMenu(@PathVariable Long id,
     43                         @RequestParam String name,
     44                         @RequestParam String ingredients,
     45                         @RequestParam double price)
     46    {
     47        menuManager.editMenu(id, name, ingredients, price);
    3648    }
    3749
     
    149161                                                         @RequestParam(name = "hourTo") String hourTo,
    150162                                                         @RequestParam(name = "numPeople") int noSeats) {
    151         Date dateFrom = date;
    152         Date dateTo = Date.from(date.toInstant());
    153         String[] splittedFrom = hourFrom.split(":");
    154         String[] splittedTo = hourTo.split(":");
    155         dateFrom.setHours(Integer.parseInt(splittedFrom[0]));
    156         dateFrom.setMinutes(Integer.parseInt(splittedFrom[1]));
    157         dateTo.setHours(Integer.parseInt(splittedTo[0]));
    158         dateTo.setMinutes(Integer.parseInt(splittedTo[1]));
    159         return restaurantManager.getTablesByDateAndLocation(restaurantLocation, dateFrom, dateTo, noSeats);
     163
     164        return restaurantManager.getTablesByDateAndLocation(restaurantLocation, date, hourFrom, hourTo, noSeats);
    160165    }
    161166
  • src/main/java/com/tourMate/controllers/ReviewController.java

    r07f4e8b r0f5aa27  
    2828    public void edit(@RequestBody Reviews review)
    2929    {
    30 //        editReview(long id, String title, String description, int numStar, Hotels hotel, Restaurants restaurant, Transport transport)
    3130        reviewManager.editReview(review.getReviewId(), review.getTitle(), review.getDescription(), review.getNumStar(), review.getHotel(), review.getRestaurant(), review.getTransport());
    3231    }
  • src/main/java/com/tourMate/controllers/TransportController.java

    r07f4e8b r0f5aa27  
    8484    @PostMapping(path = "/transport/available/add")
    8585    public void add(@RequestBody TransportAvailible transportAvailable, @RequestParam(name = "transportId") long transportId) {
    86         Transport t = transportManager.getTransportById(transportId);
    87         List<TransportRoute> routes = transportAvailable.getRoutes().stream().toList();
    88         routes.get(0).setDeparture(transportAvailable.getDate());
    89         transportAvailable.setTime(routes.get(routes.size() - 1).getArrival());
    90         routes.forEach(x -> x.setParentRoute(transportAvailable));
    91         transportAvailable.setTransport(t);
    92         transportManager.createTransportAvailable(transportAvailable.getTransport(), transportAvailable.getFrom(), transportAvailable.getTo(), transportAvailable.getDate(), transportAvailable.getFreeSpace(), transportAvailable.getTime(), routes);
     86
     87        transportManager.createTransportAvailable(transportAvailable, transportAvailable.getTransport(), transportAvailable.getFrom(), transportAvailable.getTo(), transportAvailable.getDate(), transportAvailable.getFreeSpace(), transportAvailable.getTime(), transportId, transportAvailable.getRoutes());
    9388    }
    9489
  • src/main/java/com/tourMate/controllers/UsersController.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.controllers;
    22
     3import com.tourMate.dto.PrincipalInfo;
    34import com.tourMate.entities.Business;
    45import com.tourMate.entities.User;
     6import com.tourMate.config.oauth2.OAuth2UserDetailsCustom;
    57import com.tourMate.services.BusinessManager;
    68import com.tourMate.services.UsersManager;
     
    911import org.springframework.http.ResponseEntity;
    1012import org.springframework.security.core.Authentication;
     13import org.springframework.security.core.parameters.P;
    1114import org.springframework.web.bind.annotation.*;
    1215
     
    5760        usersManager.approveUserProfile(userId);
    5861        return new ResponseEntity<>(HttpStatus.OK);
    59 
    60 
    6162    }
    6263
     
    7071    @PostMapping(path = "/register")
    7172    public List<User> add(@RequestBody User user) {
    72         System.out.println(user.getName() + user.getSurname());
    7373        usersManager.createUser(user.getName(), user.getSurname(), user.getEmail(), user.getBirthDate(), user.getAddress(), user.getContact());
    7474        return usersManager.getCreatedUsers();
     
    8888    @GetMapping(value = "/principal")
    8989    @ResponseBody
    90     public User currentUser(Authentication authentication) {
    91         return (User) authentication.getPrincipal();
     90    public PrincipalInfo currentUser(Authentication authentication) {
     91        Long id;
     92        if(authentication.getPrincipal() instanceof OAuth2UserDetailsCustom)
     93        {
     94            OAuth2UserDetailsCustom oAuth2UserDetailsCustom = (OAuth2UserDetailsCustom) authentication.getPrincipal();
     95            id = oAuth2UserDetailsCustom.getId();
     96        }
     97        else
     98        {
     99            User user = (User) authentication.getPrincipal();
     100            id = user.getUserID();
     101        }
     102        return usersManager.getPrincipalInfo(id);
    92103    }
    93104    @PostMapping(path = "/user/edit")
    94     public List<User> edit(@RequestBody User user)
     105    public void edit(@RequestBody User user)
    95106    {
    96         System.out.println(user.getName() + " " + user.getSurname() + "id e " + user.getUserID());
    97         // long userID, String name, String surname, String email, Date birthDate, String address, String contact
    98107        usersManager.editUser(user.getUserID(), user.getName(), user.getSurname(), user.getEmail(), user.getBirthDate(), user.getAddress(), user.getContact());
    99         return usersManager.getCreatedUsers();
    100108    }
    101109
    102110    @GetMapping(path = "/user/delete")
    103     public ResponseEntity remove(@RequestParam(name = "userId") long userId) {
     111    public ResponseEntity<?> remove(@RequestParam(name = "userId") long userId) {
    104112        try
    105113        {
    106114            usersManager.deleteUser(userId);
    107             return new ResponseEntity(HttpStatus.OK);
     115            return new ResponseEntity<>(HttpStatus.OK);
    108116        }
    109117        catch (Exception exception)
    110118        {
    111             return new ResponseEntity(HttpStatus.NOT_FOUND);
     119            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    112120        }
    113121    }
    114122
    115123    @GetMapping("/users/unlock/{id}")
    116     public ResponseEntity unlock(@PathVariable Long id)
     124    public ResponseEntity<?> unlock(@PathVariable Long id)
    117125    {
    118126        usersManager.unlock(id);
    119         return new ResponseEntity(HttpStatus.OK);
     127        return new ResponseEntity<>(HttpStatus.OK);
     128    }
     129
     130    @PostMapping("/users/{id}/connect")
     131    public ResponseEntity<?> connectAccount(@PathVariable Long id,
     132                                            @RequestParam String username,
     133                                            @RequestParam String password)
     134    {
     135        usersManager.connectAccount(id, username, password);
     136        return new ResponseEntity<>(HttpStatus.OK);
     137    }
     138
     139    @GetMapping("/users/{id}/connected")
     140    public List<User> getConnectedAccounts(@PathVariable Long id)
     141    {
     142        return usersManager.findConnectedAccountsByUser(id);
    120143    }
    121144}
  • src/main/java/com/tourMate/controllers/UtilsController.java

    r07f4e8b r0f5aa27  
    22
    33import org.springframework.http.ResponseEntity;
     4import org.springframework.stereotype.Controller;
    45import org.springframework.web.bind.annotation.GetMapping;
    56import org.springframework.web.bind.annotation.RestController;
     
    1011import java.net.http.HttpResponse;
    1112
    12 @RestController
     13@Controller
    1314public class UtilsController {
    14     @GetMapping("/loo")
    15     public ResponseEntity<?> testFnc(RedirectAttributes attributes) {
    16         String redirectUrl = "https://example.com"; // Replace with your desired redirect URL
    17 
    18         // Using UriComponentsBuilder to handle URL encoding
    19         return ResponseEntity
    20                 .status(302) // 302 Found status code for redirect
    21                 .location(UriComponentsBuilder.fromUriString(redirectUrl).build().toUri())
    22                 .build();
     15    @GetMapping("/login")
     16    public String getLoginPage()
     17    {
     18        return "login";
    2319    }
    2420}
  • src/main/java/com/tourMate/dao/HotelDao.java

    r07f4e8b r0f5aa27  
    9797
    9898    List<HotelRoomReservations> findPastReservationByUser(User u);
     99
     100    List<HotelRoomReservations> getReservationsInPeriod(String hotelLocation, Date dateFrom, Date dateTo);
    99101//    public void createHotel(Hotels hotel, long userId);
    100102//    public void editHotel(long hotelId, String hotelName, String hotelDescripiton, String hotelLocation, String hotelEDBS, Boolean parking, Boolean petFriendly, Boolean internetAvailable);
  • src/main/java/com/tourMate/dao/TransportDao.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.dao;
    22
    3 import com.tourMate.dto.RouteListingDto;
    4 import com.tourMate.dto.TransportDto;
    53import com.tourMate.entities.*;
    64import jakarta.transaction.Transactional;
     
    1917    List<Transport> getTransports();
    2018
    21     List<TransportDto> getTransportsByUser(User u);
     19    List<Transport> getTransportsByUser(User u);
    2220
    23     List<RouteListingDto> getRoutesForTransport(Transport t);
     21    List<TransportAvailible> getRoutesForTransport(Transport t);
    2422
    25     TransportDto findTransportById(long transportId);
     23    Transport findTransportById(long transportId);
    2624
    2725    Transport getTransportById(long transportId);
  • src/main/java/com/tourMate/dao/UsersDao.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.dao;
    22
     3import com.tourMate.entities.Providers;
    34import com.tourMate.entities.Role;
    45import com.tourMate.entities.User;
     6import jakarta.transaction.Transactional;
    57import org.springframework.security.core.userdetails.UserDetails;
    68
     
    2931
    3032    Role findById(Long id);
    31     void updateUser(User s);
     33    User updateUser(User s);
     34    User findByUsernameAndProvider(String username, String providers);
     35
     36    @Transactional
     37    User mergeUser(User user);
     38
     39    List<User> getAdmins();
     40
     41    List<User> findConnectedAccountsByUser(User u);
    3242}
  • src/main/java/com/tourMate/dao/impl/BusinessDaoImpl.java

    r07f4e8b r0f5aa27  
    44import com.tourMate.entities.Business;
    55import com.tourMate.entities.User;
     6import com.tourMate.events.OnBusinessApprovedEvent;
    67import jakarta.persistence.EntityManager;
    78import jakarta.persistence.PersistenceContext;
    89import jakarta.transaction.Transactional;
     10import org.springframework.beans.factory.annotation.Autowired;
     11import org.springframework.context.ApplicationEventPublisher;
    912import org.springframework.stereotype.Service;
    1013
     
    1619    @PersistenceContext
    1720    EntityManager em;
     21    @Autowired
     22    ApplicationEventPublisher eventPublisher;
    1823
    1924    @Transactional
     
    3742    public boolean hasBusiness(User u)
    3843    {
    39         return Integer.parseInt(em.createQuery("SELECT COUNT(b) FROM Business b WHERE b.user = :user").setParameter("user", u).getSingleResult().toString()) > 0;
     44        return Integer.parseInt(em.createQuery("SELECT COUNT(b) FROM Business b WHERE b.user = :user or b.user in :users")
     45                .setParameter("user", u)
     46                .setParameter("users", u.getConnectedAccounts())
     47                .getSingleResult().toString()) > 0;
    4048    }
    4149
     
    4957    public void approveBusiness(Business b) {
    5058        em.persist(b);
     59        eventPublisher.publishEvent(new OnBusinessApprovedEvent(b.getUser()));
    5160    }
    5261
  • src/main/java/com/tourMate/dao/impl/HotelDaoImpl.java

    r07f4e8b r0f5aa27  
    33import com.tourMate.dao.HotelDao;
    44import com.tourMate.entities.*;
     5import com.tourMate.events.OnHotelReservationEvent;
     6import com.tourMate.events.OnRegistrationSuccessEvent;
    57import jakarta.persistence.EntityManager;
    68import jakarta.persistence.PersistenceContext;
    79import jakarta.transaction.Transactional;
     10import org.springframework.beans.factory.annotation.Autowired;
     11import org.springframework.context.ApplicationEventPublisher;
    812import org.springframework.stereotype.Service;
    913
     
    1721    @PersistenceContext
    1822    EntityManager em;
     23    @Autowired
     24    ApplicationEventPublisher eventPublisher;
    1925
    2026    @Override
     
    3137    @Override
    3238    public List<Hotels> getHotelsForUser(User u) {
    33         return em.createQuery("select h from Hotels h where h.owner = :u").setParameter("u", u).getResultList();
    34     }
    35 
    36     @Override
    37     public List<Hotels> getHotelsByLocation(String hotelLocation) {
    38         return em.createQuery("select h from Hotels h where h.hotelLocation = hotelLocation").getResultList();
    39     }
    40 
     39        return em.createQuery("select h from Hotels h where h.owner = :u or h.owner in :users")
     40                .setParameter("u", u)
     41                .setParameter("users", u.getConnectedAccounts())
     42                .getResultList();
     43    }
    4144    @Transactional
    4245    @Override
     
    211214        }
    212215
    213 
    214 
    215 
    216216    }
    217217
     
    232232    public void createReservation(HotelRoomReservations  r) {
    233233        em.persist(r);
     234        eventPublisher.publishEvent(new OnHotelReservationEvent(r.getUser(), r));
    234235    }
    235236
     
    243244    @Override
    244245    public void deleteReservation(HotelRoomReservations hr) {
    245 
    246246        em.remove(hr);
    247247    }
     
    281281                .setParameter("user", u).getResultList();
    282282    }
     283
     284    @Override
     285    public List<HotelRoomReservations> getReservationsInPeriod(String hotelLocation, Date dateFrom, Date dateTo) {
     286        return em.createQuery("select hr from HotelRoomReservations hr where hr.hotelRoom.hotel.hotelLocation like :hotelLocation and (hr.dateFrom between :dateFrom and :dateTo) or (hr.dateTo between :dateFrom and :dateTo)")
     287                .setParameter("hotelLocation", hotelLocation)
     288                .setParameter("dateFrom", dateFrom)
     289                .setParameter("dateTo", dateTo)
     290                .getResultList();
     291    }
     292
     293    @Override
     294    public List<Hotels> getHotelsByLocation(String hotelLocation)
     295    {
     296        return em.createQuery("select h from Hotels h where h.hotelLocation like :hotelLocation")
     297                .setParameter("hotelLocation", hotelLocation)
     298                .getResultList();
     299    }
    283300}
  • src/main/java/com/tourMate/dao/impl/RestaurantDaoImpl.java

    r07f4e8b r0f5aa27  
    102102    @Override
    103103    public List<Restaurant> getRestaurantsByUser(User u) {
    104         return em.createQuery("select r from Restaurant r where r.restaurantOwner = :u").setParameter("u", u).getResultList();
     104        return em.createQuery("select r from Restaurant r where r.restaurantOwner = :u or r.restaurantOwner in :users")
     105                .setParameter("u", u)
     106                .setParameter("users", u.getConnectedAccounts())
     107                .getResultList();
    105108    }
    106109
  • src/main/java/com/tourMate/dao/impl/TransportDaoImpl.java

    r07f4e8b r0f5aa27  
    22
    33import com.tourMate.dao.TransportDao;
    4 import com.tourMate.dto.RouteListingDto;
    5 import com.tourMate.dto.TransportDto;
    64import com.tourMate.entities.*;
    75import jakarta.persistence.EntityManager;
     
    3735
    3836    @Override
    39     public List<TransportDto> getTransportsByUser(User u) {
    40         List<Transport> transports = em.createQuery("select t from Transport t where t.owner = :u").setParameter("u", u).getResultList();
    41         return transports.stream().map(x -> new TransportDto(
    42                 x.getTransportID(),
    43                 x.getTransportName(),
    44                 x.getCarBrand(),
    45                 x.getCarType(),
    46                 x.getCarManufacturedYear(),
    47                 x.getNoPassengers(),
    48                 x.getNoBags(),
    49                 x.getEMBG(),
    50                 x.getOwner(),
    51                 x.getCarPlate(),
    52                 x.getAvailableRoutes().stream().map(y -> new RouteListingDto(
    53                         y.getTransportAvailibleId(),
    54                         y.getFrom(),
    55                         y.getTo(),
    56                         y.getDate(),
    57                         y.getFreeSpace(),
    58                         y.getTime(),
    59                         y.getRoutes(),
    60                         y.getRoutes().stream()
    61                                 .mapToDouble(TransportRoute::getPrice)
    62                                 .max().orElse(0)
    63                 )).toList(),
    64                 x.getAvailableRoutes().stream()
    65                         .flatMapToDouble(y -> y.getRoutes()
    66                                 .stream()
    67                                 .mapToDouble(TransportRoute::getPrice)).max().orElseGet(() -> 0)
    68         )).toList();
     37    public List<Transport> getTransportsByUser(User u) {
     38        List<Transport> transports = em.createQuery("select t from Transport t where t.owner = :u or t.owner in :users")
     39                .setParameter("u", u)
     40                .setParameter("users", u.getConnectedAccounts())
     41                .getResultList();
     42        return transports;
    6943    }
    7044
    7145    @Override
    72     public List<RouteListingDto> getRoutesForTransport(Transport t) {
     46    public List<TransportAvailible> getRoutesForTransport(Transport t) {
    7347        List<TransportAvailible> transportsAvailible = em.createQuery("select ta from TransportAvailible ta where ta.transport = :transport").setParameter("transport", t).getResultList();
    74         return transportsAvailible.stream().map(x -> new RouteListingDto(
    75                 x.getTransportAvailibleId(),
    76                 x.getFrom(),
    77                 x.getTo(),
    78                 x.getDate(),
    79                 x.getFreeSpace(),
    80                 x.getTime(),
    81                 x.getRoutes(),
    82                 x.getRoutes().stream()
    83                         .mapToDouble(TransportRoute::getPrice)
    84                         .max().orElse(0)
    85         )).toList();
     48        return transportsAvailible;
    8649    }
    8750
    8851    @Override
    89     public TransportDto findTransportById(long transportId) {
     52    public Transport findTransportById(long transportId) {
    9053        Transport x = em.find(Transport.class,transportId);
    91         return new TransportDto(
    92                 x.getTransportID(),
    93                 x.getTransportName(),
    94                 x.getCarBrand(),
    95                 x.getCarType(),
    96                 x.getCarManufacturedYear(),
    97                 x.getNoPassengers(),
    98                 x.getNoBags(),
    99                 x.getEMBG(),
    100                 x.getOwner(),
    101                 x.getCarPlate(),
    102                 x.getAvailableRoutes().stream().map(y -> new RouteListingDto(
    103                         y.getTransportAvailibleId(),
    104                         y.getFrom(),
    105                         y.getTo(),
    106                         y.getDate(),
    107                         y.getFreeSpace(),
    108                         y.getTime(),
    109                         y.getRoutes(),
    110                         y.getRoutes().stream()
    111                                 .mapToDouble(TransportRoute::getPrice)
    112                                 .max().orElse(0)
    113                 )).toList(),
    114                 x.getAvailableRoutes().stream()
    115                         .flatMapToDouble(y -> y.getRoutes()
    116                                                         .stream()
    117                                                         .mapToDouble(TransportRoute::getPrice)).max().orElseGet(() -> 0));
     54        return x;
    11855    }
    11956
  • src/main/java/com/tourMate/dao/impl/UsersDaoImpl.java

    r07f4e8b r0f5aa27  
    44import com.tourMate.entities.Role;
    55import com.tourMate.entities.User;
     6import com.tourMate.events.OnProfileEnabledEvent;
     7import com.tourMate.events.OnRegistrationSuccessEvent;
    68import jakarta.persistence.EntityManager;
    79import jakarta.persistence.PersistenceContext;
    810import jakarta.transaction.Transactional;
    9 import org.jetbrains.annotations.NotNull;
    1011import org.springframework.beans.factory.annotation.Autowired;
     12import org.springframework.context.ApplicationEventPublisher;
    1113import org.springframework.security.core.userdetails.UserDetails;
    1214import org.springframework.security.crypto.password.PasswordEncoder;
    13 import org.springframework.stereotype.Service;
     15import org.springframework.stereotype.Repository;
    1416
    1517import java.util.Date;
    1618import java.util.List;
    1719
    18 @Service
     20@Repository
    1921public class UsersDaoImpl implements UsersDao {
    2022
    2123    @PersistenceContext
    2224    EntityManager em;
    23 
    2425    @Autowired
    2526    PasswordEncoder passwordEncoder;
     27    @Autowired
     28    private ApplicationEventPublisher eventPublisher;
    2629
    2730    @Transactional
     
    3033        Role r = em.find(Role.class, 2);
    3134        User user = new User(name, surname, email, passwordEncoder.encode("password"), birthDate, address, contact, r);
     35        user.setProvider("local");
     36        user.setLocked(true);
    3237        em.persist(user);
     38        if(user.getProvider().equals("local"))
     39        {
     40            eventPublisher.publishEvent(new OnRegistrationSuccessEvent(user));
     41        }
    3342    }
    3443
     
    8493        u.setEnabled(true);
    8594        em.persist(u);
     95        eventPublisher.publishEvent(new OnProfileEnabledEvent(u));
    8696    }
    8797
     
    93103    @Override
    94104    @Transactional
    95     public void updateUser(User s) {
     105    public User updateUser(User s) {
    96106        em.persist(s);
     107        return s;
    97108    }
    98109
     110    @Override
     111    public User findByUsernameAndProvider(String username, String providers)
     112    {
     113        try
     114        {
     115            return (User) em.createQuery("select u from User u where u.email = :username and u.provider = :provider")
     116                    .setParameter("username", username)
     117                    .setParameter("provider", providers)
     118                    .getSingleResult();
     119        }
     120        catch (Exception ex)
     121        {
     122            return null;
     123        }
     124    }
    99125
     126    @Override
     127    @Transactional
     128    public User mergeUser(User user) {
     129        return em.merge(user);
     130    }
     131
     132    @Override
     133    public List<User> getAdmins() {
     134        return em.createQuery("select u from User u where u.role.roleName = 'SUPERADMIN'")
     135                .getResultList();
     136    }
     137
     138    @Override
     139    public List<User> findConnectedAccountsByUser(User u) {
     140        return em.createQuery("select u.connectedAccounts from User u where u = :user")
     141                .setParameter("user", u)
     142                .getResultList();
     143    }
    100144}
  • src/main/java/com/tourMate/dto/HotelDto.java

    r07f4e8b r0f5aa27  
    2121    private double averageScore;
    2222    private List<HotelsImages> images;
    23 
    24     public HotelDto(long hotelId, String hotelName, String hotelDescripiton, String hotelLocation, String hotelEDBS, Boolean parking, Boolean petFriendly, Boolean internetAvailable, double totalPrice, List<HotelRoomAvailable> hotelRooms, List<Reviews> hotelReviews, double averageScore, List<HotelsImages> images) {
     23    private Boolean promoted;
     24    private Boolean marketed;
     25    public HotelDto(long hotelId, String hotelName, String hotelDescripiton, String hotelLocation, String hotelEDBS, Boolean parking, Boolean petFriendly, Boolean internetAvailable, double totalPrice, List<HotelRoomAvailable> hotelRooms, List<Reviews> hotelReviews, double averageScore, List<HotelsImages> images, Boolean promoted, Boolean marketed) {
    2526        this.hotelId = hotelId;
    2627        this.hotelName = hotelName;
     
    3637        this.averageScore = averageScore;
    3738        this.images = images;
     39        this.promoted = promoted;
     40        this.marketed = marketed;
    3841    }
    3942
     
    132135        this.images = images;
    133136    }
     137
     138    public void setHotelReviews(List<Reviews> hotelReviews) {
     139        this.hotelReviews = hotelReviews;
     140    }
     141
     142    public void setAverageScore(double averageScore) {
     143        this.averageScore = averageScore;
     144    }
     145
     146    public Boolean getPromoted() {
     147        return promoted;
     148    }
     149
     150    public void setPromoted(Boolean promoted) {
     151        this.promoted = promoted;
     152    }
     153
     154    public Boolean getMarketed() {
     155        return marketed;
     156    }
     157
     158    public void setMarketed(Boolean marketed) {
     159        this.marketed = marketed;
     160    }
    134161}
  • src/main/java/com/tourMate/entities/User.java

    r07f4e8b r0f5aa27  
    1414import java.util.Collections;
    1515import java.util.Date;
     16import java.util.List;
    1617
    1718@Entity
     
    2728    private String name;
    2829
    29     @Column(name = "surname", unique = false, nullable = false)
     30    @Column(name = "surname", unique = false, nullable = true)
    3031    private String surname;
    3132
     
    3435    private String email;
    3536
    36     @Column(name = "password", unique = true, nullable = false)
     37    @Column(name = "password", unique = true, nullable = true)
    3738    @NotNull
    3839    private String password;
    3940
    40     @Column(name = "birth_date", unique = false, nullable = false)
     41    @Column(name = "birth_date", unique = false, nullable = true)
    4142    @NotNull
    4243    private Date birthDate;
    4344
    44     @Column(name = "address", unique = false, nullable = false)
     45    @Column(name = "address", unique = false, nullable = true)
    4546    private String address;
    4647
    47     @Column(name = "contact", unique = false, nullable = false)
     48    @Column(name = "contact", unique = false, nullable = true)
    4849    private String contact;
    4950
     
    5758    boolean enabled;
    5859
     60    @Column(name = "provider", unique = false, nullable = true)
     61    String provider;
     62
     63    @ManyToMany
     64    @JsonIgnore
     65    List<User> connectedAccounts;
     66
    5967
    6068    public User(@NotNull String name, String surname, @NotNull String email, @NotNull String password, @NotNull Date birthDate, String address, String contact, Role role) {
     
    120128    }
    121129
     130    public List<User> getConnectedAccounts() {
     131        return connectedAccounts;
     132    }
     133
     134    public void setConnectedAccounts(List<User> connectedAccounts) {
     135        this.connectedAccounts = connectedAccounts;
     136    }
     137
     138    public void addConnectedUser(User u)
     139    {
     140        connectedAccounts.add(u);
     141    }
    122142
    123143    public void setSurname(String surname) {
     
    212232        this.enabled = enabled;
    213233    }
     234
     235    public String getProvider() {
     236        return provider;
     237    }
     238
     239    public void setProvider(String  provider) {
     240        this.provider = provider;
     241    }
    214242}
  • src/main/java/com/tourMate/services/HotelManager.java

    r07f4e8b r0f5aa27  
    2525    public HotelRoom findRoomById (long hotelRoomId);
    2626    public List<HotelRoomImages> getRoomImages(Long hotelRoom);
    27     public void createRoom(Hotels hotel, String hotelRoomDescription, String hotelRoomName, Boolean kitchenAvailable, Boolean airConditioning, Boolean balcony, double price, int numOfBeds);
     27    public void createRoom(Long hotelId, String hotelRoomDescription, String hotelRoomName, Boolean kitchenAvailable, Boolean airConditioning, Boolean balcony, double price, int numOfBeds);
    2828    public void editRoom(long hotelRoomId, Hotels hotel, String hotelRoomDescription, String hotelRoomName, Boolean kitchenAvailable, Boolean airConditioning, Boolean balcony, double price);
    2929    public void deleteRoom(long hotelRoomId);
    30     public void createRoomAvailible(HotelRoom hotelRoom, Date dateFrom, Date dateTo, int numberOfBeds);
     30    public void createRoomAvailible(long hotelRoom, Date dateFrom, Date dateTo, int numberOfBeds);
    3131    public void editRoomAvailible(long hotelRoomAvailableId, HotelRoom hotelRoom, Date dateFrom, Date dateTo, int numberOfBeds);
    3232    public void editRoomAvailibleReservation(Long HotelRoomAvailableId, Long hotelRoomId, Date from, Date to, int numberOfBeds);
     
    3636    public List<HotelRoomAvailable> getRoomsAvailableById(Long id);
    3737    public List<HotelRoomAvailable> getRoomsAvailibilityByHotel(Hotels hotel);
     38
     39    List<HotelRoomReservations> getReservationsInPeriod(String hotelLocation, Date dateFrom, Date dateTo);
     40
    3841    public List<HotelDto> getRoomsAvailibilityByDateAndLocation(String hotelLocation, Date dateFrom, Date dateTo, int numberOfBeds, Boolean flexible);
    3942    public void createReservation(Long userId, Long hotelRoomId, Long hotelRoomAvailableId, Date dateFrom, Date dateTo, Integer numberOfBeds);
  • src/main/java/com/tourMate/services/RestaurantManager.java

    r07f4e8b r0f5aa27  
    3737    public List<RestaurantsTable> getRestaurantTables(long restaurantID);
    3838
    39     public List<RestaurantDto> getTablesByDateAndLocation(String restaurantLocation, Date hourFrom, Date hourTo, int noSeats);
     39    public List<RestaurantDto> getTablesByDateAndLocation(String restaurantLocation, Date date, String hourFrom, String hourTo, int noSeats);
    4040
    4141    public RestaurantsTable findTableById(long tableId);
  • src/main/java/com/tourMate/services/TransportManager.java

    r07f4e8b r0f5aa27  
    4545    public List<TransportAvailible> getTransportsAvailable();
    4646
    47     public void createTransportAvailable(Transport transport, String departureLocation, String arrivalLocation, Date date, Integer noSeats, Date departureHour, Collection<TransportRoute> routes);
     47    public void createTransportAvailable(TransportAvailible transportAvailible, Transport transport, String departureLocation, String arrivalLocation, Date date, Integer noSeats, Date departureHour, Long trnasportId, Collection<TransportRoute> routes);
    4848    public void editTransportAvailable(Transport transport, long availableID, String departureLocation, String arrivalLocation, Date date, Integer noSeats, Date departureHour);
    4949
  • src/main/java/com/tourMate/services/UsersManager.java

    r07f4e8b r0f5aa27  
    11package com.tourMate.services;
    22
     3import com.tourMate.dto.PrincipalInfo;
    34import com.tourMate.entities.User;
    45
     
    2021
    2122    void unlock(Long id);
     23
     24    List<User> getAdmins();
     25
     26    void connectAccount(Long id, String username, String password);
     27
     28    List<User> findConnectedAccountsByUser(Long id);
     29    PrincipalInfo getPrincipalInfo(Long userId);
    2230}
  • src/main/java/com/tourMate/services/impl/HotelManagerImpl.java

    r07f4e8b r0f5aa27  
    1313
    1414import java.time.Duration;
    15 import java.util.Date;
    16 import java.util.List;
    17 import java.util.Map;
     15import java.util.*;
    1816import java.util.stream.Collectors;
    1917
     
    123121
    124122    @Override
    125     public void createRoom(Hotels hotel, String hotelRoomDescription, String hotelRoomName, Boolean kitchenAvailable, Boolean airConditioning, Boolean balcony, double price, int numOfBeds) {
     123    public void createRoom(Long hotelId, String hotelRoomDescription, String hotelRoomName, Boolean kitchenAvailable, Boolean airConditioning, Boolean balcony, double price, int numOfBeds) {
     124        Hotels hotel = findHotelByID(hotelId);
    126125        HotelRoom hotelRoom = new HotelRoom(hotel, hotelRoomDescription, hotelRoomName, kitchenAvailable, airConditioning, balcony, price, numOfBeds);
    127126        hotelDao.createRoom(hotelRoom);
     
    154153
    155154    @Override
    156     public void createRoomAvailible(HotelRoom hotelRoom, Date dateFrom, Date dateTo, int numberOfBeds) {
     155    public void createRoomAvailible(long hotelRoomId, Date dateFrom, Date dateTo, int numberOfBeds) {
     156        HotelRoom hotelRoom = findRoomById(hotelRoomId);
    157157        HotelRoomAvailable hra = new HotelRoomAvailable(hotelRoom, dateFrom, dateTo, numberOfBeds);
    158158        hotelDao.createRoomAvailible(hra);
     
    168168        hotelDao.editRoomAvailible(hr);
    169169    }
    170 
     170    //01-01-2024 - 30-01-2024
     171    //05-01-2024 - 10-01-2024
     172
     173    //01-01 - 05-01
     174    //10-01 - 30-01
    171175    @Override
    172176    public void editRoomAvailibleReservation(Long HotelRoomAvailableId, Long hotelRoomId, Date from, Date to, int numberOfBeds){
     
    202206
    203207    @Override
     208    public List<HotelRoomReservations> getReservationsInPeriod(String hotelLocation, Date dateFrom, Date dateTo)
     209    {
     210        return hotelDao.getReservationsInPeriod(hotelLocation, dateFrom, dateTo);
     211    }
     212
     213    @Override
    204214    public List<HotelDto> getRoomsAvailibilityByDateAndLocation(String hotelLocation, Date dateFrom, Date dateTo, int numberOfBeds, Boolean flexible) {
    205215        long numberOfNights = Duration.between(dateFrom.toInstant(), dateTo.toInstant()).toDays();
     216        List<Hotels> hotels = getHotelsByLocation(hotelLocation);
     217        List<HotelRoomReservations> hotelRoomReservations = getReservationsInPeriod(hotelLocation, dateFrom, dateTo);
     218        List<Hotels> hotelsWithReservations = hotelRoomReservations.stream().map(x -> x.getHotelRoom().getHotel()).toList();
     219        List<Hotels> mostReservedHotels = hotelRoomReservations.stream()
     220                .collect(Collectors.groupingBy(x -> x.getHotelRoom().getHotel(), Collectors.counting())).entrySet().stream()
     221                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
     222                .limit(5)
     223                .map(Map.Entry::getKey)
     224                .toList();
     225        List<Hotels> leastReservedHotels = hotelRoomReservations.stream()
     226                .collect(Collectors.groupingBy(x -> x.getHotelRoom().getHotel(), Collectors.counting())).entrySet().stream()
     227                .sorted(Map.Entry.comparingByValue())
     228                .limit(5)
     229                .map(Map.Entry::getKey)
     230                .toList();
     231        List<Hotels> hotelsWithoutReservations = hotels.stream().filter(x -> !hotelsWithReservations.contains(x)).toList();
     232        List<Hotels> hotelsToBeMarketed = new ArrayList<>();
     233        hotelsToBeMarketed.addAll(hotelsWithoutReservations);
     234        hotelsToBeMarketed.addAll(leastReservedHotels);
    206235        List<HotelRoomAvailable> roomsAvailible = hotelDao.getRoomsAvailibilityByDateAndLocation(hotelLocation, dateFrom, dateTo, numberOfBeds, flexible);
    207236        Map<Hotels, List<HotelRoomAvailable>> roomsByHotels = roomsAvailible.stream().collect(Collectors.groupingBy(x -> x.getHotelRoom().getHotel()));
     
    220249                        getReviewsForHotel(x.getHotelId()),
    221250                        getReviewsForHotel(x.getHotelId()).stream().mapToDouble(Reviews::getNumStar).average().orElse(0),
    222                         getHotelImages(x.getHotelId())
     251                        getHotelImages(x.getHotelId()),
     252                        mostReservedHotels.contains(x),
     253                        hotelsToBeMarketed.contains(x)
    223254                )).toList();
    224255        return hotelsList;
     
    227258
    228259    @Override
     260    // TODO:Transactional
    229261    public void createReservation(Long userId, Long hotelRoomId, Long hotelRoomAvailableId, Date dateFrom, Date dateTo, Integer numberOfBeds) {
    230262        HotelRoom room = hotelDao.findRoomById(hotelRoomId);
     
    246278        hotelDao.editReservation(hr);
    247279    }
     280
    248281
    249282    @Override
  • src/main/java/com/tourMate/services/impl/RestaurantManagerImpl.java

    r07f4e8b r0f5aa27  
    8989
    9090    @Override
    91     public List<RestaurantDto> getTablesByDateAndLocation(String restaurantLocation, Date hourFrom, Date hourTo, int noSeats) {
    92         List<RestaurantsAvailible> restaurantsAvailibles = restaurantDao.getTablesByDateAndLocation(restaurantLocation, hourFrom, hourTo, noSeats);
     91    public List<RestaurantDto> getTablesByDateAndLocation(String restaurantLocation, Date date, String hourFrom, String hourTo, int noSeats) {
     92        Date dateFrom = date;
     93        Date dateTo = Date.from(date.toInstant());
     94        String[] splittedFrom = hourFrom.split(":");
     95        String[] splittedTo = hourTo.split(":");
     96        dateFrom.setHours(Integer.parseInt(splittedFrom[0]));
     97        dateFrom.setMinutes(Integer.parseInt(splittedFrom[1]));
     98        dateTo.setHours(Integer.parseInt(splittedTo[0]));
     99        dateTo.setMinutes(Integer.parseInt(splittedTo[1]));
     100        List<RestaurantsAvailible> restaurantsAvailibles = restaurantDao.getTablesByDateAndLocation(restaurantLocation, dateFrom, dateTo, noSeats);
    93101        Map<Restaurant, List<RestaurantsAvailible>> tablesByRestaurants = restaurantsAvailibles.stream().collect(Collectors.groupingBy(x -> x.getRestaurantTable().getRestaurant()));
    94102        List<RestaurantDto> restaurantsList = tablesByRestaurants.keySet().stream()
  • src/main/java/com/tourMate/services/impl/TransportManagerImpl.java

    r07f4e8b r0f5aa27  
    4646    public List<TransportDto> getTransportsByUser(long userId) {
    4747        User u = usersManager.findUserByID(userId);
    48         return transportDao.getTransportsByUser(u);
     48        List<Transport> transports = transportDao.getTransportsByUser(u);
     49        return transports.stream().map(x -> new TransportDto(
     50                x.getTransportID(),
     51                x.getTransportName(),
     52                x.getCarBrand(),
     53                x.getCarType(),
     54                x.getCarManufacturedYear(),
     55                x.getNoPassengers(),
     56                x.getNoBags(),
     57                x.getEMBG(),
     58                x.getOwner(),
     59                x.getCarPlate(),
     60                x.getAvailableRoutes().stream().map(y -> new RouteListingDto(
     61                        y.getTransportAvailibleId(),
     62                        y.getFrom(),
     63                        y.getTo(),
     64                        y.getDate(),
     65                        y.getFreeSpace(),
     66                        y.getTime(),
     67                        y.getRoutes(),
     68                        y.getRoutes().stream()
     69                                .mapToDouble(TransportRoute::getPrice)
     70                                .max().orElse(0)
     71                )).toList(),
     72                x.getAvailableRoutes().stream()
     73                        .flatMapToDouble(y -> y.getRoutes()
     74                                .stream()
     75                                .mapToDouble(TransportRoute::getPrice)).max().orElseGet(() -> 0)
     76        )).toList();
    4977    }
    5078
     
    5280    public List<RouteListingDto> getRoutesForTransport(long transportId) {
    5381        Transport t = getTransportById(transportId);
    54         return transportDao.getRoutesForTransport(t);
     82        List<TransportAvailible> transportAvailibles = transportDao.getRoutesForTransport(t);
     83        return transportAvailibles.stream().map(x -> new RouteListingDto(
     84                x.getTransportAvailibleId(),
     85                x.getFrom(),
     86                x.getTo(),
     87                x.getDate(),
     88                x.getFreeSpace(),
     89                x.getTime(),
     90                x.getRoutes(),
     91                x.getRoutes().stream()
     92                        .mapToDouble(TransportRoute::getPrice)
     93                        .max().orElse(0)
     94        )).toList();
    5595    }
    5696
    5797    @Override
    5898    public TransportDto findTransportById(long transportId) {
    59         return transportDao.findTransportById(transportId);
     99        Transport x = transportDao.findTransportById(transportId);
     100        return new TransportDto(
     101                x.getTransportID(),
     102                x.getTransportName(),
     103                x.getCarBrand(),
     104                x.getCarType(),
     105                x.getCarManufacturedYear(),
     106                x.getNoPassengers(),
     107                x.getNoBags(),
     108                x.getEMBG(),
     109                x.getOwner(),
     110                x.getCarPlate(),
     111                x.getAvailableRoutes().stream().map(y -> new RouteListingDto(
     112                        y.getTransportAvailibleId(),
     113                        y.getFrom(),
     114                        y.getTo(),
     115                        y.getDate(),
     116                        y.getFreeSpace(),
     117                        y.getTime(),
     118                        y.getRoutes(),
     119                        y.getRoutes().stream()
     120                                .mapToDouble(TransportRoute::getPrice)
     121                                .max().orElse(0)
     122                )).toList(),
     123                x.getAvailableRoutes().stream()
     124                        .flatMapToDouble(y -> y.getRoutes()
     125                                .stream()
     126                                .mapToDouble(TransportRoute::getPrice)).max().orElseGet(() -> 0));
    60127    }
    61128
     
    152219
    153220    @Override
    154     public void createTransportAvailable(Transport transport, String departureLocation, String arrivalLocation, Date date, Integer noSeats, Date departureHour, Collection<TransportRoute> routes) {
    155         TransportAvailible ta=new TransportAvailible(transport,departureLocation,arrivalLocation,date,noSeats,departureHour);
     221    public void createTransportAvailable(TransportAvailible transportAvailible, Transport transport, String departureLocation, String arrivalLocation, Date date, Integer noSeats, Date departureHour, Long transportId, Collection<TransportRoute> trRoutes) {
     222        Transport t = getTransportById(transportId);
     223        List<TransportRoute> routes = trRoutes.stream().toList();
     224        routes.get(0).setDeparture(transportAvailible.getDate());
     225        transportAvailible.setTime(routes.get(routes.size() - 1).getArrival());
     226        routes.forEach(x -> x.setParentRoute(transportAvailible));
     227        transportAvailible.setTransport(t);
     228        TransportAvailible ta=new TransportAvailible(t,departureLocation,arrivalLocation,date,noSeats,departureHour);
    156229        transportDao.createTransportAvailable(ta);
    157230        routes.forEach(x -> {
  • src/main/java/com/tourMate/services/impl/UsersManagerImpl.java

    r07f4e8b r0f5aa27  
    22
    33import com.tourMate.dao.UsersDao;
     4import com.tourMate.dto.PrincipalInfo;
    45import com.tourMate.entities.User;
     6import com.tourMate.events.OnProfileEnabledEvent;
    57import com.tourMate.services.UsersManager;
    68import org.springframework.beans.factory.annotation.Autowired;
     9import org.springframework.context.ApplicationEventPublisher;
    710import org.springframework.security.core.userdetails.UserDetails;
    811import org.springframework.security.core.userdetails.UserDetailsService;
    912import org.springframework.security.core.userdetails.UsernameNotFoundException;
     13import org.springframework.security.crypto.password.PasswordEncoder;
    1014import org.springframework.stereotype.Service;
    1115
     
    1822    @Autowired
    1923    UsersDao usersDao;
    20 
     24    @Autowired
     25    ApplicationEventPublisher eventPublisher;
     26    @Autowired
     27    PasswordEncoder passwordEncoder;
    2128    @Override
    2229    public void createUser(String name, String surname, String email, Date birthDate, String address, String contact) {
     
    6471
    6572    @Override
     73    public List<User> getAdmins() {
     74        return usersDao.getAdmins();
     75    }
     76
     77    @Override
     78    public void connectAccount(Long id, String username, String password) {
     79        User u1 = findUserByID(id);
     80        User u2 = (User) loadUserByUsername(username);
     81        if(passwordEncoder.matches(password, u2.getPassword()))
     82        {
     83            u1.addConnectedUser(u2);
     84        }
     85        usersDao.updateUser(u1);
     86    }
     87
     88    @Override
     89    public List<User> findConnectedAccountsByUser(Long id) {
     90        User u = findUserByID(id);
     91        return usersDao.findConnectedAccountsByUser(u);
     92    }
     93
     94    @Override
     95    public PrincipalInfo getPrincipalInfo(Long userId) {
     96        PrincipalInfo principalInfo = new PrincipalInfo();
     97        User u = findUserByID(userId);
     98        principalInfo.setUsername(u.getUsername());
     99        principalInfo.setRole(u.getRole().getRoleName());
     100        principalInfo.setId(userId);
     101        principalInfo.setName(u.getName());
     102        principalInfo.setEmail(u.getEmail());
     103        principalInfo.setSurname(u.getSurname());
     104        return principalInfo;
     105    }
     106
     107    @Override
    66108    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    67109        return usersDao.findUserByUsername(username);
Note: See TracChangeset for help on using the changeset viewer.