/* * Copyright (C) 2021 Anton Romanov - All Rights Reserved * You may use, distribute and modify this code, please write to: romanov73@gmail.com. * */ package ru.ulstu.news; import org.springframework.data.domain.Page; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import ru.ulstu.model.OffsetablePageRequest; import ru.ulstu.model.UserRoleConstants; import javax.validation.Valid; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; @Controller @RequestMapping("news") public class NewsController { private final static int DEFAULT_PAGE_SIZE = 10; private final NewsService newsService; public NewsController(NewsService newsService) { this.newsService = newsService; } @GetMapping("/news") public String listNews(Model model, @RequestParam Optional page, @RequestParam Optional size) { int currentPage = page.orElse(1); int pageSize = size.orElse(DEFAULT_PAGE_SIZE); Page newsPage = newsService.getNews(new OffsetablePageRequest(currentPage - 1, pageSize)); model.addAttribute("news", newsPage); int totalPages = newsPage.getTotalPages(); if (totalPages > 0) { List pageNumbers = IntStream.rangeClosed(1, totalPages) .boxed() .collect(Collectors.toList()); model.addAttribute("pageNumbers", pageNumbers); } return "news"; } @GetMapping("/editNews/{newsId}") @Secured({UserRoleConstants.ADMIN}) public String editNews(@PathVariable(value = "newsId") Integer id, Model model) { model.addAttribute("news", (id != null && id != 0) ? newsService.getById(id) : new News()); return "editNews"; } @GetMapping("/news/{newsId}") public String viewNews(@PathVariable(value = "newsId") Integer id, Model model) { model.addAttribute("news", id != null ? newsService.getById(id) : new News()); return "viewNews"; } @PostMapping("saveNews") @Secured({UserRoleConstants.ADMIN}) public String saveNews(@Valid @ModelAttribute News news, BindingResult result) { if (result.hasErrors()) { return "editNews"; } newsService.save(news); return "redirect:/news/news"; } @GetMapping("deleteNews/{newsId}") @Secured({UserRoleConstants.ADMIN}) public String delete(@PathVariable(value = "newsId") Integer id) { newsService.delete(id); return "redirect:/news/news"; } }