From d7e1dba341c4a444c6b563a454dead496bc66964 Mon Sep 17 00:00:00 2001 From: Pranay Shinde Date: Mon, 19 Jan 2026 18:04:29 +0530 Subject: [PATCH 1/4] add demo code --- .../com/staxrt/tutorial/controller/UserController.java | 8 ++++++++ src/main/resources/application.properties | 7 +++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/staxrt/tutorial/controller/UserController.java b/src/main/java/com/staxrt/tutorial/controller/UserController.java index 434e30c..02ba4bc 100644 --- a/src/main/java/com/staxrt/tutorial/controller/UserController.java +++ b/src/main/java/com/staxrt/tutorial/controller/UserController.java @@ -32,6 +32,9 @@ 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. @@ -50,6 +53,11 @@ public class UserController { * * @return the list */ + @GetMapping("/demo") + public String printHello() { + return "Hello World!"; + } + @GetMapping("/users") public List getAllUsers() { return userRepository.findAll(); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index affb74d..5543395 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=root ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database From c029d0b2b1ae0cc8fa684f0252b49aea5f7d7e5e Mon Sep 17 00:00:00 2001 From: Pranay Shinde Date: Tue, 20 Jan 2026 11:09:43 +0530 Subject: [PATCH 2/4] Add pagination and sorting --- .../tutorial/controller/UserController.java | 19 +++++ .../staxrt/tutorial/dto/PageResponseDto.java | 70 +++++++++++++++++++ .../staxrt/tutorial/dto/UserResponseDto.java | 41 +++++++++++ .../staxrt/tutorial/service/UserService.java | 44 ++++++++++++ src/main/resources/application.properties | 2 +- 5 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/staxrt/tutorial/dto/PageResponseDto.java create mode 100644 src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java create mode 100644 src/main/java/com/staxrt/tutorial/service/UserService.java diff --git a/src/main/java/com/staxrt/tutorial/controller/UserController.java b/src/main/java/com/staxrt/tutorial/controller/UserController.java index 02ba4bc..ab1a5e0 100644 --- a/src/main/java/com/staxrt/tutorial/controller/UserController.java +++ b/src/main/java/com/staxrt/tutorial/controller/UserController.java @@ -20,10 +20,15 @@ package com.staxrt.tutorial.controller; +import com.staxrt.tutorial.dto.PageResponseDto; +import com.staxrt.tutorial.dto.UserResponseDto; import com.staxrt.tutorial.exception.ResourceNotFoundException; 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.*; @@ -48,6 +53,9 @@ public class UserController { @Autowired private UserRepository userRepository; + @Autowired + UserService userService; + /** * Get all users list. * @@ -57,6 +65,17 @@ public class UserController { public String printHello() { return "Hello World!"; } + + @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); + + } @GetMapping("/users") public List getAllUsers() { 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/UserResponseDto.java b/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java new file mode 100644 index 0000000..48e5672 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java @@ -0,0 +1,41 @@ +package com.staxrt.tutorial.dto; + +public class UserResponseDto { + private Long id; + private String firstname; + private String lastName; + private String email; + 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/service/UserService.java b/src/main/java/com/staxrt/tutorial/service/UserService.java new file mode 100644 index 0000000..ca65014 --- /dev/null +++ b/src/main/java/com/staxrt/tutorial/service/UserService.java @@ -0,0 +1,44 @@ +package com.staxrt.tutorial.service; + + +import java.util.List; + +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.UserResponseDto; +import com.staxrt.tutorial.model.User; +import com.staxrt.tutorial.repository.UserRepository; + +@Service +public class UserService { + @Autowired + UserRepository userRepository; + + + + 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 5543395..8ee3546 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,5 @@ ## Database Properties -spring.datasource.url = jdbc:mysql://localhost:3306/demo_db +spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false spring.datasource.username=root spring.datasource.password=root From 178ec872bfdcf40dc2d9ff1af3610d40dcb8e842 Mon Sep 17 00:00:00 2001 From: Pranay Shinde Date: Sun, 25 Jan 2026 18:41:52 +0530 Subject: [PATCH 3/4] add servie --- .../tutorial/controller/UserController.java | 80 ++++----- .../tutorial/exception/ErrorResponse.java | 154 ++++-------------- .../exception/GlobalExceptionHandler.java | 142 +++++++++------- .../exception/ResourceNotFoundException.java | 79 +++++---- .../exception/UserAlreadyExistException.java | 9 + .../java/com/staxrt/tutorial/model/User.java | 2 +- .../tutorial/repository/UserRepository.java | 4 +- .../staxrt/tutorial/service/UserService.java | 76 +++++++-- src/main/resources/application.properties | 4 +- 9 files changed, 268 insertions(+), 282 deletions(-) create mode 100644 src/main/java/com/staxrt/tutorial/exception/UserAlreadyExistException.java diff --git a/src/main/java/com/staxrt/tutorial/controller/UserController.java b/src/main/java/com/staxrt/tutorial/controller/UserController.java index ab1a5e0..72649f9 100644 --- a/src/main/java/com/staxrt/tutorial/controller/UserController.java +++ b/src/main/java/com/staxrt/tutorial/controller/UserController.java @@ -23,6 +23,7 @@ import com.staxrt.tutorial.dto.PageResponseDto; 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; @@ -40,7 +41,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; - /** * The type User controller. * @@ -66,93 +66,69 @@ public String printHello() { return "Hello World!"; } - @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); - - } - @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 User 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); + @PathVariable(value = "id") Long userId, @Valid @RequestBody User 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/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 index ca65014..faca43b 100644 --- a/src/main/java/com/staxrt/tutorial/service/UserService.java +++ b/src/main/java/com/staxrt/tutorial/service/UserService.java @@ -1,7 +1,9 @@ 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; @@ -12,6 +14,8 @@ import com.staxrt.tutorial.dto.PageResponseDto; 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; @@ -20,25 +24,75 @@ 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 User createUser(User user) { + if (userRepository.existsByEmail(user.getEmail())) { + throw new UserAlreadyExistException("User already exist by email: " + user.getEmail()); + } + return userRepository.save(user); + } + + // update User + public User updateuser(Long userId, User 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); + return updatedUser; + } + + //delete user + public Map deleteUser(Long userId) { + User user = userRepository + .findById(userId) + .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); - 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(); + 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(); + .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()); + 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 8ee3546..791fd39 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,7 @@ ## Database Properties -spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false +spring.datasource.url = jdbc:mysql://localhost:3306/demo_db spring.datasource.username=root -spring.datasource.password=root +spring.datasource.password=1234 ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database From 5cb44796b33409a70ef7100c40d62c18abb018e2 Mon Sep 17 00:00:00 2001 From: Pranay Shinde Date: Mon, 26 Jan 2026 21:36:03 +0530 Subject: [PATCH 4/4] added proper dtos and validation --- .../tutorial/controller/UserController.java | 7 +- .../com/staxrt/tutorial/dto/CreateGroup.java | 5 ++ .../com/staxrt/tutorial/dto/UpdateGroup.java | 5 ++ .../java/com/staxrt/tutorial/dto/UserDto.java | 74 +++++++++++++++++++ .../staxrt/tutorial/dto/UserResponseDto.java | 10 +++ .../staxrt/tutorial/service/UserService.java | 37 ++++++++-- 6 files changed, 129 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/staxrt/tutorial/dto/CreateGroup.java create mode 100644 src/main/java/com/staxrt/tutorial/dto/UpdateGroup.java create mode 100644 src/main/java/com/staxrt/tutorial/dto/UserDto.java diff --git a/src/main/java/com/staxrt/tutorial/controller/UserController.java b/src/main/java/com/staxrt/tutorial/controller/UserController.java index 72649f9..091aa85 100644 --- a/src/main/java/com/staxrt/tutorial/controller/UserController.java +++ b/src/main/java/com/staxrt/tutorial/controller/UserController.java @@ -21,6 +21,7 @@ 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; @@ -90,7 +91,7 @@ public ResponseEntity getUsersById(@PathVariable(value = "id") Long userId * @return the user */ @PostMapping("/users") - public ResponseEntity createUser(@Valid @RequestBody User user) { + public ResponseEntity createUser(@Valid @RequestBody UserDto user) { return ResponseEntity.ok(userService.createUser(user)); } @@ -103,8 +104,8 @@ public ResponseEntity createUser(@Valid @RequestBody User user) { * @throws ResourceNotFoundException the resource not found exception */ @PutMapping("/users/{id}") - public ResponseEntity updateUser( - @PathVariable(value = "id") Long userId, @Valid @RequestBody User userDetails) { + public ResponseEntity updateUser( + @PathVariable(value = "id") Long userId, @Valid @RequestBody UserDto userDetails) { return ResponseEntity.ok(userService.updateuser(userId, userDetails)); } 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/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 index 48e5672..0f03d04 100644 --- a/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java +++ b/src/main/java/com/staxrt/tutorial/dto/UserResponseDto.java @@ -1,15 +1,25 @@ 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; diff --git a/src/main/java/com/staxrt/tutorial/service/UserService.java b/src/main/java/com/staxrt/tutorial/service/UserService.java index faca43b..cd57665 100644 --- a/src/main/java/com/staxrt/tutorial/service/UserService.java +++ b/src/main/java/com/staxrt/tutorial/service/UserService.java @@ -13,6 +13,7 @@ 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; @@ -38,15 +39,33 @@ public User findByUserId(Long id) { // create user - public User createUser(User user) { - if (userRepository.existsByEmail(user.getEmail())) { - throw new UserAlreadyExistException("User already exist by email: " + user.getEmail()); + public UserResponseDto createUser(UserDto userDto) { + if (userRepository.existsByEmail(userDto.getEmail())) { + throw new UserAlreadyExistException("User already exist by email: " + userDto.getEmail()); } - return userRepository.save(user); + 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 User updateuser(Long userId, User userDetails) { + public UserResponseDto updateuser(Long userId, UserDto userDetails) { User user = userRepository .findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId)); @@ -56,7 +75,13 @@ public User updateuser(Long userId, User userDetails) { user.setFirstName(userDetails.getFirstName()); user.setUpdatedAt(new Date()); final User updatedUser = userRepository.save(user); - return updatedUser; + + UserResponseDto userResponseDto = new UserResponseDto(); + userResponseDto.setId(updatedUser.getId()); + userResponseDto.setEmail(updatedUser.getEmail()); + userResponseDto.setFirstname(updatedUser.getFirstName()); + userResponseDto.setLastName(updatedUser.getLastName()); + return userResponseDto; } //delete user