diff --git a/src/main/java/com/staxrt/tutorial/controller/UserController.java b/src/main/java/com/staxrt/tutorial/controller/UserController.java index 434e30c..091aa85 100644 --- a/src/main/java/com/staxrt/tutorial/controller/UserController.java +++ b/src/main/java/com/staxrt/tutorial/controller/UserController.java @@ -20,10 +20,17 @@ package com.staxrt.tutorial.controller; +import com.staxrt.tutorial.dto.PageResponseDto; +import com.staxrt.tutorial.dto.UserDto; +import com.staxrt.tutorial.dto.UserResponseDto; import com.staxrt.tutorial.exception.ResourceNotFoundException; +import com.staxrt.tutorial.exception.UserAlreadyExistException; import com.staxrt.tutorial.model.User; import com.staxrt.tutorial.repository.UserRepository; +import com.staxrt.tutorial.service.UserService; + import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -32,6 +39,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; /** * The type User controller. @@ -45,87 +54,82 @@ public class UserController { @Autowired private UserRepository userRepository; + @Autowired + UserService userService; + /** * Get all users list. * * @return the list */ + @GetMapping("/demo") + public String printHello() { + return "Hello World!"; + } + @GetMapping("/users") - public List getAllUsers() { - return userRepository.findAll(); + public ResponseEntity> getAllUsers() { + return ResponseEntity.ok(userService.findAllUserse()); } /** * Gets users by id. * - * @param userId the user id + * @Pathvaraible userId the user id * @return the users by id * @throws ResourceNotFoundException the resource not found exception */ @GetMapping("/users/{id}") - public ResponseEntity getUsersById(@PathVariable(value = "id") Long userId) - throws ResourceNotFoundException { - User user = - userRepository - .findById(userId) - .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); - return ResponseEntity.ok().body(user); + public ResponseEntity getUsersById(@PathVariable(value = "id") Long userId) { + return ResponseEntity.ok(userService.findByUserId(userId)); } /** * Create user user. * - * @param user the user + * @RequestBody user * @return the user */ @PostMapping("/users") - public User createUser(@Valid @RequestBody User user) { - return userRepository.save(user); + public ResponseEntity createUser(@Valid @RequestBody UserDto user) { + return ResponseEntity.ok(userService.createUser(user)); } /** * Update user response entity. * - * @param userId the user id - * @param userDetails the user details + * @RequestBody user the user id + * * @return the response entity * @throws ResourceNotFoundException the resource not found exception */ @PutMapping("/users/{id}") - public ResponseEntity updateUser( - @PathVariable(value = "id") Long userId, @Valid @RequestBody User userDetails) - throws ResourceNotFoundException { - - User user = - userRepository - .findById(userId) - .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); - - user.setEmail(userDetails.getEmail()); - user.setLastName(userDetails.getLastName()); - user.setFirstName(userDetails.getFirstName()); - user.setUpdatedAt(new Date()); - final User updatedUser = userRepository.save(user); - return ResponseEntity.ok(updatedUser); + public ResponseEntity updateUser( + @PathVariable(value = "id") Long userId, @Valid @RequestBody UserDto userDetails) { + + return ResponseEntity.ok(userService.updateuser(userId, userDetails)); } /** * Delete user map. * - * @param userId the user id + * @Pathvaraible userId the user id * @return the map * @throws Exception the exception */ @DeleteMapping("/user/{id}") - public Map deleteUser(@PathVariable(value = "id") Long userId) throws Exception { - User user = - userRepository - .findById(userId) - .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); - - userRepository.delete(user); - Map response = new HashMap<>(); - response.put("deleted", Boolean.TRUE); - return response; + public ResponseEntity> deleteUser(@PathVariable(value = "id") Long userId) { + return ResponseEntity.ok(userService.deleteUser(userId)); + } + + @GetMapping("/users/getPaginatedusers") + public ResponseEntity> getPaginatedUsers( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "5") int size, + @RequestParam(defaultValue = "id") String sortBy, + @RequestParam(defaultValue = "asc") String direction) { + PageResponseDto users = userService.getUsers(page, size, sortBy, direction); + return ResponseEntity.ok(users); + } } diff --git a/src/main/java/com/staxrt/tutorial/dto/CreateGroup.java b/src/main/java/com/staxrt/tutorial/dto/CreateGroup.java new file mode 100644 index 0000000..507ae67 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/CreateGroup.java @@ -0,0 +1,5 @@ +package com.staxrt.tutorial.dto; + +public interface CreateGroup { + +} diff --git a/src/main/java/com/staxrt/tutorial/dto/PageResponseDto.java b/src/main/java/com/staxrt/tutorial/dto/PageResponseDto.java new file mode 100644 index 0000000..f1dba88 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/PageResponseDto.java @@ -0,0 +1,70 @@ +package com.staxrt.tutorial.dto; + +import java.util.List; + +public class PageResponseDto { + + private List data; + private int page; + private int size; + private long totalElements; + private int totalPages; + private boolean first; + private boolean last; + public PageResponseDto(List data, int page, int size, long totalElements, int totalPages, boolean first, + boolean last) { + this.data = data; + this.page = page; + this.size = size; + this.totalElements = totalElements; + this.totalPages = totalPages; + this.first = first; + this.last = last; + } + public List getData() { + return data; + } + public void setData(List data) { + this.data = data; + } + public int getPage() { + return page; + } + public void setPage(int page) { + this.page = page; + } + public int getSize() { + return size; + } + public void setSize(int size) { + this.size = size; + } + public long getTotalElements() { + return totalElements; + } + public void setTotalElements(long totalElements) { + this.totalElements = totalElements; + } + public int getTotalPages() { + return totalPages; + } + public void setTotalPages(int totalPages) { + this.totalPages = totalPages; + } + public boolean isFirst() { + return first; + } + public void setFirst(boolean first) { + this.first = first; + } + public boolean isLast() { + return last; + } + public void setLast(boolean last) { + this.last = last; + } + + + + +} diff --git a/src/main/java/com/staxrt/tutorial/dto/UpdateGroup.java b/src/main/java/com/staxrt/tutorial/dto/UpdateGroup.java new file mode 100644 index 0000000..bce55c0 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/UpdateGroup.java @@ -0,0 +1,5 @@ +package com.staxrt.tutorial.dto; + +public interface UpdateGroup { + +} diff --git a/src/main/java/com/staxrt/tutorial/dto/UserDto.java b/src/main/java/com/staxrt/tutorial/dto/UserDto.java new file mode 100644 index 0000000..d02df88 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/UserDto.java @@ -0,0 +1,74 @@ +package com.staxrt.tutorial.dto; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class UserDto { + + @NotNull(message = "First name cannot be null") + @Size(min = 2, message = "First name should have at least 2 characters") + @Size(max = 50, message = "First name should have at most 50 characters") + private String firstName; + + @NotNull(message = "Last name cannot be null") + @Size(min = 2, message = "Last name should have at least 2 characters") + @Size(max = 50, message = "Last name should have at most 50 characters") + private String lastName; + + @NotNull(message = "Email cannot be null") + @Email(message = "Email should be valid") + @Size(max = 100, message = "Email should have at most 100 characters") + private String email; + + public UserDto() { + } + + public UserDto(@NotNull(message = "First name cannot be null") String firstName, + @NotNull(message = "Last name cannot be null") String lastName, + @NotNull(message = "Email cannot be null") @Email(message = "Email should be valid") String email +) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "UserDto [firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; + } + + + + + + + + + +} diff --git a/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java b/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java new file mode 100644 index 0000000..0f03d04 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java @@ -0,0 +1,51 @@ +package com.staxrt.tutorial.dto; + +import java.util.Date; + +public class UserResponseDto { + private Long id; + private String firstname; + private String lastName; + private String email; + + + + + public UserResponseDto() { + } + + public UserResponseDto(Long id, String firstname, String lastName, String email) { + this.id = id; + this.firstname = firstname; + this.lastName = lastName; + this.email = email; + + } + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getFirstname() { + return firstname; + } + public void setFirstname(String firstname) { + this.firstname = firstname; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + +} diff --git a/src/main/java/com/staxrt/tutorial/exception/ErrorResponse.java b/src/main/java/com/staxrt/tutorial/exception/ErrorResponse.java index b3a7bb3..7de13e2 100644 --- a/src/main/java/com/staxrt/tutorial/exception/ErrorResponse.java +++ b/src/main/java/com/staxrt/tutorial/exception/ErrorResponse.java @@ -1,123 +1,33 @@ -/* - * - * Copyright (c) 2018-2020 Givantha Kalansuriya, This source is a part of - * Staxrt - sample application source code. - * http://staxrt.com - * - * Licensed 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. - * - */ - package com.staxrt.tutorial.exception; - -import java.util.Date; - -/** - * The type Error response. - * - * @author Givantha Kalansuriya - */ -public class ErrorResponse { - - private Date timestamp; - private String status; - private String message; - private String details; - - /** - * Instantiates a new Error response. - * - * @param timestamp the timestamp - * @param status the status - * @param message the message - * @param details the details - */ - public ErrorResponse(Date timestamp, String status, String message, String details) { - this.timestamp = timestamp; - this.status = status; - this.message = message; - this.details = details; - } - - /** - * Gets timestamp. - * - * @return the timestamp - */ - public Date getTimestamp() { - return timestamp; - } - - /** - * Sets timestamp. - * - * @param timestamp the timestamp - */ - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - /** - * Gets status. - * - * @return the status - */ - public String getStatus() { - return status; - } - - /** - * Sets status. - * - * @param status the status - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * Gets message. - * - * @return the message - */ - public String getMessage() { - return message; - } - - /** - * Sets message. - * - * @param message the message - */ - public void setMessage(String message) { - this.message = message; - } - - /** - * Gets details. - * - * @return the details - */ - public String getDetails() { - return details; - } - - /** - * Sets details. - * - * @param details the details - */ - public void setDetails(String details) { - this.details = details; - } -} +import java.time.LocalDateTime; + +public class ErrorResponse{ + private String message; + private int statusCode; + private LocalDateTime timestamp; + public ErrorResponse(String message, int statusCode) { + this.message = message; + this.statusCode = statusCode; + this.timestamp = LocalDateTime.now(); + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public int getStatusCode() { + return statusCode; + } + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + public LocalDateTime getTimestamp() { + return timestamp; + } + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/staxrt/tutorial/exception/GlobalExceptionHandler.java b/src/main/java/com/staxrt/tutorial/exception/GlobalExceptionHandler.java index 36940be..c510130 100644 --- a/src/main/java/com/staxrt/tutorial/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/staxrt/tutorial/exception/GlobalExceptionHandler.java @@ -1,67 +1,93 @@ -/* - * - * Copyright (c) 2018-2020 Givantha Kalansuriya, This source is a part of - * Staxrt - sample application source code. - * http://staxrt.com - * - * Licensed 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. - * - */ +// /* +// * +// * Copyright (c) 2018-2020 Givantha Kalansuriya, This source is a part of +// * Staxrt - sample application source code. +// * http://staxrt.com +// * +// * Licensed 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. +// * +// */ -package com.staxrt.tutorial.exception; + package com.staxrt.tutorial.exception; + +// 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 org.springframework.web.context.request.WebRequest; + +// import java.util.Date; + +// /** +// * The type Global exception handler. +// * +// * @author Givantha Kalansuriya +// */ +// @ControllerAdvice +// public class GlobalExceptionHandler { + +// /** +// * Resource not found exception response entity. +// * +// * @param ex the ex +// * @param request the request +// * @return the response entity +// */ +// @ExceptionHandler(ResourceNotFoundException.class) +// public ResponseEntity resourceNotFoundException( +// ResourceNotFoundException ex, WebRequest request) { +// ErrorResponse errorDetails = +// new ErrorResponse(new Date(), HttpStatus.NOT_FOUND.toString(), ex.getMessage(), request.getDescription(false)); +// return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); +// } + +// /** +// * Globle excpetion handler response entity. +// * +// * @param ex the ex +// * @param request the request +// * @return the response entity +// */ +// @ExceptionHandler(Exception.class) +// public ResponseEntity globleExcpetionHandler(Exception ex, WebRequest request) { +// ErrorResponse errorDetails = +// new ErrorResponse(new Date(), HttpStatus.INTERNAL_SERVER_ERROR.toString() ,ex.getMessage(), request.getDescription(false)); +// return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); +// } +// } 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 org.springframework.web.context.request.WebRequest; - -import java.util.Date; +import org.springframework.web.bind.annotation.RestControllerAdvice; -/** - * The type Global exception handler. - * - * @author Givantha Kalansuriya - */ -@ControllerAdvice -public class GlobalExceptionHandler { +@RestControllerAdvice +public class GlobalExceptionHandler{ + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity handleResourceNotFoundException(ResourceNotFoundException ex) { + ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.NOT_FOUND.value()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse); + } - /** - * Resource not found exception response entity. - * - * @param ex the ex - * @param request the request - * @return the response entity - */ - @ExceptionHandler(ResourceNotFoundException.class) - public ResponseEntity resourceNotFoundException( - ResourceNotFoundException ex, WebRequest request) { - ErrorResponse errorDetails = - new ErrorResponse(new Date(), HttpStatus.NOT_FOUND.toString(), ex.getMessage(), request.getDescription(false)); - return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); - } + @ExceptionHandler(UserAlreadyExistException.class) + public ResponseEntity handleAlreadyExistUserException(UserAlreadyExistException ex){ + ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.CONFLICT.value()); + return ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse); + } - /** - * Globle excpetion handler response entity. - * - * @param ex the ex - * @param request the request - * @return the response entity - */ - @ExceptionHandler(Exception.class) - public ResponseEntity globleExcpetionHandler(Exception ex, WebRequest request) { - ErrorResponse errorDetails = - new ErrorResponse(new Date(), HttpStatus.INTERNAL_SERVER_ERROR.toString() ,ex.getMessage(), request.getDescription(false)); - return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); - } + @ExceptionHandler(Exception.class) + public ResponseEntity handeleGlobalException(Exception ex){ + ErrorResponse errorResponse = new ErrorResponse("INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR.value()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse); + } } diff --git a/src/main/java/com/staxrt/tutorial/exception/ResourceNotFoundException.java b/src/main/java/com/staxrt/tutorial/exception/ResourceNotFoundException.java index 4cd4a8f..a014e81 100644 --- a/src/main/java/com/staxrt/tutorial/exception/ResourceNotFoundException.java +++ b/src/main/java/com/staxrt/tutorial/exception/ResourceNotFoundException.java @@ -1,42 +1,51 @@ -/* - * - * Copyright (c) 2018-2020 Givantha Kalansuriya, This source is a part of - * Staxrt - sample application source code. - * http://staxrt.com - * - * Licensed 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. - * - */ +// /* +// * +// * Copyright (c) 2018-2020 Givantha Kalansuriya, This source is a part of +// * Staxrt - sample application source code. +// * http://staxrt.com +// * +// * Licensed 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. +// * +// */ -package com.staxrt.tutorial.exception; + package com.staxrt.tutorial.exception; -import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -/** - * The type Resource not found exception. - * - * @author Givantha Kalansuriya - */ -@ResponseStatus(value = HttpStatus.NOT_FOUND) -public class ResourceNotFoundException extends Exception { + import org.springframework.http.HttpStatus; +// import org.springframework.web.bind.annotation.ResponseStatus; - /** - * Instantiates a new Resource not found exception. - * - * @param message the message - */ - public ResourceNotFoundException(String message) { - super(message); +// /** +// * The type Resource not found exception. +// * +// * @author Givantha Kalansuriya +// */ +// @ResponseStatus(value = HttpStatus.NOT_FOUND) +// public class ResourceNotFoundException extends Exception { + +// /** +// * Instantiates a new Resource not found exception. +// * +// * @param message the message +// */ +// public ResourceNotFoundException(String message) { +// super(message); +// } +// } + +@ResponseStatus(org.springframework.http.HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { + public ResourceNotFoundException(String msg) { + super(msg); } } diff --git a/src/main/java/com/staxrt/tutorial/exception/UserAlreadyExistException.java b/src/main/java/com/staxrt/tutorial/exception/UserAlreadyExistException.java new file mode 100644 index 0000000..9777d8a --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/exception/UserAlreadyExistException.java @@ -0,0 +1,9 @@ +package com.staxrt.tutorial.exception; + +public class UserAlreadyExistException extends RuntimeException{ + + public UserAlreadyExistException(String msg) { + super(msg); + } + +} diff --git a/src/main/java/com/staxrt/tutorial/model/User.java b/src/main/java/com/staxrt/tutorial/model/User.java index c5d8e82..f73f734 100644 --- a/src/main/java/com/staxrt/tutorial/model/User.java +++ b/src/main/java/com/staxrt/tutorial/model/User.java @@ -43,7 +43,7 @@ public class User { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "first_name", nullable = false) diff --git a/src/main/java/com/staxrt/tutorial/repository/UserRepository.java b/src/main/java/com/staxrt/tutorial/repository/UserRepository.java index a79fddb..1c5e0f5 100644 --- a/src/main/java/com/staxrt/tutorial/repository/UserRepository.java +++ b/src/main/java/com/staxrt/tutorial/repository/UserRepository.java @@ -10,4 +10,6 @@ * @author Givantha Kalansuriya */ @Repository -public interface UserRepository extends JpaRepository {} +public interface UserRepository extends JpaRepository { + + boolean existsByEmail(String email);} diff --git a/src/main/java/com/staxrt/tutorial/service/UserService.java b/src/main/java/com/staxrt/tutorial/service/UserService.java new file mode 100644 index 0000000..cd57665 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/service/UserService.java @@ -0,0 +1,123 @@ +package com.staxrt.tutorial.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import com.staxrt.tutorial.dto.PageResponseDto; +import com.staxrt.tutorial.dto.UserDto; +import com.staxrt.tutorial.dto.UserResponseDto; +import com.staxrt.tutorial.exception.ResourceNotFoundException; +import com.staxrt.tutorial.exception.UserAlreadyExistException; +import com.staxrt.tutorial.model.User; +import com.staxrt.tutorial.repository.UserRepository; + +@Service +public class UserService { + @Autowired + UserRepository userRepository; + + // get all users + + public List findAllUserse() { + return userRepository.findAll(); + } + + // find user by Id + public User findByUserId(Long id) { + return userRepository.findById(id) + .orElseThrow(() -> new ResourceNotFoundException("user with id " + id + " not found")); + } + + // create user + + public UserResponseDto createUser(UserDto userDto) { + if (userRepository.existsByEmail(userDto.getEmail())) { + throw new UserAlreadyExistException("User already exist by email: " + userDto.getEmail()); + } + User user = new User(); + user.setFirstName(userDto.getFirstName()); + user.setLastName(userDto.getLastName()); + user.setEmail(userDto.getEmail()); + user.setCreatedAt(new Date()); + user.setUpdatedAt(new Date()); + user.setCreatedBy("System"); + user.setUpdatedBy("System"); + + User savedUser = userRepository.save(user); + + UserResponseDto responseDto = new UserResponseDto(); + responseDto.setId(savedUser.getId()); + responseDto.setFirstname(savedUser.getFirstName()); + responseDto.setLastName(savedUser.getLastName()); + responseDto.setEmail(savedUser.getEmail()); + return responseDto; + + + } + + // update User + public UserResponseDto updateuser(Long userId, UserDto userDetails) { + User user = userRepository + .findById(userId) + .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); + + user.setEmail(userDetails.getEmail()); + user.setLastName(userDetails.getLastName()); + user.setFirstName(userDetails.getFirstName()); + user.setUpdatedAt(new Date()); + final User updatedUser = userRepository.save(user); + + UserResponseDto userResponseDto = new UserResponseDto(); + userResponseDto.setId(updatedUser.getId()); + userResponseDto.setEmail(updatedUser.getEmail()); + userResponseDto.setFirstname(updatedUser.getFirstName()); + userResponseDto.setLastName(updatedUser.getLastName()); + return userResponseDto; + } + + //delete user + + public Map deleteUser(Long userId) { + User user = userRepository + .findById(userId) + .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); + + userRepository.delete(user); + Map response = new HashMap<>(); + response.put("deleted", Boolean.TRUE); + return response; + } + + // pagination + + public PageResponseDto getUsers(int page, int size, String sortBy, String direction) { + org.springframework.data.domain.Sort sort = direction.equalsIgnoreCase("desc") + ? Sort.by(sortBy).descending() + : Sort.by(sortBy).ascending(); + + Pageable pageable = PageRequest.of(page, size, sort); + Page userpage = userRepository.findAll(pageable); + + List users = userpage.getContent() + .stream() + .map(user -> new UserResponseDto( + user.getId(), user.getFirstName(), user.getLastName(), user.getEmail())) + .toList(); + + return new PageResponseDto<>(users, userpage.getNumber(), userpage.getSize(), userpage.getTotalElements(), + userpage.getTotalPages(), userpage.isFirst(), userpage.isLast()); + + } + + + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index affb74d..791fd39 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,8 +1,7 @@ ## Database Properties -spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false -spring.datasource.username = root -spring.datasource.password = root - +spring.datasource.url = jdbc:mysql://localhost:3306/demo_db +spring.datasource.username=root +spring.datasource.password=1234 ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database