Advertisement
Guest User

Untitled

a guest
Aug 9th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.80 KB | None | 0 0
  1. @MappedSuperclass
  2. public abstract class BaseEntity {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @Version
  7. private Long version;
  8.  
  9. protected BaseEntity() {
  10. id = null;
  11. }
  12.  
  13. public Long getId() {
  14. return id;
  15. }
  16.  
  17. public void setId(Long id){
  18. this.id = id;
  19. }
  20.  
  21. public Long getVersion() {
  22. return version;
  23. }
  24.  
  25. public void setVersion(Long version) {
  26. this.version = version;
  27. }
  28. }
  29.  
  30. @Entity
  31. public class User extends BaseEntity implements UserDetails{
  32.  
  33.  
  34. @NotNull
  35. @Size(min = 5, max = 30)
  36. private String name;
  37. private String username;
  38. private LocalDate dateOfBirth;
  39. private String address;
  40. @JsonIgnore
  41. private String email;
  42. @JsonIgnore
  43. private String password;
  44. private String barcode;
  45. @ManyToOne(fetch = FetchType.EAGER)
  46. @JoinColumn(name = "role_id")
  47. @JsonIgnore
  48. private Role role;
  49. @JoinTable(name = "loan", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "book_id"))
  50. @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  51. private Set<Book> loanedBooks;
  52.  
  53. private boolean enabled;
  54.  
  55. public User() {
  56. super();
  57. }
  58.  
  59. public User(String name, String username, String email, String password, Role role, boolean enabled, LocalDate dateOfBirth) {
  60. this();
  61. this.name = name;
  62. this.username = username;
  63. this.email = email;
  64. setPassword(password);
  65. this.role = role;
  66. this.enabled = enabled;
  67. this.dateOfBirth = dateOfBirth;
  68. loanedBooks = new HashSet<>();
  69.  
  70. }
  71.  
  72. @Override
  73. public Collection<? extends GrantedAuthority> getAuthorities() {
  74. List<GrantedAuthority> authorities = new ArrayList<>();
  75. authorities.add(new SimpleGrantedAuthority(role.getName()));
  76. return authorities;
  77. }
  78.  
  79. public void loanBook(Book book) throws BookNotAvailableException{
  80. if (book.isAvailable()) {
  81. loanedBooks.add(book);
  82. } else {
  83. throw new BookNotAvailableException("Book is not available right now");
  84. }
  85.  
  86. }
  87.  
  88. public void returnBook(Book book) {
  89. for (Book returnBook : loanedBooks) {
  90. if (returnBook.getBarcode().equals(book.getBarcode()));
  91. loanedBooks.remove(returnBook);
  92. }
  93. }
  94.  
  95. public Set<Book> getLoanedBooks() {
  96. return loanedBooks;
  97. }
  98.  
  99. public void setLoanedBooks(Set<Book> loanedBooks) {
  100. this.loanedBooks = loanedBooks;
  101. }
  102.  
  103.  
  104. public void setPassword(String password) {
  105. this.password = password;
  106. }
  107.  
  108. @Override
  109. public String getPassword() {
  110. return password;
  111. }
  112.  
  113. public String getName() {
  114. return name;
  115. }
  116.  
  117. public void setName(String name) {
  118. this.name = name;
  119. }
  120.  
  121. public String getBarcode() {
  122. return barcode;
  123. }
  124.  
  125. public void setBarcode(String barcode) {
  126. this.barcode = barcode;
  127. }
  128.  
  129. @Override
  130. public String getUsername() {
  131. return username;
  132. }
  133.  
  134. public void setUsername(String username) {
  135. this.username = username;
  136. }
  137.  
  138. public String getEmail() {
  139. return email;
  140. }
  141.  
  142. public void setEmail(String email) {
  143. this.email = email;
  144. }
  145.  
  146. public Role getRole() {
  147. return role;
  148. }
  149.  
  150. public void setEnabled(boolean enabled) {
  151. this.enabled = enabled;
  152. }
  153.  
  154. public void setRole(Role role) {
  155. this.role = role;
  156. }
  157.  
  158. @Override
  159. public boolean isAccountNonExpired() {
  160. return true;
  161. }
  162.  
  163. @Override
  164. public boolean isAccountNonLocked() {
  165. return true;
  166. }
  167.  
  168. @Override
  169. public boolean isCredentialsNonExpired() {
  170. return true;
  171. }
  172.  
  173. @Override
  174. public boolean isEnabled() {
  175. return enabled;
  176. }
  177.  
  178. public LocalDate getDateOfBirth() {
  179. return dateOfBirth;
  180. }
  181.  
  182. public void setDateOfBirth(LocalDate dateOfBirth) {
  183. this.dateOfBirth = dateOfBirth;
  184. }
  185.  
  186. public String getAddress() {
  187. return address;
  188. }
  189.  
  190. public void setAddress(String address) {
  191. this.address = address;
  192. }
  193. }
  194.  
  195. @Controller
  196. public class UserController {
  197. @Autowired
  198. UserService userService;
  199.  
  200. @GetMapping(path = "/users")
  201. @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_LIBRARIAN')")
  202. public String index(Model model) {
  203. return "user/index";
  204. }
  205.  
  206. // Form for editing an existing user
  207. @RequestMapping("users/{userId}/edit")
  208. public String formEditUser(@PathVariable Long userId, Model model) {
  209. // TODO: Add model attributes needed for new form
  210. if (!model.containsAttribute("user")) {
  211. model.addAttribute("user", userService.findById(userId));
  212. }
  213. model.addAttribute("action", String.format("/users/%s", userId));
  214. model.addAttribute("heading", "Edit User");
  215. model.addAttribute("submit", "Update");
  216. return "user/form";
  217. }
  218.  
  219. // Update an existing user
  220. @RequestMapping(value = "/users/{userId}", method = RequestMethod.POST)
  221. public String updateUser(@Valid User user, BindingResult result, RedirectAttributes redirectAttributes) {
  222. // Update user if valid data was received
  223. if (result.hasErrors()) {
  224. // Include validation errors upon redirect
  225. redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.user", result);
  226. // Add user if invalid data was received
  227. redirectAttributes.addFlashAttribute("user", user);
  228. // Redirect back to the form
  229. return String.format("redirect:/users/%s/edit", user.getId());
  230. }
  231.  
  232. userService.save(user);
  233.  
  234. redirectAttributes.addFlashAttribute("flash", new FlashMessage("User successfully updated!", FlashMessage.Status.SUCCESS));
  235.  
  236. //Redirect browser to /users
  237. return "redirect:/users";
  238. }
  239.  
  240. // Form for adding a new user
  241. @RequestMapping(value = "users/add", method = RequestMethod.GET)
  242. public String formNewUser(Model model) {
  243. //..
  244. }
  245.  
  246.  
  247. // Add a User
  248. @RequestMapping(value = "/users", method = RequestMethod.POST)
  249. public String addUser(@Valid User user, BindingResult result, RedirectAttributes redirectAttributes) {
  250. // Add user if valid data was received
  251. if (result.hasErrors()) {
  252. // Include validation errors upon redirect
  253. redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.user", result);
  254. // Add user if invalid data was received
  255. redirectAttributes.addFlashAttribute("user", user);
  256. // Redirect back to the form
  257. return "redirect:/users/add";
  258. }
  259. userService.save(user);
  260.  
  261. redirectAttributes.addFlashAttribute("flash", new FlashMessage("User successfully added!", FlashMessage.Status.SUCCESS));
  262.  
  263. return "redirect:/users";
  264. }
  265.  
  266. // Index for user search and listing
  267. @GetMapping(path = "/users/search")
  268. public String userSearch(@RequestParam("name_or_barcode") String nameOrBarcode,Model model) {
  269. //..
  270. }
  271.  
  272.  
  273. // Single user page
  274. @RequestMapping("/users/{userId}")
  275. public String user(@PathVariable Long userId, Model model) {
  276. User user = userService.findById(userId);
  277. model.addAttribute("user", user);
  278. return "user/details";
  279. }
  280.  
  281. // Delete an existing user
  282. @RequestMapping(value = "/users/{userId}/delete", method = RequestMethod.POST)
  283. public String deleteUser(@PathVariable Long userId, RedirectAttributes redirectAttributes) {
  284. User user = userService.findById(userId);
  285.  
  286. if(user.getLoanedBooks().size() > 0) {
  287. redirectAttributes.addFlashAttribute("flash", new FlashMessage("User cannot be deleted because he/she has borrowed books",FlashMessage.Status.FAILURE));
  288. return String.format("redirect:/users/%s/edit", userId);
  289. }
  290. userService.delete(user);
  291. redirectAttributes.addFlashAttribute("flash", new FlashMessage("User deleted", FlashMessage.Status.SUCCESS));
  292. return "redirect:/users";
  293. }
  294. }
  295.  
  296. <!DOCTYPE html>
  297. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  298. <head th:replace="layout :: head"></head>
  299. <body>
  300. <div th:replace="layout :: nav"></div>
  301. <div th:replace="layout :: flash"></div>
  302. <div class="container">
  303. <form th:action="@{${action}}" method="post" th:object="${user}">
  304. <input type="hidden" th:field="*{enabled}" />
  305. <input type="hidden" th:field="*{role}" />
  306. <input type="hidden" th:field="*{id}" />
  307. <div class="row">
  308. <div class="col s12">
  309. <h2 th:text="${heading}">New User</h2>
  310. </div>
  311. </div>
  312. <div class="divider"></div>
  313. <div class="row">
  314. <div class="col s12 l8" th:classappend="${#fields.hasErrors('name')} ? 'error' : ''">
  315. <input type="text" th:field="*{name}" placeholder="Full Name"/>
  316. <div class="error-message" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div>
  317. </div>
  318. </div>
  319.  
  320. <div class="row">
  321. <div class="col s12 l8">
  322. <button th:text="${submit}" type="submit" class="button">Add</button>
  323. <a th:href="@{/users}" class="button">Cancel</a>
  324. </div>
  325. </div>
  326. </form>
  327. <div class="row delete" th:if="${user.id != null}">
  328. <div class="col s12 l8">
  329. <form th:action="@{|/users/${user.id}/delete|}" method="post">
  330. <button type="submit" class="button">Delete</button>
  331. </form>
  332. </div>
  333. </div>
  334. </div>
  335. <div th:replace="layout :: scripts"></div>
  336. </body>
  337. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement