Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @MappedSuperclass
- public abstract class BaseEntity {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @JsonIgnore
- private Long id;
- }
- @Entity
- @Table(name = "TO_DO_ITEMS")
- public class ToDoItem extends BaseEntity {
- @Column(name = "TITLE", nullable = false)
- private String title;
- @Column(name = "COMPLETED")
- private boolean completed;
- @Column(name = "DUE_DATE", nullable = false)
- @Convert(converter = LocalDateAttributeConverter.class)
- @JsonDeserialize(using = LocalDateDeserializer.class)
- @JsonSerialize(using = LocalDateSerializer.class)
- private LocalDate dueDate;
- // a ToDoItem is only associated with one user
- @ManyToOne(cascade = CascadeType.PERSIST)
- @JsonIgnore
- @JoinColumn(name = "USER_ID")
- private User user;
- // JPA demands empty constructor
- public ToDoItem() {
- }
- public ToDoItem(User user, String title, LocalDate dueDate) {
- this.user = user;
- this.title = title;
- this.dueDate = dueDate;
- }
- @Entity
- @Table(name = "USERS")
- public class User extends BaseEntity {
- @Column(name = "USERNAME")
- private String username;
- @Column(name = "PASSWORD")
- private String password;
- @Column(name = "EMAIL")
- private String email;
- // user can have many ToDoItems
- @JsonIgnore
- @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
- private Set<ToDoItem> toDoItems = new HashSet<>();
- // JPA demands empty constructor
- public User() {
- }
- public User(String username, String password, String email) {
- this.username = username;
- this.password = password;
- this.email = email;
- }
- public interface UserRepository extends CrudRepository<User, Long> {
- User findByUsername(String username);
- }
- public interface ToDoItemRepository extends CrudRepository<ToDoItem, Long> {}
- @Service
- @Transactional
- public class ToDoItemServiceBean {
- private final ToDoItemRepository toDoItemRepository;
- @Autowired
- public ToDoItemServiceBean(ToDoItemRepository toDoItemRepository) {
- this.toDoItemRepository = toDoItemRepository;
- }
- public ToDoItem addToDo(ToDoItem toDoItem, User user) {
- String toDoTitle = toDoItem.getTitle();
- LocalDate toDoDueDate = toDoItem.getDueDate();
- ToDoItem newToDo = new ToDoItem(user, toDoTitle, toDoDueDate);
- return toDoItemRepository.save(newToDo);
- }
- public ToDoItem editToDo(ToDoItem newToDoItem, ToDoItem oldToDoItem) {
- String newTitle = newToDoItem.getTitle();
- LocalDate newDueDate = newToDoItem.getDueDate();
- oldToDoItem.setTitle(newTitle);
- oldToDoItem.setDueDate(newDueDate);
- return oldToDoItem;
- }
- public void deleteToDo(Long id) {
- toDoItemRepository.delete(id);
- }
- public void completeToDo(ToDoItem toDoItem) {
- toDoItem.setCompleted(true);
- }
- public boolean toDoExists(Long id) {
- if (toDoItemRepository.findOne(id) != null) {
- return true;
- }
- return false;
- }
- public boolean canUserAccessToDo(ToDoItem toDoItem, User user) {
- if (toDoItem.getUser() == user) {
- return true;
- }
- return false;
- }
- public ToDoItem findToDoItemById(Long id) {
- return toDoItemRepository.findOne(id);
- }
- }
- @Service
- @Transactional
- public class UserServiceBean {
- private final UserRepository userRepository;
- private final PasswordEncoder passwordEncoder;
- @Autowired
- public UserServiceBean(UserRepository userRepository, PasswordEncoder passwordEncoder) {
- this.userRepository = userRepository;
- this.passwordEncoder = passwordEncoder;
- }
- public User saveUser(User user) {
- User newUser = new User();
- newUser.setUsername(user.getUsername());
- newUser.setEmail(user.getEmail());
- newUser.setPassword(passwordEncoder.encode(user.getPassword()));
- return userRepository.save(newUser);
- }
- public boolean userExists(User user) {
- if (userRepository.findByUsername(user.getUsername()) == null) {
- return false;
- }
- return true;
- }
- public Iterable<ToDoItem> getAllToDoItems(User user) {
- return user.getToDoItems();
- }
- public boolean deleteUser(Principal principal) {
- if (findLoggedInUser(principal) != null) {
- userRepository.delete(findLoggedInUser(principal));
- return true;
- }
- return false;
- }
- private User findUserbyUsername(String username) {
- return userRepository.findByUsername(username);
- }
- public User findLoggedInUser(Principal principal) {
- return findUserbyUsername(principal.getName());
- }
- }
- @RestController
- public class ToDoItemController {
- private final ToDoItemServiceBean toDoItemService;
- private final UserServiceBean userService;
- private final ObjectMapper mapper;
- @Autowired
- public ToDoItemController(ToDoItemServiceBean toDoItemService, UserServiceBean userService, ObjectMapper mapper) {
- this.toDoItemService = toDoItemService;
- this.userService = userService;
- this.mapper = mapper;
- }
- @GetMapping("/todos")
- public ResponseEntity viewToDos(Principal principal) {
- ObjectNode jsonObject = mapper.createObjectNode();
- User currentUser = userService.findLoggedInUser(principal);
- if (userService.getAllToDoItems(currentUser) != null) {
- return new ResponseEntity<>(userService.getAllToDoItems(currentUser), HttpStatus.OK);
- } else {
- jsonObject.put("status", "You haven't added any ToDos yet");
- return new ResponseEntity<>(jsonObject, HttpStatus.NO_CONTENT);
- }
- }
- // CREATE NEW TODOITEM FROM SENT JSON
- @PostMapping("/todos")
- @ResponseStatus(HttpStatus.CREATED)
- public ToDoItem newToDo(
- @RequestBody ToDoItem toDoItem,
- Principal principal
- ) {
- User currentUser = userService.findLoggedInUser(principal);
- return toDoItemService.addToDo(toDoItem, currentUser);
- }
- @DeleteMapping("/todos/{id}")
- public ResponseEntity deleteToDo(
- @PathVariable("id") Long itemId,
- Principal principal
- ) {
- ObjectNode jsonObject = mapper.createObjectNode();
- User currentUser = userService.findLoggedInUser(principal);
- if (toDoItemService.toDoExists(itemId)) {
- ToDoItem toDoFromDb = toDoItemService.findToDoItemById(itemId);
- if (toDoItemService.canUserAccessToDo(toDoFromDb, currentUser)) {
- toDoItemService.deleteToDo(itemId);
- return new ResponseEntity(HttpStatus.NO_CONTENT);
- } else {
- jsonObject.put("status", "You can only delete your ToDos");
- return new ResponseEntity<>(jsonObject, HttpStatus.FORBIDDEN);
- }
- } else {
- jsonObject.put("status", "ToDo with that ID doesn't exist.");
- return new ResponseEntity<>(jsonObject, HttpStatus.NOT_FOUND);
- }
- }
- @PutMapping("/todos/{id}")
- public ResponseEntity editToDo(
- @PathVariable("id") Long itemId,
- @RequestBody ToDoItem newToDoItem,
- Principal principal
- ) {
- ObjectNode jsonObject = mapper.createObjectNode();
- User currentUser = userService.findLoggedInUser(principal);
- if (toDoItemService.toDoExists(itemId)) {
- ToDoItem toDoFromDb = toDoItemService.findToDoItemById(itemId);
- if (toDoItemService.canUserAccessToDo(toDoFromDb, currentUser)) {
- toDoItemService.editToDo(newToDoItem, toDoFromDb);
- return new ResponseEntity<>(newToDoItem, HttpStatus.OK);
- } else {
- jsonObject.put("status", "You can only edit your ToDos");
- return new ResponseEntity<>(jsonObject, HttpStatus.FORBIDDEN);
- }
- } else {
- jsonObject.put("status", "ToDo with that ID doesn't exist.");
- return new ResponseEntity<>(jsonObject, HttpStatus.NOT_FOUND);
- }
- }
- @PatchMapping("/todos/{id}/complete")
- public ResponseEntity editToDo(
- @PathVariable("id") Long itemId,
- Principal principal
- ) {
- ObjectNode jsonObject = mapper.createObjectNode();
- User currentUser = userService.findLoggedInUser(principal);
- if (toDoItemService.toDoExists(itemId)) {
- ToDoItem toDoFromDb = toDoItemService.findToDoItemById(itemId);
- if (toDoItemService.canUserAccessToDo(toDoFromDb, currentUser)) {
- toDoItemService.completeToDo(toDoFromDb);
- return new ResponseEntity<>(toDoFromDb, HttpStatus.OK);
- } else {
- jsonObject.put("status", "You can only complete your ToDos");
- return new ResponseEntity<>(jsonObject, HttpStatus.FORBIDDEN);
- }
- } else {
- jsonObject.put("status", "ToDo with that ID doesn't exist.");
- return new ResponseEntity<>(jsonObject, HttpStatus.NOT_FOUND);
- }
- }
- }
- @RestController
- public class UserController {
- private final UserServiceBean userService;
- private final ObjectMapper mapper;
- @Autowired
- public UserController(UserServiceBean userService, ObjectMapper objectMapper) {
- this.userService = userService;
- this.mapper = objectMapper;
- }
- // CREATE A USER
- @PostMapping("/users")
- public ResponseEntity<ObjectNode> createUser(@RequestBody User user) {
- ObjectNode jsonObject = mapper.createObjectNode();
- if (userService.userExists(user)) {
- jsonObject.put("status", "User with that username already exists.");
- return new ResponseEntity<>(jsonObject, HttpStatus.BAD_REQUEST);
- }
- userService.saveUser(user);
- jsonObject.put("status", "User created.");
- return new ResponseEntity<>(jsonObject, HttpStatus.CREATED);
- }
- // DELETE YOUR ACCOUNT - deletes logged in user
- @DeleteMapping("/users")
- public ResponseEntity deleteUser(Principal principal) {
- if (userService.deleteUser(principal)) {
- return new ResponseEntity(HttpStatus.NO_CONTENT);
- }
- return new ResponseEntity(HttpStatus.BAD_REQUEST);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement