From f4d6a3f3c777f727af8a3df6a591f9af3639199b Mon Sep 17 00:00:00 2001 From: Claudio Maggioni Date: Mon, 23 Mar 2020 16:42:33 +0100 Subject: [PATCH] RoomController PUT fixed --- .../smarthut/controller/RoomController.java | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/controller/RoomController.java b/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/controller/RoomController.java index 8d083d9..6a2ded4 100644 --- a/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/controller/RoomController.java +++ b/src/main/java/ch/usi/inf/sa4/sanmarinoes/smarthut/controller/RoomController.java @@ -33,40 +33,50 @@ public class RoomController { return roomRepository.findById(id).orElseThrow(NotFoundException::new); } - private Room save(final RoomSaveRequest r, final Principal principal, boolean setWhenNull) { - Room newRoom = new Room(); + @PostMapping + public @ResponseBody Room create( + @Valid @RequestBody RoomSaveRequest r, final Principal principal) { final String username = principal.getName(); final Long userId = userRepository.findByUsername(username).getId(); final String img = r.getImage(); final Room.Icon icon = r.getIcon(); + final Room newRoom = new Room(); newRoom.setUserId(userId); newRoom.setName(r.getName()); - if (img != null) { - newRoom.setImage(img); - } else if (setWhenNull) { - newRoom.setImage(null); - } - if (icon != null) { - newRoom.setIcon(icon); - } else if (setWhenNull) { - newRoom.setIcon(null); - } + newRoom.setImage(img); + newRoom.setIcon(icon); return roomRepository.save(newRoom); } - @PostMapping - public @ResponseBody Room create( - @Valid @RequestBody RoomSaveRequest r, final Principal principal) { - return this.save(r, principal, true); - } - - @PutMapping + @PutMapping("/{id}") public @ResponseBody Room update( - @Valid @RequestBody RoomSaveRequest r, final Principal principal) { - return this.save(r, principal, false); + @PathVariable("id") long id, @RequestBody RoomSaveRequest r, final Principal principal) + throws NotFoundException { + final Room newRoom = + roomRepository + .findByIdAndUsername(id, principal.getName()) + .orElseThrow(NotFoundException::new); + final String img = r.getImage(); + final Room.Icon icon = r.getIcon(); + + if (r.getName() != null) { + newRoom.setName(r.getName()); + } + + if ("".equals(img)) { + newRoom.setImage(null); + } else if (img != null) { + newRoom.setImage(img); + } + + if (icon != null) { + newRoom.setIcon(icon); + } + + return roomRepository.save(newRoom); } @DeleteMapping("/{id}")