diff --git a/.gitignore b/.gitignore index d272472a60ed42d464084017fd58f4a764860e9e..73cfdb62c0d09ddc5671811621d994cd2271da64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ ### Own ### taller *.pdf -**/target/ \ No newline at end of file +**/target/ +**/.vscode \ No newline at end of file diff --git a/angular/RestClient/environments/environment.prod.ts b/angular/RestClient/environments/environment.prod.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7abc07ec43af506db487532b2175c50676f3534 --- /dev/null +++ b/angular/RestClient/environments/environment.prod.ts @@ -0,0 +1,9 @@ +const monolithUrl = 'http://room-booking:8080'; + +export const environment = { + production: true, + authAPI: 'http://auth-api:8101', + userAPI: `http://${monolithUrl}`, + hotelAPI: `http://${monolithUrl}`, + bookingAPI: `http://${monolithUrl}`, +}; diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/RoomBookingApplication.java b/java/roomBooking/src/main/java/com/uva/monolith/RoomBookingApplication.java similarity index 90% rename from java/roomBooking/src/main/java/com/uva/roomBooking/RoomBookingApplication.java rename to java/roomBooking/src/main/java/com/uva/monolith/RoomBookingApplication.java index 1a5f312d49b2d1db4ffe587e4ae02c35e1e9a506..0a5db248da6e6be909302e323931f79151b0ed62 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/RoomBookingApplication.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/RoomBookingApplication.java @@ -1,4 +1,4 @@ -package com.uva.roomBooking; +package com.uva.monolith; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/java/services/users/src/main/java/com/uva/users/Exceptions/GlobalExceptionHandler.java b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/GlobalExceptionHandler.java similarity index 98% rename from java/services/users/src/main/java/com/uva/users/Exceptions/GlobalExceptionHandler.java rename to java/roomBooking/src/main/java/com/uva/monolith/exceptions/GlobalExceptionHandler.java index 0e43ff06348e770f579e48bcbf056521f7f37da8..9428c51a9c63c3623d44752c9e3cbe6cf78ac19f 100644 --- a/java/services/users/src/main/java/com/uva/users/Exceptions/GlobalExceptionHandler.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/GlobalExceptionHandler.java @@ -1,4 +1,4 @@ -package com.uva.users.Exceptions; +package com.uva.monolith.exceptions; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/HotelNotFoundException.java b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/HotelNotFoundException.java similarity index 89% rename from java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/HotelNotFoundException.java rename to java/roomBooking/src/main/java/com/uva/monolith/exceptions/HotelNotFoundException.java index 4da802a0c6bc552386705da734c953d5a467fa70..129a0b1086b4b78eb1f1725b9f241f51ce5540f8 100644 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/HotelNotFoundException.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/HotelNotFoundException.java @@ -1,4 +1,4 @@ -package com.uva.hotelService.Exceptions; +package com.uva.monolith.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/java/services/users/src/main/java/com/uva/users/Exceptions/InvalidDateRangeException.java b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidDateRangeException.java similarity index 80% rename from java/services/users/src/main/java/com/uva/users/Exceptions/InvalidDateRangeException.java rename to java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidDateRangeException.java index 7cf94e38ed83bc5cc1a10d67f6c48eb8c9b42a66..5fea986ef1e9279c459bc5aff10932049f283333 100644 --- a/java/services/users/src/main/java/com/uva/users/Exceptions/InvalidDateRangeException.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidDateRangeException.java @@ -1,8 +1,7 @@ -package com.uva.users.Exceptions; +package com.uva.monolith.exceptions; public class InvalidDateRangeException extends RuntimeException { public InvalidDateRangeException(String message) { super(message); } } - diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidRequestException.java b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidRequestException.java similarity index 88% rename from java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidRequestException.java rename to java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidRequestException.java index 76432c4e307148cb13288a969cf755606e76428b..ca09e054420dd174c4d2c3424dcc8fe74b6c8576 100644 --- a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidRequestException.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/exceptions/InvalidRequestException.java @@ -1,4 +1,4 @@ -package com.uva.bookings.Exceptions; +package com.uva.monolith.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/BookingController.java b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/controllers/BookingController.java similarity index 62% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/BookingController.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/bookings/controllers/BookingController.java index 5baa50358b36dfffd3184fd0e7e46a9177b2ef55..f309f2b1be9be7f5c7dbd1f0e46309cab95f4a34 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/BookingController.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/controllers/BookingController.java @@ -1,20 +1,20 @@ // BookingController.java -package com.uva.roomBooking.Controllers; - -import com.uva.roomBooking.Models.Booking; -import com.uva.roomBooking.Models.Room; -import com.uva.roomBooking.Models.User; -import com.uva.roomBooking.Repositories.BookingRepository; -import com.uva.roomBooking.Repositories.RoomRepository; -import com.uva.roomBooking.Repositories.UserRepository; +package com.uva.monolith.services.bookings.controllers; import jakarta.transaction.Transactional; import org.springframework.http.HttpStatus; -import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import com.uva.monolith.services.bookings.models.Booking; +import com.uva.monolith.services.bookings.repositories.BookingRepository; +import com.uva.monolith.services.hotels.models.Room; +import com.uva.monolith.services.hotels.repositories.RoomRepository; +import com.uva.monolith.services.users.models.User; +import com.uva.monolith.services.users.repositories.UserRepository; + +import java.time.LocalDate; import java.util.List; @RestController @@ -33,9 +33,29 @@ public class BookingController { this.roomRepository = roomRepository; } - @GetMapping - public List<Booking> getAllBookings() { - return bookingRepository.findAll(); + @GetMapping(params = { "start", "end", "roomId" }) + public List<Booking> getAllBookings( + @RequestParam(required = false) LocalDate start, + @RequestParam(required = false) LocalDate end, + @RequestParam(required = false) Integer roomId) { + + List<Booking> bookings = null; + if (start != null && end != null) { + bookings = bookingRepository.findByDateRange(start, end); + } + if (roomId != null) { + if (bookings == null) { + bookings = bookingRepository.findByRoomId(roomId); + } else { + bookings = bookings.stream() + .filter(booking -> booking.getRoomId().getId() == roomId) + .toList(); + } + } + if (start == null & end == null && roomId == null) { + bookings = bookingRepository.findAll(); + } + return bookings; } @PostMapping diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Booking.java b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/models/Booking.java similarity index 93% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Models/Booking.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/bookings/models/Booking.java index c546d1916b1c29a10f95c97f03db34e64ffbe7d2..b3b0a5a3f2738eec8693f038a281ab3844a5c169 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Booking.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/models/Booking.java @@ -1,4 +1,4 @@ -package com.uva.roomBooking.Models; +package com.uva.monolith.services.bookings.models; import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; @@ -13,6 +13,9 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import java.time.LocalDate; +import com.uva.monolith.services.hotels.models.Room; +import com.uva.monolith.services.users.models.User; + @Entity @Table(name = "bookings") public class Booking { diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/BookingRepository.java b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/repositories/BookingRepository.java similarity index 69% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/BookingRepository.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/bookings/repositories/BookingRepository.java index 16c860a30fd168d4e03018ef02466dcd5adb7f99..103dbaa5ef76f8027b8152810fb9ca67aba19546 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/BookingRepository.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/bookings/repositories/BookingRepository.java @@ -1,7 +1,5 @@ // BookingRepository.java -package com.uva.roomBooking.Repositories; - -import com.uva.roomBooking.Models.Booking; +package com.uva.monolith.services.bookings.repositories; import jakarta.transaction.Transactional; @@ -13,7 +11,15 @@ import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import com.uva.monolith.services.bookings.models.Booking; + public interface BookingRepository extends JpaRepository<Booking, Integer> { + @Query("SELECT b FROM Booking b WHERE b.roomId.id = ?1") + List<Booking> findByRoomId(int roomId); + + @Query("SELECT b FROM Booking b WHERE b.startDate < ?1 AND b.endDate > ?2") + List<Booking> findByDateRange(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); @Query("SELECT b FROM Booking b WHERE b.roomId.id = ?1 AND b.startDate < ?2 AND b.endDate > ?3") List<Booking> findByRoomIdAndDateRange(@Param("roomId") int roomId, @Param("startDate") LocalDate startDate, diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/HotelController.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/controllers/HotelController.java similarity index 87% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/HotelController.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/controllers/HotelController.java index 803edc35fdcbf2b5ec7fc96972e8ee2a7777391d..5852aa794da7dcd05a8359f2756e296c829a40da 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/HotelController.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/controllers/HotelController.java @@ -1,24 +1,23 @@ -package com.uva.roomBooking.Controllers; +package com.uva.monolith.services.hotels.controllers; import java.util.List; import java.util.Map; import java.time.LocalDate; -import com.uva.roomBooking.Exceptions.HotelNotFoundException; -import com.uva.roomBooking.Exceptions.InvalidDateRangeException; -import com.uva.roomBooking.Exceptions.InvalidRequestException; -import com.uva.roomBooking.Models.Booking; -import com.uva.roomBooking.Models.Hotel; -import com.uva.roomBooking.Models.Room; -import com.uva.roomBooking.Repositories.BookingRepository; -import com.uva.roomBooking.Repositories.HotelRepository; -import com.uva.roomBooking.Repositories.RoomRepository; - import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; +import com.uva.monolith.exceptions.HotelNotFoundException; +import com.uva.monolith.exceptions.InvalidDateRangeException; +import com.uva.monolith.exceptions.InvalidRequestException; +import com.uva.monolith.services.bookings.repositories.BookingRepository; +import com.uva.monolith.services.hotels.models.Hotel; +import com.uva.monolith.services.hotels.models.Room; +import com.uva.monolith.services.hotels.repositories.HotelRepository; +import com.uva.monolith.services.hotels.repositories.RoomRepository; + @RestController @RequestMapping("hotels") @CrossOrigin(origins = "*") diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Address.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Address.java similarity index 97% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Models/Address.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Address.java index 5e51f55e710c68ac38d4cb1c5769e574b06654bf..5f31a2a530da46c00460ad6cc6151b0769c1da61 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Address.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Address.java @@ -1,4 +1,4 @@ -package com.uva.roomBooking.Models; +package com.uva.monolith.services.hotels.models; import com.fasterxml.jackson.annotation.JsonIgnore; diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Hotel.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Hotel.java similarity index 97% rename from java/services/hotels/src/main/java/com/uva/hotelService/Models/Hotel.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Hotel.java index 672f8d8b74030707319b6d8368c0bb0f941d90e7..7400dfa789c29c788e497e23393827bca10298aa 100644 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Hotel.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Hotel.java @@ -1,4 +1,4 @@ -package com.uva.hotelService.Models; +package com.uva.monolith.services.hotels.models; import java.util.List; import jakarta.persistence.Basic; diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Room.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Room.java similarity index 94% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Models/Room.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Room.java index 639dfdb0bd3be629b16c719373fa51c9a7584898..0ac71f500f7c805cee67dccd04d77ea354fab6d4 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Room.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/models/Room.java @@ -1,10 +1,10 @@ -package com.uva.roomBooking.Models; +package com.uva.monolith.services.hotels.models; import java.util.List; -import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; +import com.uva.monolith.services.bookings.models.Booking; +import com.uva.monolith.services.users.models.Tipo; import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Repositories/HotelRepository.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/HotelRepository.java similarity index 56% rename from java/services/hotels/src/main/java/com/uva/hotelService/Repositories/HotelRepository.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/HotelRepository.java index ae05426286ff6fb316513da9869ff4b715040703..ad88e98985f82e695aa9ed40df30d1501990eff5 100644 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Repositories/HotelRepository.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/HotelRepository.java @@ -1,8 +1,8 @@ -package com.uva.hotelService.Repositories; +package com.uva.monolith.services.hotels.repositories; import org.springframework.data.jpa.repository.JpaRepository; -import com.uva.hotelService.Models.Hotel; +import com.uva.monolith.services.hotels.models.Hotel; public interface HotelRepository extends JpaRepository<Hotel, Integer> { diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/RoomRepository.java b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/RoomRepository.java similarity index 90% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/RoomRepository.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/RoomRepository.java index 3df9937f1ba7dc7c8bc0aa839a7a93ffd0baa8de..78187e4389873bb649fd451ae4cb7ed1f1f0c473 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/RoomRepository.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/hotels/repositories/RoomRepository.java @@ -1,9 +1,10 @@ -package com.uva.roomBooking.Repositories; +package com.uva.monolith.services.hotels.repositories; -import com.uva.roomBooking.Models.Room; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import com.uva.monolith.services.hotels.models.Room; + import java.time.LocalDate; import java.util.List; import java.util.Optional; diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/UserController.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/controllers/UserController.java similarity index 83% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/UserController.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/users/controllers/UserController.java index a0e6397b9cabc191f7d5d24ecde162e8da6b2f14..812d0b83ff5b82c078d3f471c479fb680db252df 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Controllers/UserController.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/controllers/UserController.java @@ -1,9 +1,11 @@ -package com.uva.roomBooking.Controllers; +package com.uva.monolith.services.users.controllers; import java.time.LocalDate; import java.util.List; import java.util.Map; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -13,12 +15,13 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.uva.roomBooking.Models.UserStatus; -import com.uva.roomBooking.Models.Booking; -import com.uva.roomBooking.Models.User; -import com.uva.roomBooking.Repositories.UserRepository; +import com.uva.monolith.services.bookings.models.Booking; +import com.uva.monolith.services.users.models.User; +import com.uva.monolith.services.users.models.UserStatus; +import com.uva.monolith.services.users.repositories.UserRepository; @RestController @RequestMapping("users") @@ -35,11 +38,18 @@ public class UserController { return userRepository.findAll(); } + @GetMapping(params = { "email" }) + public ResponseEntity<?> getUserByEmail(@RequestParam String email) { + try { + return new ResponseEntity<User>(userRepository.findByEmail(email).orElseThrow(), HttpStatus.ACCEPTED); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } + @PostMapping public User addUser(@RequestBody User user) { - // TODO revisar como se desea manejar estado por defecto user.setStatus(UserStatus.NO_BOOKINGS); - // Aunque se asegure a lo mejor no es la forma de manejo esperada return userRepository.save(user); } diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Tipo.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/Tipo.java similarity index 53% rename from java/services/hotels/src/main/java/com/uva/hotelService/Models/Tipo.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/users/models/Tipo.java index b893a7c4e5da3792e6de1d86972c8946d990f9da..8b240e8d25bcef2caf06e509a59c9ad2862bf919 100644 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Tipo.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/Tipo.java @@ -1,4 +1,4 @@ -package com.uva.hotelService.Models; +package com.uva.monolith.services.users.models; public enum Tipo { SINGLE, diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/User.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/User.java similarity index 60% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Models/User.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/users/models/User.java index c5373df6edc5e936d9c94f794ae36d3289d173d5..3936e7d566f1c43c4a702f67fbcdb2707edac64c 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/User.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/User.java @@ -1,8 +1,10 @@ -package com.uva.roomBooking.Models; +package com.uva.monolith.services.users.models; +import java.time.LocalDate; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.uva.monolith.services.bookings.models.Booking; import jakarta.persistence.Basic; import jakarta.persistence.CascadeType; @@ -19,6 +21,7 @@ import jakarta.persistence.Table; @Entity @Table(name = "users") public class User { + // TODO extraer a dos clases hijas, una por cada tipo @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @@ -30,9 +33,16 @@ public class User { @Basic(optional = false) private String email; + @Basic(optional = false) + private String password; + @Basic(optional = false) @Enumerated(EnumType.STRING) - private UserStatus status = UserStatus.NO_BOOKINGS; + private UserRol rol = UserRol.CONSUMER; + + @Basic(optional = false) + @Enumerated(EnumType.STRING) + private UserStatus status; @JsonIgnore @OneToMany(mappedBy = "userId", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @@ -41,9 +51,12 @@ public class User { public User() { } - public User(int id, String name, String email, UserStatus status, List<Booking> bookings) { + public User(int id, String name, String email, String password, UserRol rol, UserStatus status, + List<Booking> bookings) { setId(id); + setName(name); setEmail(email); + setRol(rol); setStatus(status); setBookings(bookings); } @@ -72,8 +85,28 @@ public class User { this.email = email; } + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public UserRol getRol() { + return this.rol; + } + + public void setRol(UserRol rol) { + this.rol = rol; + } + public UserStatus getStatus() { - return this.status; + if (!getBookings().isEmpty()) + return UserStatus.NO_BOOKINGS; + boolean activeBookings = getBookings().stream() + .anyMatch(booking -> !booking.getEndDate().isBefore(LocalDate.now())); // reserva >= ahora + return activeBookings ? UserStatus.WITH_ACTIVE_BOOKINGS : UserStatus.WITH_INACTIVE_BOOKINGS; } public void setStatus(UserStatus status) { diff --git a/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserRol.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserRol.java new file mode 100644 index 0000000000000000000000000000000000000000..0abe595a154a10347b4eb63a818e72a51ea616f9 --- /dev/null +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserRol.java @@ -0,0 +1,5 @@ +package com.uva.monolith.services.users.models; + +public enum UserRol { + HOTEL_ADMIN, CONSUMER +} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/UserStatus.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserStatus.java similarity index 64% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Models/UserStatus.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserStatus.java index 41adce4ba6df6332286f0971b7f8e43b9126e401..362b8688260d4c13dc4a8eae205411c9d5533d79 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/UserStatus.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/models/UserStatus.java @@ -1,4 +1,4 @@ -package com.uva.roomBooking.Models; +package com.uva.monolith.services.users.models; public enum UserStatus { NO_BOOKINGS, WITH_ACTIVE_BOOKINGS, WITH_INACTIVE_BOOKINGS; diff --git a/java/services/users/src/main/java/com/uva/users/Repositories/UserRepository.java b/java/roomBooking/src/main/java/com/uva/monolith/services/users/repositories/UserRepository.java similarity index 52% rename from java/services/users/src/main/java/com/uva/users/Repositories/UserRepository.java rename to java/roomBooking/src/main/java/com/uva/monolith/services/users/repositories/UserRepository.java index 730510d96586d62c9596fae8b711c06840cd2ff9..e5b44c976f095719854aa8070abc843b898036fe 100644 --- a/java/services/users/src/main/java/com/uva/users/Repositories/UserRepository.java +++ b/java/roomBooking/src/main/java/com/uva/monolith/services/users/repositories/UserRepository.java @@ -1,11 +1,11 @@ -package com.uva.users.Repositories; +package com.uva.monolith.services.users.repositories; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; -import com.uva.users.Models.User; +import com.uva.monolith.services.users.models.User; public interface UserRepository extends JpaRepository<User, Integer> { - Optional<User> findByEmail(String email); + Optional<User> findByEmail(String email); } diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/GlobalExceptionHandler.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/GlobalExceptionHandler.java deleted file mode 100644 index 03b21e27ffa7e4e921cc9801187911d9f1be6a52..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/GlobalExceptionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.uva.roomBooking.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.Map; - -@ControllerAdvice -public class GlobalExceptionHandler { - - @ExceptionHandler(HotelNotFoundException.class) - public ResponseEntity<Map<String, Object>> handleHotelNotFound(HotelNotFoundException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); - } - - @ExceptionHandler(InvalidRequestException.class) - public ResponseEntity<Map<String, Object>> handleInvalidRequest(InvalidRequestException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(InvalidDateRangeException.class) - public ResponseEntity<Map<String, Object>> handleInvalidDateRange(InvalidDateRangeException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(Exception.class) - public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", "An unexpected error occurred: " + ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); - } -} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidRequestException.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidRequestException.java deleted file mode 100644 index a8433b6f620da742dab87dae96a2e0f0193709ff..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidRequestException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.roomBooking.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.BAD_REQUEST) -public class InvalidRequestException extends RuntimeException { - public InvalidRequestException(String message) { - super(message); - } -} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Hotel.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Hotel.java deleted file mode 100644 index 5a23005de99c022b5fff9570e2c515fcfc75e07e..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Hotel.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.uva.roomBooking.Models; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import jakarta.persistence.Basic; -import jakarta.persistence.CascadeType; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.OneToMany; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; - -@Entity -@Table(name = "hotels") -// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, -// property = "id") -public class Hotel { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - - @Basic(optional = false) - private String name; - - @JoinColumn(name = "address_id", referencedColumnName = "id") - @OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Address address; - - @OneToMany(mappedBy = "hotel", fetch = FetchType.EAGER, cascade = CascadeType.ALL) - private List<Room> rooms; - - public Hotel() { - } - - public Hotel(int id, String name, Address address, List<Room> rooms) { - setId(id); - setName(name); - setAddress(address); - setRooms(rooms); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public Address getAddress() { - return this.address; - } - - public void setAddress(Address address) { - this.address = address; - } - - public List<Room> getRooms() { - return this.rooms; - } - - public void setRooms(List<Room> rooms) { - this.rooms = rooms; - rooms.forEach(room -> room.setHotel(this)); - } - -} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Tipo.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Tipo.java deleted file mode 100644 index e1a48b53450e1f87ae070b1bf70bd6a9afc1ea34..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Models/Tipo.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.uva.roomBooking.Models; - -public enum Tipo { - SINGLE, - DOUBLE, - SUITE -} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/HotelRepository.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/HotelRepository.java deleted file mode 100644 index 290f129a7be376279300062d4bf3d7a614abefcc..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/HotelRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.uva.roomBooking.Repositories; - -import com.uva.roomBooking.Models.Hotel; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface HotelRepository extends JpaRepository<Hotel, Integer> { - -} diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/UserRepository.java b/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/UserRepository.java deleted file mode 100644 index 5f02f6d4a3b2147d181b8db36736d85ccfd884b5..0000000000000000000000000000000000000000 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Repositories/UserRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.uva.roomBooking.Repositories; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.uva.roomBooking.Models.User; - -public interface UserRepository extends JpaRepository<User, Integer> { - -} diff --git a/java/roomBooking/src/main/resources/application.properties b/java/roomBooking/src/main/resources/application.properties index 563d4ad07ad10e7fb52bb3defcc3b736d889447b..e9a1304c8364b789ce008c161df0f98daf1238a9 100644 --- a/java/roomBooking/src/main/resources/application.properties +++ b/java/roomBooking/src/main/resources/application.properties @@ -7,4 +7,5 @@ spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Usar esto para alternar entre las exposición del room repository ya que no es necesario su uso pero por defecto, al no cubrir su ruta, se expone -# spring.data.rest.base-path=false \ No newline at end of file +# spring.data.rest.base-path=false +external.services.auth.host=localhost:8101 \ No newline at end of file diff --git a/java/services/auth/pom.xml b/java/services/auth/pom.xml index 9cbd96d71de023623d5eeb168a533f99b9dc8ccc..2838a0e84212291636783be15f1dec8706cf285f 100644 --- a/java/services/auth/pom.xml +++ b/java/services/auth/pom.xml @@ -52,17 +52,17 @@ <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> - <version>0.11.2</version> + <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> - <version>0.11.2</version> + <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> - <version>0.11.2</version> + <version>0.11.5</version> </dependency> </dependencies> @@ -75,4 +75,4 @@ </plugins> </build> -</project> +</project> \ No newline at end of file diff --git a/java/services/auth/src/main/java/com/uva/authentication/Controllers/AuthenticationController.java b/java/services/auth/src/main/java/com/uva/authentication/Controllers/AuthenticationController.java deleted file mode 100644 index f650865625d8d7364c2b0718598351606ad546ce..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Controllers/AuthenticationController.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.uva.authentication.Controllers; - -import com.uva.authentication.Models.User; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.client.RestTemplate; - -import java.util.Date; - -@RestController -@RequestMapping("/auth") -public class AuthenticationController { - - @Autowired - private RestTemplate restTemplate; // Usamos RestTemplate para acceder al microservicio de usuarios - - private final String USER_SERVICE_URL = "http://user-service/users"; // URL del microservicio de usuarios - - // Clave secreta para firmar el token JWT - private final String SECRET_KEY = "your-secret-key"; // Cambia esto por una clave secreta segura - - @PostMapping("/login") - public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) { - // Hacemos una llamada al microservicio de usuarios para obtener el usuario por correo - ResponseEntity<User> userResponse = restTemplate.getForEntity( - USER_SERVICE_URL + "/{email}", - User.class, - loginRequest.getEmail() - ); - - // Verificamos si el usuario existe - if (userResponse.getStatusCode().is2xxSuccessful()) { - User user = userResponse.getBody(); - // Verificamos que la contraseña coincida (esto debería hacerse de forma segura en un servicio real) - if (user != null && user.getPassword().equals(loginRequest.getPassword())) { - // Generamos el token JWT si la autenticación es correcta - String token = generateToken(user.getName(), user.getEmail()); - return ResponseEntity.ok(new AuthResponse(token)); - } - } - - // Si el usuario no existe o la contraseña es incorrecta - return ResponseEntity.status(401).body("Invalid email or password"); - } - - // Método para generar el token JWT - private String generateToken(String name, String email) { - return Jwts.builder() - .setSubject(name) - .claim("email", email) // Añadimos el correo como parte del payload - .setIssuedAt(new Date()) // Fecha de emisión - .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // Expira en 1 hora - .signWith(SignatureAlgorithm.HS512, SECRET_KEY) // Firma con la clave secreta - .compact(); - } - - public static class LoginRequest { - private String email; - private String password; - - // Getters and setters - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - } - - public static class AuthResponse { - private String token; - - public AuthResponse(String token) { - this.token = token; - } - - // Getter - public String getToken() { - return token; - } - } -} diff --git a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/GlobalExceptionHandler.java b/java/services/auth/src/main/java/com/uva/authentication/Exceptions/GlobalExceptionHandler.java deleted file mode 100644 index f8c8057c9c856a01ee309437de85576d34b0ff13..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/GlobalExceptionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.uva.authentication.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.Map; - -@ControllerAdvice -public class GlobalExceptionHandler { - - @ExceptionHandler(HotelNotFoundException.class) - public ResponseEntity<Map<String, Object>> handleHotelNotFound(HotelNotFoundException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); - } - - @ExceptionHandler(InvalidRequestException.class) - public ResponseEntity<Map<String, Object>> handleInvalidRequest(InvalidRequestException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(InvalidDateRangeException.class) - public ResponseEntity<Map<String, Object>> handleInvalidDateRange(InvalidDateRangeException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(Exception.class) - public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", "An unexpected error occurred: " + ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); - } -} diff --git a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/HotelNotFoundException.java b/java/services/auth/src/main/java/com/uva/authentication/Exceptions/HotelNotFoundException.java deleted file mode 100644 index 13270b07b214169a995fa980ddbd72cd45aa728f..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/HotelNotFoundException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.authentication.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción -public class HotelNotFoundException extends RuntimeException { - public HotelNotFoundException(int id) { - super("Hotel not found with id: " + id); - } -} diff --git a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidDateRangeException.java b/java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidDateRangeException.java deleted file mode 100644 index 699ddc9124f4aea097659ad8dac1d6d4321654b8..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidDateRangeException.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.uva.authentication.Exceptions; - -public class InvalidDateRangeException extends RuntimeException { - public InvalidDateRangeException(String message) { - super(message); - } -} - diff --git a/java/services/auth/src/main/java/com/uva/authentication/Models/User.java b/java/services/auth/src/main/java/com/uva/authentication/Models/User.java deleted file mode 100644 index eff82ac4dcadfd4cf23b85f9704d8fab999e861b..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Models/User.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.uva.authentication.Models; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import jakarta.persistence.Basic; -import jakarta.persistence.CascadeType; -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.OneToMany; -import jakarta.persistence.Table; - -@Entity -@Table(name = "users") -public class User { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - - @Basic(optional = false) - private String name; - - @Basic(optional = false) - private String email; - - @Basic(optional = false) - @Enumerated(EnumType.STRING) - private UserStatus status = UserStatus.NO_BOOKINGS; - - private String password; - - - - public User() { - } - - public User(int id, String name, String email, UserStatus status, String password) { - setId(id); - setEmail(email); - setStatus(status); - setPassword(password); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return this.email; - } - - public void setEmail(String email) { - this.email = email; - } - - public UserStatus getStatus() { - return this.status; - } - - public void setStatus(UserStatus status) { - this.status = status; - } - - public String getPassword() { - return this.password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/java/services/auth/src/main/java/com/uva/authentication/Models/UserStatus.java b/java/services/auth/src/main/java/com/uva/authentication/Models/UserStatus.java deleted file mode 100644 index 7d37403ba4c02364414e2cdf99cd4f9db269aa3f..0000000000000000000000000000000000000000 --- a/java/services/auth/src/main/java/com/uva/authentication/Models/UserStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.uva.authentication.Models; - -public enum UserStatus { - NO_BOOKINGS, WITH_ACTIVE_BOOKINGS, WITH_INACTIVE_BOOKINGS; -} diff --git a/java/services/auth/src/main/java/com/uva/authentication/api/UserAPI.java b/java/services/auth/src/main/java/com/uva/authentication/api/UserAPI.java new file mode 100644 index 0000000000000000000000000000000000000000..03e44c8462a69bf143876c62eed3a751735a6c3c --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/api/UserAPI.java @@ -0,0 +1,44 @@ +package com.uva.authentication.api; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +import com.uva.authentication.models.RegisterRequest; +import com.uva.authentication.models.User; + +@Component +public class UserAPI { + + @Autowired + private RestTemplate restTemplate; + + @Value("${external.services.users.baseurl}") + private String USER_API_URL; + + public User getUserByEmail(String email) { + String url = USER_API_URL + "?email={email}"; + try { + ResponseEntity<User> userResponse = restTemplate.getForEntity(url, User.class, email); + return userResponse.getBody(); + } catch (HttpClientErrorException e) { + if (e.getStatusCode() != HttpStatus.NOT_FOUND) + throw e; + return null; + } + } + + public User registerUser(RegisterRequest registerRequest) { + String url = USER_API_URL; + ResponseEntity<User> userResponse = restTemplate.postForEntity(url, registerRequest, User.class); + if (!userResponse.getStatusCode().is2xxSuccessful()) + throw new RuntimeException("Failed to register user"); + + return userResponse.getBody(); + } + +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/controllers/AuthController.java b/java/services/auth/src/main/java/com/uva/authentication/controllers/AuthController.java new file mode 100644 index 0000000000000000000000000000000000000000..1bd5c44944e419ea24f3ccff7984aa8c9edae502 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/controllers/AuthController.java @@ -0,0 +1,46 @@ +package com.uva.authentication.controllers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.HttpClientErrorException; +import com.uva.authentication.models.*; +import com.uva.authentication.services.AuthService; + +@RestController +public class AuthController { + + @Autowired + private AuthService authService; + + @PostMapping("/login") + public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest) { + try { + String token = authService.login(loginRequest); + return ResponseEntity.ok(token); + } catch (HttpClientErrorException e) { + if (e.getStatusCode() == HttpStatus.FORBIDDEN) { + // return new ResponseEntity<Void>(HttpStatus.FORBIDDEN); + return new ResponseEntity<String>(e.getMessage(), HttpStatus.FORBIDDEN); + } + } + return new ResponseEntity<String>("Algo no fue bien", HttpStatus.UNAUTHORIZED); + } + + @PostMapping("/register") + public ResponseEntity<String> register(@RequestBody RegisterRequest registerRequest) { + try { + authService.register(registerRequest); + return login(registerRequest); + } catch (HttpClientErrorException e) { + if (e.getStatusCode() == HttpStatus.CONFLICT) { + // return new ResponseEntity<Void>(HttpStatus.FORBIDDEN); + return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT); + } + } + + return new ResponseEntity<String>("Algo no fue bien", HttpStatus.UNAUTHORIZED); + } + +} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/GlobalExceptionHandler.java b/java/services/auth/src/main/java/com/uva/authentication/exceptions/GlobalExceptionHandler.java similarity index 76% rename from java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/GlobalExceptionHandler.java rename to java/services/auth/src/main/java/com/uva/authentication/exceptions/GlobalExceptionHandler.java index 29c475c6cb4f50505fd4ea798423fdbabc74d502..6d4b8d58dbb5560de50b5b2149cbe3f181687446 100644 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/GlobalExceptionHandler.java +++ b/java/services/auth/src/main/java/com/uva/authentication/exceptions/GlobalExceptionHandler.java @@ -1,4 +1,4 @@ -package com.uva.hotelService.Exceptions; +package com.uva.authentication.exceptions; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -39,12 +39,13 @@ public class GlobalExceptionHandler { return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); } - @ExceptionHandler(Exception.class) - public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", "An unexpected error occurred: " + ex.getMessage()); + // @ExceptionHandler(Exception.class) + // public ResponseEntity<Map<String, Object>> handleGeneralException(Exception + // ex) { + // Map<String, Object> body = new HashMap<>(); + // body.put("timestamp", LocalDateTime.now()); + // body.put("message", "An unexpected error occurred: " + ex.getMessage()); - return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); - } + // return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); + // } } diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/HotelNotFoundException.java b/java/services/auth/src/main/java/com/uva/authentication/exceptions/HotelNotFoundException.java similarity index 67% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/HotelNotFoundException.java rename to java/services/auth/src/main/java/com/uva/authentication/exceptions/HotelNotFoundException.java index 3d47f5efad71b6fbf3b3f5912493c9c0af1ca412..c642139b421a5cf864218fa2d0063f955335c5b7 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/HotelNotFoundException.java +++ b/java/services/auth/src/main/java/com/uva/authentication/exceptions/HotelNotFoundException.java @@ -1,9 +1,9 @@ -package com.uva.roomBooking.Exceptions; +package com.uva.authentication.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción +@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción public class HotelNotFoundException extends RuntimeException { public HotelNotFoundException(int id) { super("Hotel not found with id: " + id); diff --git a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidDateRangeException.java b/java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidDateRangeException.java similarity index 78% rename from java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidDateRangeException.java rename to java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidDateRangeException.java index 17a8420453ef402411b61b965d001560a4dd51ce..c3dc917fb03495480007365b117e185521cf7bf2 100644 --- a/java/roomBooking/src/main/java/com/uva/roomBooking/Exceptions/InvalidDateRangeException.java +++ b/java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidDateRangeException.java @@ -1,8 +1,7 @@ -package com.uva.roomBooking.Exceptions; +package com.uva.authentication.exceptions; public class InvalidDateRangeException extends RuntimeException { public InvalidDateRangeException(String message) { super(message); } } - diff --git a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidRequestException.java b/java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidRequestException.java similarity index 87% rename from java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidRequestException.java rename to java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidRequestException.java index 20bd4d00df753bad8b6bfa53ca5f2fc1b74284b0..499a320e58ecd7576cbfff39101db14395f0edbe 100644 --- a/java/services/auth/src/main/java/com/uva/authentication/Exceptions/InvalidRequestException.java +++ b/java/services/auth/src/main/java/com/uva/authentication/exceptions/InvalidRequestException.java @@ -1,4 +1,4 @@ -package com.uva.authentication.Exceptions; +package com.uva.authentication.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/java/services/auth/src/main/java/com/uva/authentication/jwt/JwtUtil.java b/java/services/auth/src/main/java/com/uva/authentication/jwt/JwtUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..6c596112fd7c80984099225b35199d9e887bf313 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/jwt/JwtUtil.java @@ -0,0 +1,87 @@ +package com.uva.authentication.jwt; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; + +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import com.uva.authentication.models.User; + +@Component +public class JwtUtil { + + @Value("${security.jwt.secret-key}") + private String secretKey; + + @Value("${security.jwt.expiration-time}") + private long jwtExpiration; + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + public long getExpirationTime() { + return jwtExpiration; + } + + public String generateToken(User user) { + Map<String, Object> extraClaims = new HashMap<>(); + // extraClaims.put("role", user.getRole()); + extraClaims.put("email", user.getEmail()); + extraClaims.put("user", user); + long expiration = jwtExpiration; + + return Jwts + .builder() + .setClaims(extraClaims) + .setSubject(user.getName()) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSignInKey(), SignatureAlgorithm.HS256) + .compact(); + } + + public boolean isTokenValid(String token, User user) { + final String username = extractUsername(token); + return (username.equals(user.getName())) && !isTokenExpired(token); + } + + private boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } + + private Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + private Claims extractAllClaims(String token) { + return Jwts + .parserBuilder() + .setSigningKey(getSignInKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + private Key getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + // byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); // for secret + // key + return Keys.hmacShaKeyFor(keyBytes); + } +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/models/AuthResponse.java b/java/services/auth/src/main/java/com/uva/authentication/models/AuthResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..0ec6ee5d2d5a9aa6b61a09d8e3a8550ba6a9b019 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/models/AuthResponse.java @@ -0,0 +1,14 @@ +package com.uva.authentication.models; + +public class AuthResponse { + private String token; + + public AuthResponse(String token) { + this.token = token; + } + + // Getter + public String getToken() { + return token; + } +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/models/LoginRequest.java b/java/services/auth/src/main/java/com/uva/authentication/models/LoginRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..d829de96fd9a45ed458976f03107f38e8933e797 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/models/LoginRequest.java @@ -0,0 +1,26 @@ +package com.uva.authentication.models; + +import java.util.Objects; + +public class LoginRequest { + private String email; + private String password = String.valueOf(Objects.hashCode("hi")); + + // Getters and setters + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/models/RegisterRequest.java b/java/services/auth/src/main/java/com/uva/authentication/models/RegisterRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..d15ccb3726a4a8b323b894348b55d267feb8ed40 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/models/RegisterRequest.java @@ -0,0 +1,23 @@ +package com.uva.authentication.models; + +public class RegisterRequest extends LoginRequest { + private UserRol rol; + private String name; + + public UserRol getRol() { + return this.rol; + } + + public void setRol(UserRol rol) { + this.rol = rol; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/models/User.java b/java/services/auth/src/main/java/com/uva/authentication/models/User.java new file mode 100644 index 0000000000000000000000000000000000000000..4a8ceb643989c16cd53e90717035c0fa31d09c8d --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/models/User.java @@ -0,0 +1,25 @@ +package com.uva.authentication.models; + +public class User extends RegisterRequest { + private int id; + private UserStatus status; + + public User() { + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public UserStatus getStatus() { + return this.status; + } + + public void setStatus(UserStatus status) { + this.status = status; + } +} diff --git a/java/services/auth/src/main/java/com/uva/authentication/models/UserRol.java b/java/services/auth/src/main/java/com/uva/authentication/models/UserRol.java new file mode 100644 index 0000000000000000000000000000000000000000..80bc5a008c2b7ebf990f2416162d756fb61f5597 --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/models/UserRol.java @@ -0,0 +1,5 @@ +package com.uva.authentication.models; + +public enum UserRol { + HOTEL_ADMIN, CONSUMER +} diff --git a/java/services/users/src/main/java/com/uva/users/Models/UserStatus.java b/java/services/auth/src/main/java/com/uva/authentication/models/UserStatus.java similarity index 69% rename from java/services/users/src/main/java/com/uva/users/Models/UserStatus.java rename to java/services/auth/src/main/java/com/uva/authentication/models/UserStatus.java index 95ebb033127fd89a1af9685deded8c842786645d..cdf51ada0dadf18de9b28caeedf0923c7100ade9 100644 --- a/java/services/users/src/main/java/com/uva/users/Models/UserStatus.java +++ b/java/services/auth/src/main/java/com/uva/authentication/models/UserStatus.java @@ -1,4 +1,4 @@ -package com.uva.users.Models; +package com.uva.authentication.models; public enum UserStatus { NO_BOOKINGS, WITH_ACTIVE_BOOKINGS, WITH_INACTIVE_BOOKINGS; diff --git a/java/services/auth/src/main/java/com/uva/authentication/services/AuthService.java b/java/services/auth/src/main/java/com/uva/authentication/services/AuthService.java new file mode 100644 index 0000000000000000000000000000000000000000..c5ed741466942fa64aa3c6ac47b42a424b90f76d --- /dev/null +++ b/java/services/auth/src/main/java/com/uva/authentication/services/AuthService.java @@ -0,0 +1,61 @@ +package com.uva.authentication.services; + +import java.util.Objects; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import com.uva.authentication.api.UserAPI; +import com.uva.authentication.jwt.JwtUtil; +import com.uva.authentication.models.LoginRequest; +import com.uva.authentication.models.RegisterRequest; +import com.uva.authentication.models.User; + +@Service +public class AuthService { + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserAPI userAPI; + + private String hashPass(String password) { + return String.valueOf(Objects.hashCode(password)); + } + + private boolean authenticateUser(LoginRequest request, User user) { + System.err.println(user); + if (user == null) + return false; + String hashPass = hashPass(request.getPassword()); + // System.err.println(request.getPassword() + " -> " + hashPass + " == " + + // user.getPassword()); + return hashPass.equals(user.getPassword()); + } + + public String login(LoginRequest loginRequest) { + User user = userAPI.getUserByEmail(loginRequest.getEmail()); + boolean isAuthenticated = authenticateUser(loginRequest, user); + + if (!isAuthenticated) { + throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Invalid credentials"); + } + + // Generate a mock JWT token for simplicity + String jwtToken = "Bearer " + jwtUtil.generateToken(user); + return jwtToken; + + } + + public User register(RegisterRequest registerRequest) { + User user = userAPI.getUserByEmail(registerRequest.getEmail()); + if (user != null) + throw new HttpClientErrorException(HttpStatus.CONFLICT, "Email already in use"); + + return userAPI.registerUser(registerRequest); + } + +} diff --git a/java/services/auth/src/main/resources/application.properties b/java/services/auth/src/main/resources/application.properties index 394adbeb066350dbc703341658ee10a64b666856..f08d9f6bd82253e53914fa3c4b695d4c25ba6f24 100644 --- a/java/services/auth/src/main/resources/application.properties +++ b/java/services/auth/src/main/resources/application.properties @@ -8,4 +8,9 @@ spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Usar esto para alternar entre las exposición del room repository ya que no es necesario su uso pero por defecto, al no cubrir su ruta, se expone -# spring.data.rest.base-path=false \ No newline at end of file +# spring.data.rest.base-path=false +security.jwt.secret-key=3cfa76ef14937c1c0ea519f8fc057a80fcd04a7420f8e8bcd0a7567c272e007b +# 1h in millisecond +security.jwt.expiration-time=3600000 + +external.services.users.baseurl=http://localhost:8080/users \ No newline at end of file diff --git a/java/services/bookings/.gitignore b/java/services/bookings/.gitignore deleted file mode 100644 index 549e00a2a96fa9d7c5dbc9859664a78d980158c2..0000000000000000000000000000000000000000 --- a/java/services/bookings/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/java/services/bookings/Dockerfile b/java/services/bookings/Dockerfile deleted file mode 100644 index 8d0b79d6514534deddac782fc9367bcdbcaf89c3..0000000000000000000000000000000000000000 --- a/java/services/bookings/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM maven:3-openjdk-17 AS maven -WORKDIR /app -COPY ./ ./ -RUN mvn -Dmaven.test.skip clean package -FROM openjdk:17-jdk-oracle -ARG JAR_FILE=/app/target/*.jar -COPY --from=maven ${JAR_FILE} app.jar -ENV PORT 8080 -EXPOSE $PORT -ENTRYPOINT ["java","-jar", "/app.jar"] \ No newline at end of file diff --git a/java/services/bookings/mvnw b/java/services/bookings/mvnw deleted file mode 100755 index 19529ddf8c6eaa08c5c75ff80652d21ce4b72f8c..0000000000000000000000000000000000000000 --- a/java/services/bookings/mvnw +++ /dev/null @@ -1,259 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.2 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - if [ -n "${JAVA_HOME-}" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/java/services/bookings/mvnw.cmd b/java/services/bookings/mvnw.cmd deleted file mode 100644 index 249bdf3822221aa612d1da2605316cabd7b07e50..0000000000000000000000000000000000000000 --- a/java/services/bookings/mvnw.cmd +++ /dev/null @@ -1,149 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.2 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' -$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -if ($env:MAVEN_USER_HOME) { - $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" -} -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/services/bookings/pom.xml b/java/services/bookings/pom.xml deleted file mode 100644 index 957ab2baae5bc9cd55fd13fa4610617dcf4153a0..0000000000000000000000000000000000000000 --- a/java/services/bookings/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>3.3.4</version> - <relativePath/> <!-- lookup parent from repository --> - </parent> - <groupId>com.uva</groupId> - <artifactId>bookingService</artifactId> - <version>0.0.1-SNAPSHOT</version> - <name>bookingService</name> - <description>Booking Microservice</description> - <url/> - <licenses> - <license/> - </licenses> - <developers> - <developer/> - </developers> - <scm> - <connection/> - <developerConnection/> - <tag/> - <url/> - </scm> - <properties> - <java.version>17</java.version> - </properties> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-rest</artifactId> - </dependency> - - <dependency> - <groupId>com.mysql</groupId> - <artifactId>mysql-connector-j</artifactId> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - </plugin> - </plugins> - </build> - -</project> diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Controllers/BookingController.java b/java/services/bookings/src/main/java/com/uva/bookings/Controllers/BookingController.java deleted file mode 100644 index 66b49481d04a156fb1a4ab509612ca3a7a601234..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Controllers/BookingController.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.uva.bookings.Controllers; - -import com.uva.bookings.Models.Booking; -import com.uva.bookings.Repositories.BookingRepository; - -import jakarta.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.client.RestTemplate; - -import java.util.List; - -@RestController -@RequestMapping("/bookings") -@CrossOrigin(origins = "*") -public class BookingController { - - @Autowired - private BookingRepository bookingRepository; - - @Autowired - private RestTemplate restTemplate; - - @GetMapping - public ResponseEntity<List<Booking>> getBookings( - @RequestParam(required = false) String startDate, - @RequestParam(required = false) String endDate, - @RequestParam(required = false) Integer roomId) { - - // Si no se proporcionan filtros, devolver todas las reservas - if (startDate == null && endDate == null && roomId == null) { - return ResponseEntity.ok(bookingRepository.findAll()); - } - - // Obtener reservas filtradas por los parámetros dados - List<Booking> bookings = bookingRepository.findByFilters(startDate, endDate, roomId); - if (bookings.isEmpty()) { - return ResponseEntity.noContent().build(); - } - - return ResponseEntity.ok(bookings); - } - - @PostMapping - public Booking createBooking(@RequestBody Booking booking) { - // Llamada al microservicio de usuarios para validar al usuario - ResponseEntity<Void> userResponse = restTemplate.exchange( - "http://user-service/users/{userId}", - HttpMethod.GET, - null, - Void.class, - booking.getUserId() - ); - if (!userResponse.getStatusCode().is2xxSuccessful()) { - throw new RuntimeException("User not found"); - } - - // Llamada al microservicio de habitaciones para validar la habitación - ResponseEntity<Void> roomResponse = restTemplate.exchange( - "http://room-service/rooms/{roomId}", - HttpMethod.GET, - null, - Void.class, - booking.getRoomId() - ); - if (!roomResponse.getStatusCode().is2xxSuccessful()) { - throw new RuntimeException("Room not found"); - } - - // Verificar disponibilidad - List<Booking> existingBookings = bookingRepository.findByRoomIdAndDateRange( - booking.getRoomId(), booking.getStartDate(), booking.getEndDate()); - - if (!existingBookings.isEmpty()) { - throw new RuntimeException("Room is not available for the selected dates"); - } - - return bookingRepository.save(booking); - } - - @GetMapping("/{id}") - public Booking getBookingById(@PathVariable Integer id) { - return bookingRepository.findById(id) - .orElseThrow(() -> new RuntimeException("Booking not found")); - } - - @GetMapping(params = "userId") - public ResponseEntity<List<Booking>> getBookingsByUserId(@RequestParam Integer userId) { - // Llamada al microservicio de usuarios para validar la existencia del usuario - ResponseEntity<Void> userResponse = restTemplate.exchange( - "http://user-service/users/{userId}", - HttpMethod.GET, - null, - Void.class, - userId - ); - - if (!userResponse.getStatusCode().is2xxSuccessful()) { - return ResponseEntity.noContent().build(); - } - - List<Booking> bookings = bookingRepository.findByUserId(userId); - if (bookings.isEmpty()) { - return ResponseEntity.noContent().build(); - } - return ResponseEntity.ok(bookings); - } - - @DeleteMapping("/{id}") - @Transactional - public ResponseEntity<Void> deleteBooking(@PathVariable Integer id) { - try { - if (!bookingRepository.existsById(id)) - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - - bookingRepository.deleteBookingById(id); - return new ResponseEntity<>(HttpStatus.ACCEPTED); - } catch (Exception e) { - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); - } - } -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/GlobalExceptionHandler.java b/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/GlobalExceptionHandler.java deleted file mode 100644 index 8a9f4447dd4c4a94fbc32379ced1c86e8bd75e8c..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/GlobalExceptionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.uva.bookings.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.Map; - -@ControllerAdvice -public class GlobalExceptionHandler { - - @ExceptionHandler(HotelNotFoundException.class) - public ResponseEntity<Map<String, Object>> handleHotelNotFound(HotelNotFoundException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); - } - - @ExceptionHandler(InvalidRequestException.class) - public ResponseEntity<Map<String, Object>> handleInvalidRequest(InvalidRequestException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(InvalidDateRangeException.class) - public ResponseEntity<Map<String, Object>> handleInvalidDateRange(InvalidDateRangeException ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); - } - - @ExceptionHandler(Exception.class) - public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) { - Map<String, Object> body = new HashMap<>(); - body.put("timestamp", LocalDateTime.now()); - body.put("message", "An unexpected error occurred: " + ex.getMessage()); - - return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); - } -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/HotelNotFoundException.java b/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/HotelNotFoundException.java deleted file mode 100644 index b0f7409bd4ea5bf89816d979c1643dccbe2dea47..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/HotelNotFoundException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.bookings.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción -public class HotelNotFoundException extends RuntimeException { - public HotelNotFoundException(int id) { - super("Hotel not found with id: " + id); - } -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidDateRangeException.java b/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidDateRangeException.java deleted file mode 100644 index adca056e50cc8a5a27e06510b4eefe0ebcfb3207..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Exceptions/InvalidDateRangeException.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.uva.bookings.Exceptions; - -public class InvalidDateRangeException extends RuntimeException { - public InvalidDateRangeException(String message) { - super(message); - } -} - diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Models/Booking.java b/java/services/bookings/src/main/java/com/uva/bookings/Models/Booking.java deleted file mode 100644 index 269daf37234145f3d248ff0782e3b99c0b138168..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Models/Booking.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.uva.bookings.Models; - -import jakarta.persistence.Basic; -import jakarta.persistence.CascadeType; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.Table; -import java.time.LocalDate; - -@Entity -@Table(name = "bookings") -public class Booking { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - @Column(name = "user_id", nullable = false) - private int userId; - @Column(name = "room_id", nullable = false) - private int roomId; - @Column(name = "start_date", nullable = false) - private LocalDate startDate; - @Column(name = "end_date", nullable = false) - private LocalDate endDate; - - public Booking() { - } - - public Booking(int id, int userId, int roomID, LocalDate startDate, LocalDate endDate) { - this.id = id; - this.userId = userId; - this.roomId = roomID; - this.startDate = startDate; - this.endDate = endDate; - } - - public void setId(int id) { - this.id = id; - } - - public int getId() { - return this.id; - } - - public void setUserId(int userId) { - this.userId = userId; - } - - public int getUserId() { - return this.userId; - } - - public void setRoomId(int roomID) { - this.roomId = roomID; - } - - public int getRoomId() { - return this.roomId; - } - - public void setStartDate(LocalDate startDate) { - this.startDate = startDate; - } - - public LocalDate getStartDate() { - return this.startDate; - } - - public void setEndDate(LocalDate endDate) { - this.endDate = endDate; - } - - public LocalDate getEndDate() { - return this.endDate; - } - -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/Repositories/BookingRepository.java b/java/services/bookings/src/main/java/com/uva/bookings/Repositories/BookingRepository.java deleted file mode 100644 index 8459911ba59cbf0095b2a7406c0022004f17cd9f..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/Repositories/BookingRepository.java +++ /dev/null @@ -1,40 +0,0 @@ -// BookingRepository.java -package com.uva.bookings.Repositories; - -import com.uva.bookings.Models.Booking; - -import jakarta.transaction.Transactional; - -import java.time.LocalDate; -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -public interface BookingRepository extends JpaRepository<Booking, Integer> { - - @Query("SELECT b FROM Booking b WHERE b.roomId = ?1 AND b.startDate < ?2 AND b.endDate > ?3") - List<Booking> findByRoomIdAndDateRange(@Param("roomId") int roomId, @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - @Transactional - @Modifying - @Query("DELETE FROM Booking b WHERE b.id = ?1") - void deleteBookingById(@Param("id") Integer id); - - - List<Booking> findByUserId(Integer userId); - - @Query("SELECT b FROM Booking b WHERE " - + "(:roomId IS NULL OR b.roomId = :roomId) AND " - + "(:startDate IS NULL OR b.startDate >= :startDate) AND " - + "(:endDate IS NULL OR b.endDate <= :endDate)") - List<Booking> findByFilters(@Param("startDate") String startDate, - @Param("endDate") String endDate, - @Param("roomId") Integer roomId); - - - -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/bookingServiceApplication.java b/java/services/bookings/src/main/java/com/uva/bookings/bookingServiceApplication.java deleted file mode 100644 index ae4765caf5111f18fdbceafd5a66272e8aafd775..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/bookingServiceApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.bookings; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class bookingServiceApplication { - - public static void main(String[] args) { - SpringApplication.run(bookingServiceApplication.class, args); - } - -} diff --git a/java/services/bookings/src/main/java/com/uva/bookings/config/RestTemplateConfig.java b/java/services/bookings/src/main/java/com/uva/bookings/config/RestTemplateConfig.java deleted file mode 100644 index 9891319840494a78fb1f0c8c67a1001461d4467b..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/java/com/uva/bookings/config/RestTemplateConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.uva.bookings.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class RestTemplateConfig { - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } -} diff --git a/java/services/bookings/src/main/resources/application.properties b/java/services/bookings/src/main/resources/application.properties deleted file mode 100644 index afaa0e3df29833b5a13dc71cbbdfb523897f4cc8..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/main/resources/application.properties +++ /dev/null @@ -1,11 +0,0 @@ -spring.application.name=bookingService -server.port=8131 -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect -spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/RoomsBooking?createDatabaseIfNotExist=true -spring.datasource.username=user -spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver - -# Usar esto para alternar entre las exposición del room repository ya que no es necesario su uso pero por defecto, al no cubrir su ruta, se expone -# spring.data.rest.base-path=false \ No newline at end of file diff --git a/java/services/bookings/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java b/java/services/bookings/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java deleted file mode 100644 index 3b50599492c36017391c0dcabd81573f123a809a..0000000000000000000000000000000000000000 --- a/java/services/bookings/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.roomBooking; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class RoomBookingApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/java/services/check_service.sh b/java/services/check_service.sh deleted file mode 100644 index 2a474f277d1a5b2d2974f793b9f2dd4b169bb6ee..0000000000000000000000000000000000000000 --- a/java/services/check_service.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/bash -servicesdir="$PWD" -for i in $(ls $servicesdir); do - if [ -d "$servicesdir/$i" ]; then - logfile="/tmp/debug_$i.log" - echo -n Log file for $i service: - [ ! -f ] && echo -n " NOT" - echo " FOUND" - fi -done - -for i in {0..30..10}; do - port=$((8101 + $i)) - curl "http://localhost:$port" > /dev/null 2>/dev/null - if [ $? -eq 0 ]; then - echo "Port $port is open" - else - echo "Port $port is closed" - fi -done \ No newline at end of file diff --git a/java/services/hotels/.gitignore b/java/services/hotels/.gitignore deleted file mode 100644 index 549e00a2a96fa9d7c5dbc9859664a78d980158c2..0000000000000000000000000000000000000000 --- a/java/services/hotels/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/java/services/hotels/.mvn/wrapper/maven-wrapper.properties b/java/services/hotels/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index d58dfb70bab565a697e6854eb012d17e0fd39bd4..0000000000000000000000000000000000000000 --- a/java/services/hotels/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -wrapperVersion=3.3.2 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/services/hotels/Dockerfile b/java/services/hotels/Dockerfile deleted file mode 100644 index 8d0b79d6514534deddac782fc9367bcdbcaf89c3..0000000000000000000000000000000000000000 --- a/java/services/hotels/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM maven:3-openjdk-17 AS maven -WORKDIR /app -COPY ./ ./ -RUN mvn -Dmaven.test.skip clean package -FROM openjdk:17-jdk-oracle -ARG JAR_FILE=/app/target/*.jar -COPY --from=maven ${JAR_FILE} app.jar -ENV PORT 8080 -EXPOSE $PORT -ENTRYPOINT ["java","-jar", "/app.jar"] \ No newline at end of file diff --git a/java/services/hotels/mvnw b/java/services/hotels/mvnw deleted file mode 100755 index 19529ddf8c6eaa08c5c75ff80652d21ce4b72f8c..0000000000000000000000000000000000000000 --- a/java/services/hotels/mvnw +++ /dev/null @@ -1,259 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.2 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - if [ -n "${JAVA_HOME-}" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/java/services/hotels/mvnw.cmd b/java/services/hotels/mvnw.cmd deleted file mode 100644 index 249bdf3822221aa612d1da2605316cabd7b07e50..0000000000000000000000000000000000000000 --- a/java/services/hotels/mvnw.cmd +++ /dev/null @@ -1,149 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.2 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' -$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -if ($env:MAVEN_USER_HOME) { - $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" -} -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/services/hotels/pom.xml b/java/services/hotels/pom.xml deleted file mode 100644 index fd6521678ea85077d527d118898ab02c8c8d9e79..0000000000000000000000000000000000000000 --- a/java/services/hotels/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>3.3.4</version> - <relativePath/> <!-- lookup parent from repository --> - </parent> - <groupId>com.uva</groupId> - <artifactId>hotelService</artifactId> - <version>0.0.1-SNAPSHOT</version> - <name>hotelService</name> - <description>Hotel Microservice REST</description> - <url/> - <licenses> - <license/> - </licenses> - <developers> - <developer/> - </developers> - <scm> - <connection/> - <developerConnection/> - <tag/> - <url/> - </scm> - <properties> - <java.version>17</java.version> - </properties> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-rest</artifactId> - </dependency> - - <dependency> - <groupId>com.mysql</groupId> - <artifactId>mysql-connector-j</artifactId> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - </plugin> - </plugins> - </build> - -</project> \ No newline at end of file diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Controllers/HotelController.java b/java/services/hotels/src/main/java/com/uva/hotelService/Controllers/HotelController.java deleted file mode 100644 index fc949f5efce63f12785a858a307ef61b7d41d70d..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Controllers/HotelController.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.uva.hotelService.Controllers; - -import java.util.List; -import java.util.Map; -import java.time.LocalDate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.client.RestTemplate; - -import com.uva.hotelService.Exceptions.HotelNotFoundException; -import com.uva.hotelService.Exceptions.InvalidDateRangeException; -import com.uva.hotelService.Exceptions.InvalidRequestException; -import com.uva.hotelService.Models.Hotel; -import com.uva.hotelService.Models.Room; -import com.uva.hotelService.Repositories.HotelRepository; -import com.uva.hotelService.Repositories.RoomRepository; - -@RestController -@RequestMapping("hotels") -@CrossOrigin(origins = "*") -public class HotelController { - - @Autowired - private HotelRepository hotelRepository; - - @Autowired - private RoomRepository roomRepository; - - @Autowired - private RestTemplate restTemplate; - - // Obtener todos los hoteles - @GetMapping - public List<Hotel> getAllHotels() { - return hotelRepository.findAll(); - } - - // Añadir un hotel con sus habitaciones - @PostMapping - public ResponseEntity<Hotel> addHotel(@RequestBody Hotel hotel) { - Hotel savedHotel = hotelRepository.save(hotel); - return new ResponseEntity<>(savedHotel, HttpStatus.CREATED); - } - - // Obtener un hotel por su ID - @GetMapping("/{id}") - public Hotel getHotelById(@PathVariable int id) { - return hotelRepository.findById(id) - .orElseThrow(() -> new HotelNotFoundException(id)); - } - - // Borrar un hotel junto con sus habitaciones (borrado en cascada) - @DeleteMapping("/{id}") - @Transactional - public ResponseEntity<Void> deleteHotel(@PathVariable Integer id) { - Hotel target = hotelRepository.findById(id) - .orElseThrow(() -> new HotelNotFoundException(id)); - // bookingRepository.deleteAllByHotelId(id); - // TODO revisar como se va a hacer cuando se haga lo de reservas - String deleteUrl = String.format("http://reservas-service/?hotelId=%d", target.getId()); - restTemplate.delete(deleteUrl); - hotelRepository.delete(target); - return new ResponseEntity<>(HttpStatus.NO_CONTENT); - } - - // Obtener habitaciones de un hotel según disponibilidad y fechas - @GetMapping("/{hotelId}/rooms") - public ResponseEntity<List<Room>> getRoomsFromHotel( - @PathVariable int hotelId, - @RequestParam(required = false) LocalDate start, - @RequestParam(required = false) LocalDate end) { - - List<Room> rooms; - rooms = roomRepository.findAllByHotelIdAndAvailable(hotelId, true); - if (start != null && end != null) { - if (!start.isBefore(end)) { - throw new InvalidDateRangeException("La fecha de inicio debe ser anterior a la fecha de fin"); - } - rooms = rooms.stream().filter( - room -> { - // TODO revisar - String url = String.format("http://reservas-service/?hotelId=%d&start=%s&end=%s", room.getId(), - start, end); - return Boolean.parseBoolean( - restTemplate.exchange( - url, - HttpMethod.GET, - null, - Boolean.class).toString()); - }).toList(); - - } - return new ResponseEntity<>(rooms, HttpStatus.OK); - } - - // Actualizar disponibilidad de una habitación específica en un hotel - @PatchMapping("/{hotelId}/rooms/{roomId}") - public ResponseEntity<Room> updateRoomAvailability( - @PathVariable int hotelId, - @PathVariable int roomId, - @RequestBody Map<String, Boolean> body) { - - if (!body.containsKey("available")) { - throw new InvalidRequestException("El campo 'available' es obligatorio"); - } - - Room targetRoom = roomRepository.findByIdAndHotelId(roomId, hotelId) - .orElseThrow(() -> new IllegalArgumentException("Habitación no encontrada")); - - targetRoom.setAvailable(body.get("available")); - roomRepository.save(targetRoom); - - return new ResponseEntity<>(targetRoom, HttpStatus.OK); - } - - // Obtener los detalles de una habitación específica en un hotel - @GetMapping("/{hotelId}/rooms/{roomId}") - public Room getRoomByIdFromHotel( - @PathVariable int hotelId, @PathVariable int roomId) { - return roomRepository.findByIdAndHotelId(roomId, hotelId) - .orElseThrow(() -> new HotelNotFoundException(hotelId)); - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidDateRangeException.java b/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidDateRangeException.java deleted file mode 100644 index 5bddd4c9083a7dd7ca896f7af916dbd5f70aab09..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidDateRangeException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.uva.hotelService.Exceptions; - -public class InvalidDateRangeException extends RuntimeException { - public InvalidDateRangeException(String message) { - super(message); - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidRequestException.java b/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidRequestException.java deleted file mode 100644 index cd714aa29347e661eff5099c835178a67f38a279..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Exceptions/InvalidRequestException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.hotelService.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.BAD_REQUEST) -public class InvalidRequestException extends RuntimeException { - public InvalidRequestException(String message) { - super(message); - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Address.java b/java/services/hotels/src/main/java/com/uva/hotelService/Models/Address.java deleted file mode 100644 index 43bc9642cd9b75d8bd98ea135707e02be1749d04..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Address.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.uva.hotelService.Models; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import jakarta.persistence.Basic; -import jakarta.persistence.CascadeType; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; - -@Entity -@Table(name = "addresses") -public class Address { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - - @Basic(optional = false) - @Column(name = "street_kind") - private String streetKind; - - @Basic(optional = false) - @Column(name = "street_name") - private String streetName; - - @Basic(optional = false) - private int number; - - @Basic(optional = false) - @Column(name = "post_code") - private String postCode; - - @Basic(optional = true) - @Column(name = "other_info") - private String otherInfo; - - @JsonIgnore - @OneToOne(mappedBy = "address", fetch = FetchType.EAGER, cascade = CascadeType.ALL) - private Hotel hotel; - - public Address() { - } - - public Address(String streetKind, String streetName, int number, String postCode, String otherInfo, Hotel hotel) { - setStreetKind(streetKind); - setStreetName(streetName); - setNumber(number); - setPostCode(postCode); - setOtherInfo(otherInfo); - setHotel(hotel); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getStreetKind() { - return this.streetKind; - } - - public void setStreetKind(String streetKind) { - this.streetKind = streetKind; - } - - public String getStreetName() { - return this.streetName; - } - - public void setStreetName(String streetName) { - this.streetName = streetName; - } - - public int getNumber() { - return this.number; - } - - public void setNumber(int number) { - this.number = number; - } - - public String getPostCode() { - return this.postCode; - } - - public void setPostCode(String postCode) { - this.postCode = postCode; - } - - public String getOtherInfo() { - return this.otherInfo; - } - - public void setOtherInfo(String otherInfo) { - this.otherInfo = otherInfo; - } - - public Hotel getHotel() { - return this.hotel; - } - - public void setHotel(Hotel hotel) { - this.hotel = hotel; - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Room.java b/java/services/hotels/src/main/java/com/uva/hotelService/Models/Room.java deleted file mode 100644 index 0d09d6f81477c0331691c8e4b5e36ac58e0d0d24..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Models/Room.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.uva.hotelService.Models; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import jakarta.persistence.Basic; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.Table; - -@Entity -@Table(name = "rooms") -// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, -// property = "id") -public class Room { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - - @ManyToOne - @JoinColumn(name = "hotel_id", referencedColumnName = "id") - @JsonIgnore - private Hotel hotel; - @Column(name = "room_number", nullable = false) - private String roomNumber; - @Column(name = "type", nullable = false) - private Tipo type; - @Column(name = "available", nullable = false) - private boolean available; - - public Room() { - } - - public Room(int id, Hotel hotelId, String roomNumber, Tipo type, boolean available) { - this.id = id; - this.hotel = hotelId; - this.roomNumber = roomNumber; - this.type = type; - this.available = available; - } - - public void setId(int id) { - this.id = id; - } - - public int getId() { - return this.id; - } - - public void setHotel(Hotel hotelId) { - this.hotel = hotelId; - } - - public Hotel getHotel() { - return this.hotel; - } - - public void setRoomNumber(String roomNumber) { - this.roomNumber = roomNumber; - } - - public String getRoomNumber() { - return this.roomNumber; - } - - public void setType(Tipo type) { - this.type = type; - } - - public Tipo getType() { - return this.type; - } - - public void setAvailable(boolean available) { - this.available = available; - } - - public boolean isAvailable() { - return this.available; - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/Repositories/RoomRepository.java b/java/services/hotels/src/main/java/com/uva/hotelService/Repositories/RoomRepository.java deleted file mode 100644 index c84a86eb58035937dba9638933036196c2d1a470..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/Repositories/RoomRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.uva.hotelService.Repositories; - -import org.springframework.data.jpa.repository.JpaRepository; -import com.uva.hotelService.Models.Room; -import java.util.List; -import java.util.Optional; - -public interface RoomRepository extends JpaRepository<Room, Integer> { - - Optional<Room> findByIdAndHotelId(int id, int hotelId); - - List<Room> findAllByHotelId(int hotelId); - - List<Room> findAllByHotelIdAndAvailable(int hotelId, boolean available); -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/config/RestTemplateConfig.java b/java/services/hotels/src/main/java/com/uva/hotelService/config/RestTemplateConfig.java deleted file mode 100644 index 05af4ebcc1528bb428c9ac6022d61f109c7dc4d5..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/config/RestTemplateConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.uva.hotelService.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class RestTemplateConfig { - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } -} diff --git a/java/services/hotels/src/main/java/com/uva/hotelService/hotelServiceApplication.java b/java/services/hotels/src/main/java/com/uva/hotelService/hotelServiceApplication.java deleted file mode 100644 index 0068b98f3b84aa2f29a70339223880279ecb7e09..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/java/com/uva/hotelService/hotelServiceApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.hotelService; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class hotelServiceApplication { - - public static void main(String[] args) { - SpringApplication.run(hotelServiceApplication.class, args); - } - -} diff --git a/java/services/hotels/src/main/resources/application.properties b/java/services/hotels/src/main/resources/application.properties deleted file mode 100644 index 5021e2005773ae5544474798099ed2b72bb1edb4..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -spring.application.name=hotelService -server.port=8121 -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect -spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/RoomsBooking?createDatabaseIfNotExist=true -spring.datasource.username=user -spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver \ No newline at end of file diff --git a/java/services/hotels/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java b/java/services/hotels/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java deleted file mode 100644 index 3b50599492c36017391c0dcabd81573f123a809a..0000000000000000000000000000000000000000 --- a/java/services/hotels/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.roomBooking; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class RoomBookingApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/java/services/launch.sh b/java/services/launch.sh deleted file mode 100644 index 7224e675de8f43307adc80214a8453266d140fbb..0000000000000000000000000000000000000000 --- a/java/services/launch.sh +++ /dev/null @@ -1,16 +0,0 @@ -#! /usr/bin/bash -servicesdir="$PWD" -pidfile=$servicesdir/servers.pid -echo "Pids of launch `date`" > $pidfile -for i in $(ls $servicesdir); do - if [ -d $servicesdir/$i ]; then - cd $servicesdir/$i - logfile="/tmp/debug_$i.log" - mvn spring-boot:run > $logfile & - pid=$! - # echo "El servicio se está ejecutando en segundo plano con PID: $pid" - # Opcionalmente, puedes guardar el PID en un archivo - echo "$i running in pid $pid" >> $pidfile - echo Launched $i service, view the log in $logfile - fi -done diff --git a/java/services/servers.pid b/java/services/servers.pid deleted file mode 100644 index 689f217b8da2a2b0f56e68aeeebb43cfa149e491..0000000000000000000000000000000000000000 --- a/java/services/servers.pid +++ /dev/null @@ -1,5 +0,0 @@ -Pids of launch dom 17 nov 2024 12:30:54 CET -auth running in pid 104539 -bookings running in pid 104540 -hotels running in pid 104541 -users running in pid 104542 diff --git a/java/services/stop-service.sh b/java/services/stop-service.sh deleted file mode 100644 index 87a710ea48416c38e6ccfada5a7fe6bb96bdb530..0000000000000000000000000000000000000000 --- a/java/services/stop-service.sh +++ /dev/null @@ -1,4 +0,0 @@ -for i in {0..30..10}; do - port=$((8101 + $i)) - kill `sudo lsof -t -i :$port` -done \ No newline at end of file diff --git a/java/services/users/.gitignore b/java/services/users/.gitignore deleted file mode 100644 index 549e00a2a96fa9d7c5dbc9859664a78d980158c2..0000000000000000000000000000000000000000 --- a/java/services/users/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/java/services/users/.mvn/wrapper/maven-wrapper.properties b/java/services/users/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index d58dfb70bab565a697e6854eb012d17e0fd39bd4..0000000000000000000000000000000000000000 --- a/java/services/users/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,19 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -wrapperVersion=3.3.2 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/java/services/users/Dockerfile b/java/services/users/Dockerfile deleted file mode 100644 index 8d0b79d6514534deddac782fc9367bcdbcaf89c3..0000000000000000000000000000000000000000 --- a/java/services/users/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM maven:3-openjdk-17 AS maven -WORKDIR /app -COPY ./ ./ -RUN mvn -Dmaven.test.skip clean package -FROM openjdk:17-jdk-oracle -ARG JAR_FILE=/app/target/*.jar -COPY --from=maven ${JAR_FILE} app.jar -ENV PORT 8080 -EXPOSE $PORT -ENTRYPOINT ["java","-jar", "/app.jar"] \ No newline at end of file diff --git a/java/services/users/mvnw b/java/services/users/mvnw deleted file mode 100755 index 19529ddf8c6eaa08c5c75ff80652d21ce4b72f8c..0000000000000000000000000000000000000000 --- a/java/services/users/mvnw +++ /dev/null @@ -1,259 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.2 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - if [ -n "${JAVA_HOME-}" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/java/services/users/mvnw.cmd b/java/services/users/mvnw.cmd deleted file mode 100644 index 249bdf3822221aa612d1da2605316cabd7b07e50..0000000000000000000000000000000000000000 --- a/java/services/users/mvnw.cmd +++ /dev/null @@ -1,149 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.2 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash> -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' -$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -if ($env:MAVEN_USER_HOME) { - $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" -} -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/java/services/users/pom.xml b/java/services/users/pom.xml deleted file mode 100644 index e5ab046cdc0ae6ece6da29550f9df9fde7963bf1..0000000000000000000000000000000000000000 --- a/java/services/users/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>3.3.4</version> - <relativePath/> <!-- lookup parent from repository --> - </parent> - <groupId>com.uva</groupId> - <artifactId>usersService</artifactId> - <version>0.0.1-SNAPSHOT</version> - <name>usersService</name> - <description>Users microservice</description> - <url/> - <licenses> - <license/> - </licenses> - <developers> - <developer/> - </developers> - <scm> - <connection/> - <developerConnection/> - <tag/> - <url/> - </scm> - <properties> - <java.version>17</java.version> - </properties> - <dependencies> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-rest</artifactId> - </dependency> - - <dependency> - <groupId>com.mysql</groupId> - <artifactId>mysql-connector-j</artifactId> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - </plugin> - </plugins> - </build> - -</project> diff --git a/java/services/users/src/main/java/com/uva/users/Controllers/UserController.java b/java/services/users/src/main/java/com/uva/users/Controllers/UserController.java deleted file mode 100644 index 30274d83e081b0d39b701e3c711b63b2e06ee5eb..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/Controllers/UserController.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.uva.users.Controllers; - -import java.time.LocalDate; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.http.HttpMethod; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; -import org.springframework.core.ParameterizedTypeReference; - -import com.uva.users.Models.UserStatus; -import com.uva.users.Models.User; -import com.uva.users.Repositories.UserRepository; - -@RestController -@RequestMapping("users") -@CrossOrigin(origins = "*") - -public class UserController { - - private UserRepository userRepository; - @Autowired - private RestTemplate restTemplate; - - @GetMapping - public List<User> getAllUsers() { - return userRepository.findAll(); - } - - @PostMapping - public User addUser(@RequestBody User user) { - user.setStatus(UserStatus.NO_BOOKINGS); - return userRepository.save(user); - } - - @GetMapping("/{id}") - public User getUserById(@PathVariable int id) { - return userRepository.findById(id).orElseThrow(); - } - - @PutMapping("/{id}") - public User updateUserData(@PathVariable int id, @RequestBody Map<String, String> json) { - User target = userRepository.findById(id).orElseThrow(); - if (!json.containsKey("name") || !json.containsKey("email")) { - throw new RuntimeException("Missing required fields"); - } - target.setName(json.get("name")); - target.setEmail(json.get("email")); - return userRepository.save(target); - } - - @PatchMapping("/{id}") - public User updateUserState(@PathVariable int id, @RequestBody Map<String, String> json) { - User target = userRepository.findById(id).orElseThrow(); - String strStatus = json.get("status"); - if (strStatus == null) { - throw new RuntimeException("Missing required fields"); - } - UserStatus userStatus = UserStatus.valueOf(strStatus); - - // Consultar el microservicio de booking - ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange( - "http://booking-service/users/{id}/bookings", - HttpMethod.GET, - null, - new ParameterizedTypeReference<List<Map<String, Object>>>() {}, - id - ); - List<Map<String, Object>> bookings = response.getBody(); - - boolean activeBookings = bookings.stream() - .anyMatch(booking -> LocalDate.parse((String) booking.get("endDate")).isAfter(LocalDate.now())); - boolean inactiveBookings = bookings.stream() - .anyMatch(booking -> LocalDate.parse((String) booking.get("startDate")).isBefore(LocalDate.now())); - - switch (userStatus) { - case NO_BOOKINGS: - if (!bookings.isEmpty()) - throw new IllegalArgumentException("Invalid State: The user has at least one booking"); - break; - case WITH_ACTIVE_BOOKINGS: - if (bookings.isEmpty() || !activeBookings) - throw new IllegalArgumentException("Invalid State: The user doesn't have active bookings"); - break; - case WITH_INACTIVE_BOOKINGS: - if (bookings.isEmpty() || !inactiveBookings) - throw new IllegalArgumentException("Invalid State: The user doesn't have inactive bookings"); - break; - default: - break; - } - target.setStatus(userStatus); - return userRepository.save(target); - } - - @DeleteMapping("/{id}") - public User deleteUser(@PathVariable Integer id) { - User target = userRepository.findById(id).orElseThrow(); - userRepository.deleteById(id); - return target; - } - - @GetMapping("/{id}/bookings") - public List<Map<String, Object>> getUserBookingsById(@PathVariable int id) { - // Llamada al microservicio de reservas - ResponseEntity<List<Map<String, Object>>> response = restTemplate.exchange( - "http://booking-service/users/{id}/bookings", - HttpMethod.GET, - null, - new ParameterizedTypeReference<List<Map<String, Object>>>() {}, - id - ); - return response.getBody(); - } - - @GetMapping(params = "email") - public ResponseEntity<User> getUserByEmail(@RequestParam String email) { - return userRepository.findByEmail(email) - .map(ResponseEntity::ok) - .orElse(ResponseEntity.noContent().build()); -} - -} diff --git a/java/services/users/src/main/java/com/uva/users/Exceptions/HotelNotFoundException.java b/java/services/users/src/main/java/com/uva/users/Exceptions/HotelNotFoundException.java deleted file mode 100644 index ef8366dc04e7c03a6758a60c8133b606b114d80b..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/Exceptions/HotelNotFoundException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.users.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción -public class HotelNotFoundException extends RuntimeException { - public HotelNotFoundException(int id) { - super("Hotel not found with id: " + id); - } -} diff --git a/java/services/users/src/main/java/com/uva/users/Exceptions/InvalidRequestException.java b/java/services/users/src/main/java/com/uva/users/Exceptions/InvalidRequestException.java deleted file mode 100644 index 7b2712bccf3907b24cbbf6e664e5250865bb8064..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/Exceptions/InvalidRequestException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.uva.users.Exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(HttpStatus.BAD_REQUEST) -public class InvalidRequestException extends RuntimeException { - public InvalidRequestException(String message) { - super(message); - } -} diff --git a/java/services/users/src/main/java/com/uva/users/Models/User.java b/java/services/users/src/main/java/com/uva/users/Models/User.java deleted file mode 100644 index 455ef0282362759424cba7a75a3385073de48e4e..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/Models/User.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.uva.users.Models; - -import jakarta.persistence.Basic; -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.Table; -@Entity -@Table(name = "users") -public class User { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Basic(optional = false) - private int id; - - @Basic(optional = false) - private String name; - - @Basic(optional = false) - private String email; - - @Basic(optional = false) - @Enumerated(EnumType.STRING) - private UserStatus status = UserStatus.NO_BOOKINGS; - - @Basic (optional = false) - private String password; - - public User() { - } - - public User(int id, String name, String email, UserStatus status, String password) { - setId(id); - setName(name); - setEmail(email); - setStatus(status); - setPassword(password); - } - - // Getters y setters - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public UserStatus getStatus() { - return status; - } - - public void setStatus(UserStatus status) { - this.status = status; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/java/services/users/src/main/java/com/uva/users/UserServiceApplication.java b/java/services/users/src/main/java/com/uva/users/UserServiceApplication.java deleted file mode 100644 index 842ddd66f511f1c766c963b9604924a60919993b..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/UserServiceApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.users; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class UserServiceApplication { - - public static void main(String[] args) { - SpringApplication.run(UserServiceApplication.class, args); - } - -} diff --git a/java/services/users/src/main/java/com/uva/users/config/RestTemplateConfig.java b/java/services/users/src/main/java/com/uva/users/config/RestTemplateConfig.java deleted file mode 100644 index 9343721935b419c627937c713f56b64f40d894d1..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/java/com/uva/users/config/RestTemplateConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.uva.users.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class RestTemplateConfig { - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } -} diff --git a/java/services/users/src/main/resources/application.properties b/java/services/users/src/main/resources/application.properties deleted file mode 100644 index f56d92d0392f20307e5c1cb9e27f16cfb2162ba2..0000000000000000000000000000000000000000 --- a/java/services/users/src/main/resources/application.properties +++ /dev/null @@ -1,11 +0,0 @@ -spring.application.name=userService -server.port=8111 -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect -spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/RoomsBooking?createDatabaseIfNotExist=true -spring.datasource.username=user -spring.datasource.password=password -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver - -# Usar esto para alternar entre las exposición del room repository ya que no es necesario su uso pero por defecto, al no cubrir su ruta, se expone -# spring.data.rest.base-path=false \ No newline at end of file diff --git a/java/services/users/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java b/java/services/users/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java deleted file mode 100644 index 3b50599492c36017391c0dcabd81573f123a809a..0000000000000000000000000000000000000000 --- a/java/services/users/src/test/java/com/uva/roomBooking/RoomBookingApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.uva.roomBooking; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class RoomBookingApplicationTests { - - @Test - void contextLoads() { - } - -}