Compare commits

...

29 Commits

Author SHA1 Message Date
maxnes3
f4ba1554a2 MVC сделано 2023-05-25 13:12:43 +04:00
maxnes3
8044b8798c Надо добавить защиту 2023-05-25 03:00:43 +04:00
maxnes3
508954b902 Ужас 2023-05-25 01:50:41 +04:00
maxnes3
9df9926503 готово 2023-05-15 22:05:28 +04:00
maxnes3
72128f189c осталась небольшая часть 2023-05-15 20:16:46 +04:00
maxnes3
d14bf5334f Всё 2023-05-15 19:10:49 +04:00
maxnes3
0e51a0e3d6 Merge branch 'LabWork_04' into LabWork_05 2023-05-15 19:08:30 +04:00
maxnes3
0ba3312dae Сдал 2023-05-15 19:06:57 +04:00
maxnes3
cb2828e0a9 Лаба готова 2023-05-14 19:58:26 +04:00
maxnes3
46732e4a2a Начал ветку 2023-05-14 15:25:43 +04:00
maxnes3
b7efb56646 Кроме map 2023-05-13 20:54:03 +04:00
maxnes3
3a9239b77e Почти всё, ура 2023-05-12 19:23:50 +04:00
maxnes3
fa6f53bd8a Добавил кал 2023-05-12 13:17:47 +04:00
maxnes3
059729f986 работает Артём говноед и Коля тоже 2023-05-11 21:56:05 +04:00
maxnes3
c8e62cbc4f BackEnd написан, но не факт, что работает 2023-05-11 21:27:57 +04:00
maxnes3
f7ad06d262 Сдал 2023-04-18 11:31:48 +04:00
maxnes3
29b448f959 Доп задания сделаны 2023-04-16 18:18:56 +04:00
maxnes3
10ba7def55 сущности готовы 2023-03-20 15:09:57 +04:00
maxnes3
402b25c5cc улучшил 2023-03-20 13:38:43 +04:00
maxnes3
2855793c7b big-ass tests final 2023-03-20 00:40:30 +04:00
maxnes3
3dee9b728b big-ass tests2 2023-03-20 00:39:31 +04:00
maxnes3
0b8348bdbc big-ass tests 2023-03-20 00:05:11 +04:00
maxnes3
309e915e7b big-ass changes 2023-03-18 22:56:06 +04:00
maxnes3
f3f31c1a03 tests complete 2023-02-21 12:42:12 +04:00
maxnes3
51b4b1b53e need to add tests 2023-02-20 16:38:27 +04:00
maxnes3
04f358067f done 2023-02-19 23:51:57 +04:00
maxnes3
4fb650e3d1 add frontend 2023-02-19 21:44:05 +04:00
Макс Бондаренко
673233ea88 labwork done 2023-02-06 21:36:17 +04:00
Макс Бондаренко
02eae37b14 4 fetch 2023-02-06 15:07:27 +04:00
79 changed files with 10282 additions and 4 deletions

View File

@ -1,6 +1,6 @@
plugins { plugins {
id 'java' id 'java'
id 'org.springframework.boot' version '2.7.8' id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.0.15.RELEASE' id 'io.spring.dependency-management' version '1.0.15.RELEASE'
} }
@ -13,8 +13,24 @@ repositories {
} }
dependencies { dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.webjars:jquery:3.6.0'
implementation 'com.h2database:h2:2.1.210'
implementation 'jakarta.validation:jakarta.validation-api:3.0.0'
implementation 'org.hibernate.validator:hibernate-validator:7.0.1.Final'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }

BIN
data.mv.db Normal file

Binary file not shown.

1406
data.trace.db Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,8 +2,10 @@ package ru.ip.labworks.labworks;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @SpringBootApplication
@RestController
public class LabworksApplication { public class LabworksApplication {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -0,0 +1,65 @@
/*package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.AuthorService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/author")
public class AuthorController {
private final AuthorService authorService;
public AuthorController(AuthorService authorService){
this.authorService = authorService;
}
@GetMapping("/{id}")
public AuthorDto getAuthor(@PathVariable Long id){
return new AuthorDto(authorService.findAuthor(id));
}
@GetMapping
public List<AuthorDto> getAuthors(){
return authorService.findAllAuthors().stream().map(AuthorDto::new).toList();
}
@GetMapping("/{id}/books")
public List<BookDto> getAuthorBooks(@PathVariable Long id){
return authorService.authorBooks(id).stream().map(BookDto::new).toList();
}
@PostMapping
public AuthorDto createAuthor(@RequestBody @Valid AuthorDto authorDto) throws IOException {
return new AuthorDto(authorService.addAuthor(authorDto));
}
@PutMapping("/{id}")
public AuthorDto updateAuthor(@PathVariable Long id, @RequestBody @Valid AuthorDto authorDto){
return new AuthorDto(authorService.updateAuthor(id, authorDto));
}
@PostMapping("/{id}/Book/{bookId}")
public void addBook(@PathVariable Long id, @PathVariable Long bookId) {
authorService.addBookToAuthor(id, bookId);
}
@DeleteMapping("/{id}/Book/{bookId}")
public void removeBook(@PathVariable Long id, @PathVariable Long bookId)
{
authorService.removeBookFromAuthor(id, bookId);
}
@DeleteMapping("/{id}")
public void deleteAuthor(@PathVariable Long id){
authorService.deleteAuthor(id);
}
@GetMapping("/books")
public Map<String, List<String>> getAuthorsBooks(){
return authorService.AllAuthorsAndBooks();
}
}*/

View File

@ -0,0 +1,30 @@
package ru.ip.labworks.labworks.bookshop.controller;
import ru.ip.labworks.labworks.bookshop.model.Author;
import java.nio.charset.StandardCharsets;
public class AuthorDto {
private Long id;
private String firstname;
private String lastname;
private String photo;
public AuthorDto(){}
public AuthorDto(Author author){
id = author.getId();
firstname = author.getFirstnameName();
lastname = author.getLastName();
photo = new String(author.getPhoto(), StandardCharsets.UTF_8);
}
public Long getId(){return id;}
public String getFirstname(){return firstname;}
public String getLastname(){return lastname;}
public String getPhoto(){return photo;}
public void setId(Long id){this.id = id;}
public void setFirstname(String firstname){this.firstname = firstname;}
public void setLastname(String lastname){this.lastname = lastname;}
public void setPhoto(String photo){this.photo = photo;}
}

View File

@ -0,0 +1,114 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.ip.labworks.labworks.bookshop.service.AuthorService;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
@Controller
@RequestMapping("/author")
public class AuthorMvcController {
private final AuthorService authorService;
private final BookService bookService;
private final UserService userService;
public AuthorMvcController(UserService userService, AuthorService authorService, BookService bookService)
{
this.authorService = authorService;
this.bookService = bookService;
this.userService = userService;
}
@GetMapping
public String getAuthors(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("authors",
authorService.findAllAuthors().stream()
.map(AuthorDto::new)
.toList());
return "authors";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String updateAuthor(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("authorDto", new AuthorDto());
} else {
model.addAttribute("authorDto", id);
model.addAttribute("authorDto", new AuthorDto(authorService.findAuthor(id)));
}
return "author-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveAuthor(@PathVariable(required = false) Long id,
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
@ModelAttribute("authorDto") AuthorDto authorDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "author-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
authorDto.setPhoto("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
if (id == null || id <= 0) {
return "redirect:/author/" + authorService.addAuthor(authorDto, userId).getId().toString() + "/books";
} else {
authorService.updateAuthor(id, authorDto, userId);
}
return "redirect:/author";
}
@PostMapping("/delete/{id}")
public String deleteAuthor(@PathVariable Long id, Principal principal) {
authorService.deleteAuthor(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/author";
}
@GetMapping("/{id}/books")
public String getAuthorBooks(@PathVariable Long id, Model model){
model.addAttribute("author",
new AuthorDto(authorService.findAuthor(id)));
model.addAttribute("authorbooks",
authorService.authorBooks(id).stream()
.map(BookDto::new)
.toList());
model.addAttribute("books",
bookService.findAllBooks().stream()
.map(BookDto::new)
.toList());
return "author-mtm";
}
@PostMapping("/{id}/books")
public String addBookToAuthor(@PathVariable Long id, @RequestParam(value = "bookid") Long bookid, Principal principal){
authorService.addBookToAuthor(id, bookid, userService.findByLogin(principal.getName()).getId());
return "redirect:/author/" + id.toString() + "/books";
}
@PostMapping("/{id}/books/{bookid}")
public String removeBookFromAuthor(@PathVariable Long id, @PathVariable Long bookid, Principal principal){
authorService.removeBookFromAuthor(id, bookid, userService.findByLogin(principal.getName()).getId());
return "redirect:/author/" + id.toString() + "/books";
}
@GetMapping("/books")
private String getAllAuthorsBooks(Model model){
model.addAttribute("authorsbooks",
authorService.AllAuthorsAndBooks());
return "all-authors-books";
}
}

View File

@ -0,0 +1,61 @@
/*
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/book")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService){
this.bookService = bookService;
}
@GetMapping("/{id}")
public BookDto getBook(@PathVariable Long id){
return new BookDto(bookService.findBook(id));
}
@GetMapping
public List<BookDto> getBooks(){
return bookService.findAllBooks().stream().map(BookDto::new).toList();
}
@GetMapping("/{id}/genres")
public List<GenreDto> getBookGenres(@PathVariable Long id){
return bookService.bookGenres(id).stream().map(GenreDto::new).toList();
}
@PostMapping
public BookDto createBook(@RequestBody @Valid BookDto bookDto) throws IOException {
return new BookDto(bookService.addBook(bookDto));
}
@PutMapping("/{id}")
public BookDto updateBook(@PathVariable Long id, @RequestBody @Valid BookDto bookDto){
return new BookDto(bookService.updateBook(id, bookDto));
}
@PostMapping("/{id}/Genre/{genreId}")
public void addGenre(@PathVariable Long id, @PathVariable Long genreId) {
bookService.addGenreToBook(id, genreId);
}
@DeleteMapping("/{id}/Genre/{genreId}")
public void removeGenre(@PathVariable Long id, @PathVariable Long genreId)
{
bookService.removeGenreFromBook(id, genreId);
}
@DeleteMapping("/{id}")
public void deleteBook(@PathVariable Long id){
bookService.deleteBook(id);
}
}
*/

View File

@ -0,0 +1,33 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ip.labworks.labworks.bookshop.model.Book;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class BookDto {
private Long id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date release;
private String cover;
public BookDto(){}
public BookDto(Book book){
id = book.getId();
name = book.getName();
release = book.getRelease();
cover = new String(book.getCover(), StandardCharsets.UTF_8);
}
public Long getId(){return id;}
public String getName(){return name;}
public Date getRelease(){return release;}
public String getCover(){return cover;}
public void setId(Long id){this.id = id;}
public void setName(String name){this.name = name;}
public void setRelease(Date release){this.release = release;}
public void setCover(String cover){this.cover = cover;}
}

View File

@ -0,0 +1,106 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
@Controller
@RequestMapping("/book")
public class BookMvcController {
private final BookService bookService;
private final GenreService genreService;
private final UserService userService;
public BookMvcController(BookService bookService, GenreService genreService, UserService userService){
this.bookService = bookService;
this.genreService = genreService;
this.userService = userService;
}
@GetMapping
public String getBooks(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("books",
bookService.findAllBooks().stream()
.map(BookDto::new)
.toList());
return "books";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String updateBook(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("bookDto", new BookDto());
} else {
model.addAttribute("bookDto", id);
model.addAttribute("bookDto", new BookDto(bookService.findBook(id)));
}
return "book-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveBook(@PathVariable(required = false) Long id,
@RequestParam(value = "multipartFile") MultipartFile multipartFile,
@ModelAttribute("bookDto") BookDto bookDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "book-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
bookDto.setCover("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
if (id == null || id <= 0) {
return "redirect:/book/" + bookService.addBook(bookDto, userId).getId().toString() + "/genres";
} else {
bookService.updateBook(id, bookDto, userId);
}
return "redirect:/book";
}
@PostMapping("/delete/{id}")
public String deleteBook(@PathVariable Long id, Principal principal) {
bookService.deleteBook(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/book";
}
@GetMapping("/{id}/genres")
public String getBookGenres(@PathVariable Long id, Model model){
model.addAttribute("book",
new BookDto(bookService.findBook(id)));
model.addAttribute("bookgenres",
bookService.bookGenres(id).stream()
.map(GenreDto::new)
.toList());
model.addAttribute("genres",
genreService.findAllGenres().stream()
.map(GenreDto::new)
.toList());
return "book-mtm";
}
@PostMapping("/{id}/genres")
public String addGenreToBook(@PathVariable Long id, @RequestParam(value = "genreid") Long genreid, Principal principal){
bookService.addGenreToBook(id, genreid, userService.findByLogin(principal.getName()).getId());
return "redirect:/book/" + id.toString() + "/genres";
}
@PostMapping("/{id}/genres/{genreid}")
public String removeGenreFromBook(@PathVariable Long id, @PathVariable Long genreid, Principal principal){
bookService.removeGenreFromBook(id, genreid, userService.findByLogin(principal.getName()).getId());
return "redirect:/book/" + id.toString() + "/genres";
}
}

View File

@ -0,0 +1,43 @@
/*package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.configuration.WebConfiguration;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/genre")
public class GenreController {
private final GenreService genreService;
public GenreController(GenreService genreService){
this.genreService = genreService;
}
@GetMapping("/{id}")
public GenreDto getGenre(@PathVariable Long id){
return new GenreDto(genreService.findGenre(id));
}
@GetMapping
public List<GenreDto> getGenres(){
return genreService.findAllGenres().stream().map(GenreDto::new).toList();
}
@PostMapping
public GenreDto createGenre(@RequestBody @Valid GenreDto genreDto) throws IOException {
return new GenreDto(genreService.addGenre(genreDto));
}
@PutMapping("/{id}")
public GenreDto updateGenre(@PathVariable Long id, @RequestBody @Valid GenreDto genreDto){
return new GenreDto(genreService.updateGenre(id, genreDto));
}
@DeleteMapping("/{id}")
public void deleteGenre(@PathVariable Long id){
genreService.deleteGenre(id);
}
}*/

View File

@ -0,0 +1,20 @@
package ru.ip.labworks.labworks.bookshop.controller;
import ru.ip.labworks.labworks.bookshop.model.Genre;
public class GenreDto {
private Long id;
private String name;
public GenreDto(){}
public GenreDto(Genre genre){
id = genre.getId();
name = genre.getName();
}
public Long getId(){return id;}
public String getName(){return name;}
public void setId(Long id){this.id = id;}
public void setName(String name){this.name = name;}
}

View File

@ -0,0 +1,72 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.io.IOException;
import java.security.Principal;
@Controller
@RequestMapping("/genre")
public class GenreMvcController {
private final GenreService genreService;
private final UserService userService;
public GenreMvcController(GenreService genreService, UserService userService){
this.genreService = genreService;
this.userService = userService;
}
@GetMapping
public String getBooks(Model model, Authentication authentication) {
model.addAttribute("user", userService.findByLogin(authentication.getName()));
model.addAttribute("genres",
genreService.findAllGenres().stream()
.map(GenreDto::new)
.toList());
return "genres";
}
@GetMapping(value = {"/update", "/update/{id}"})
public String editBook(@PathVariable(required = false) Long id,
Model model, Principal principal) {
if (id == null || id <= 0) {
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId",userId);
model.addAttribute("genreDto", new GenreDto());
} else {
model.addAttribute("genreDto", id);
model.addAttribute("genreDto", new GenreDto(genreService.findGenre(id)));
}
return "genre-update";
}
@PostMapping(value = {"/", "/{id}"})
public String saveBook(@PathVariable(required = false) Long id,
@ModelAttribute("genreDto") GenreDto genreDto,
BindingResult bindingResult,
Model model, Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors",
bindingResult.getAllErrors());
return "genre-update";
}
Long userId = userService.findByLogin(principal.getName()).getId();
model.addAttribute("userId", userId);
if (id == null || id <= 0) {
genreService.addGenre(genreDto, userId);
} else {
genreService.updateGenre(id, genreDto, userId);
}
return "redirect:/genre";
}
@PostMapping("/delete/{id}")
public String deleteGenre(@PathVariable Long id, Principal principal) {
genreService.deleteGenre(id, userService.findByLogin(principal.getName()).getId());
return "redirect:/genre";
}
}

View File

@ -0,0 +1,28 @@
package ru.ip.labworks.labworks.bookshop.controller;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
public class UserDto {
private final long id;
private final String login;
private final UserRole role;
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
}

View File

@ -0,0 +1,41 @@
package ru.ip.labworks.labworks.bookshop.controller;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -0,0 +1,40 @@
package ru.ip.labworks.labworks.bookshop.controller;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignUpDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,48 @@
package ru.ip.labworks.labworks.bookshop.controller;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
@Controller
@RequestMapping(UserSignUpMvcController.SIGNUP_URL)
public class UserSignUpMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignUpMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("UserDTO", new UserSignUpDTO());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("UserDTO") @Valid UserSignUpDTO userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -0,0 +1,88 @@
package ru.ip.labworks.labworks.bookshop.model;
import jakarta.persistence.*;
import ru.ip.labworks.labworks.bookshop.controller.AuthorDto;
import java.util.*;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
@Lob
private byte[] photo;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "authors_books",
joinColumns = @JoinColumn(name = "author_fk"),
inverseJoinColumns = @JoinColumn(name = "book_fk"))
private List<Book> books;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Author(){}
public Author(String firstname, String lastname, byte[] photo){
this.firstname = firstname;
this.lastname = lastname;
this.photo = photo;
}
public Author(AuthorDto authorDto){
this.firstname = authorDto.getFirstname();
this.lastname = authorDto.getLastname();
this.photo = authorDto.getPhoto().getBytes();
}
public Long getId(){return id;}
public String getFirstnameName(){return firstname;}
public void setFirstnameName(String firstname){this.firstname = firstname;}
public String getLastName(){return lastname;}
public void setLastName(String lastname){this.lastname = lastname;}
public byte[] getPhoto(){return photo;}
public void setPhoto(byte[] photo){this.photo = photo;}
public List<Book> getBooks(){return books;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Author author = (Author) o;
return Objects.equals(id, author.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Author{" +
"id=" + id +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
'}';
}
public void addBook(Book book) {
books.add(book);
}
public void removeBook(Book book) {
books.remove(book);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,94 @@
package ru.ip.labworks.labworks.bookshop.model;
import jakarta.persistence.*;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import ru.ip.labworks.labworks.bookshop.controller.BookDto;
import java.util.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Date release;
@Lob
private byte[] cover;
@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name = "books_genres",
joinColumns = @JoinColumn(name = "book_fk"),
inverseJoinColumns = @JoinColumn(name = "genre_fk"))
private List<Genre> genres;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "books")
private List<Author> authors;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Book(){}
public Book(String name,Date release, byte[] cover){
this.name = name;
this.release = release;
this.cover = cover;
}
public Book(BookDto bookDto){
this.name = bookDto.getName();
this.release = bookDto.getRelease();
this.cover = bookDto.getCover().getBytes();
}
public Long getId(){return id;}
public String getName(){return name;}
public void setName(String name){this.name = name;}
public Date getRelease(){return release;}
public void setRelease(Date release){this.release = release;}
public byte[] getCover(){return cover;}
public void setCover(byte[] cover){this.cover = cover;}
public List<Genre> getGenres(){return genres;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", release='" + release + '\'' +
'}';
}
public void addGenre(Genre genre) {
genres.add(genre);
}
public void removeGenre(Genre genre) {
genres.remove(genre);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,59 @@
package ru.ip.labworks.labworks.bookshop.model;
import jakarta.persistence.*;
import ru.ip.labworks.labworks.bookshop.controller.GenreDto;
import java.util.*;
@Entity
public class Genre {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Genre(){}
public Genre(String name){
this.name = name;
}
public Genre(GenreDto genreDto){
this.name = genreDto.getName();
}
public Long getId(){return id;}
public String getName(){return name;}
public void setName(String name){this.name = name;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Genre genre = (Genre) o;
return Objects.equals(id, genre.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Genre{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,83 @@
package ru.ip.labworks.labworks.bookshop.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
}
}

View File

@ -0,0 +1,20 @@
package ru.ip.labworks.labworks.bookshop.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,15 @@
package ru.ip.labworks.labworks.bookshop.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ip.labworks.labworks.bookshop.model.Author;
import java.util.List;
public interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select a.lastname as author, b.name as book " +
"from Author a " +
"join a.books b " +
"group by a.id, a.lastname, b.name")
List<Object[]> getAuthorsWithBooks();
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labworks.labworks.bookshop.model.Book;
public interface BookRepository extends JpaRepository<Book, Long> {
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labworks.labworks.bookshop.model.Genre;
public interface GenreRepository extends JpaRepository<Genre, Long> {
}

View File

@ -0,0 +1,8 @@
package ru.ip.labworks.labworks.bookshop.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labworks.labworks.bookshop.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.service;
public class AuthorNotFoundException extends RuntimeException{
public AuthorNotFoundException(Long id) {
super(String.format("Author with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,155 @@
package ru.ip.labworks.labworks.bookshop.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ip.labworks.labworks.bookshop.controller.AuthorDto;
import ru.ip.labworks.labworks.bookshop.model.*;
import ru.ip.labworks.labworks.bookshop.repository.AuthorRepository;
import ru.ip.labworks.labworks.util.validation.ValidatorUtil;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class AuthorService {
@Autowired
private final AuthorRepository authorRepository;
@Autowired
private final BookService bookService;
@Autowired
private final ValidatorUtil validatorUtil;
@Autowired
private final UserService userService;
public AuthorService(AuthorRepository authorRepository, BookService bookService, ValidatorUtil validatorUtil, UserService userService){
this.authorRepository = authorRepository;
this.bookService = bookService;
this.validatorUtil = validatorUtil;
this.userService = userService;
}
@Transactional
public Author addAuthor(String firstname, String lastname, File photo){
if (!StringUtils.hasText(firstname) || !StringUtils.hasText(lastname)) {
throw new IllegalArgumentException("Author firstname and lastname is null or empty");
}
final Author author = new Author(firstname, lastname, ImageHelper.ImageToByte(photo));
validatorUtil.validate(author);
return authorRepository.save(author);
}
@Transactional
public Author addAuthor(AuthorDto authorDto, Long userId) throws IOException {
User currentUser = userService.findUser(userId);
final Author author = new Author(authorDto);
author.setUser(currentUser);
validatorUtil.validate(author);
return authorRepository.save(author);
}
@Transactional
public void saveAuthor(Author author){
authorRepository.save(author);
}
@Transactional(readOnly = true)
public Author findAuthor(Long id) {
final Optional<Author> author = authorRepository.findById(id);
return author.orElseThrow(() -> new AuthorNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Author> findAllAuthors() {
return authorRepository.findAll();
}
@Transactional(readOnly = true)
public List<Book> authorBooks(Long id){
return authorRepository.findById(id).get().getBooks();
}
@Transactional
public Author updateAuthor(Long id, String firstname, String lastname, File photo){
if (!StringUtils.hasText(firstname) || !StringUtils.hasText(lastname)) {
throw new IllegalArgumentException("Author firstname and lastname is null or empty");
}
final Author currentAuthor = findAuthor(id);
currentAuthor.setFirstnameName(firstname);
currentAuthor.setLastName(lastname);
currentAuthor.setPhoto(ImageHelper.ImageToByte(photo));
validatorUtil.validate(currentAuthor);
return authorRepository.save(currentAuthor);
}
@Transactional
public Author updateAuthor(Long id, AuthorDto authorDto, Long userId){
User currentUser = userService.findUser(userId);
final Author currentAuthor = findAuthor(id);
if(currentUser.getId() != currentAuthor.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null;
}
currentAuthor.setFirstnameName(authorDto.getFirstname());
currentAuthor.setLastName(authorDto.getLastname());
currentAuthor.setPhoto(authorDto.getPhoto().getBytes());
validatorUtil.validate(currentAuthor);
return authorRepository.save(currentAuthor);
}
@Transactional
public void deleteAuthor(Long id, Long userId) {
User currentUser = userService.findUser(userId);
final Author currentAuthor = findAuthor(id);
if(currentUser.getId() != currentAuthor.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
authorRepository.deleteById(id);
}
@Transactional
public void deleteAllAuthors() {
authorRepository.deleteAll();
}
@Transactional
public void addBookToAuthor(Long id, Long bookId, Long userId){
User currentUser = userService.findUser(userId);
Optional<Author> author = authorRepository.findById(id);
if(currentUser.getId() != author.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if (author.isPresent() && !author.get().getBooks().contains(bookService.findBook(bookId))){
author.get().addBook(bookService.findBook(bookId));
}
authorRepository.save(author.get());
}
@Transactional
public void removeBookFromAuthor(Long id, Long bookId, Long userId){
User currentUser = userService.findUser(userId);
Optional<Author> author = authorRepository.findById(id);
if(currentUser.getId() != author.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if(author.isPresent() && author.get().getBooks().contains(bookService.findBook(bookId))){
author.get().removeBook(bookService.findBook(bookId));
}
authorRepository.save(author.get());
}
@Transactional
public Map<String, List<String>> AllAuthorsAndBooks(){
return authorRepository.getAuthorsWithBooks().stream()
.collect(
Collectors.groupingBy(
o -> (String) o[0],
Collectors.mapping( o -> (String) o[1], Collectors.toList() )
)
);
}
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.service;
public class BookNotFoundException extends RuntimeException{
public BookNotFoundException(Long id) {
super(String.format("Book with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,152 @@
package ru.ip.labworks.labworks.bookshop.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ip.labworks.labworks.bookshop.controller.BookDto;
import ru.ip.labworks.labworks.bookshop.model.Book;
import ru.ip.labworks.labworks.bookshop.model.Genre;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.repository.BookRepository;
import ru.ip.labworks.labworks.util.validation.ValidatorUtil;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
@Service
public class BookService {
@Autowired
private final BookRepository bookRepository;
@Autowired
private final ValidatorUtil validatorUtil;
@Autowired
private final GenreService genreService;
@Autowired
private final UserService userService;
public BookService(BookRepository bookRepository, ValidatorUtil validatorUtil, GenreService genreService, UserService userService){
this.bookRepository = bookRepository;
this.validatorUtil = validatorUtil;
this.genreService = genreService;
this.userService = userService;
}
private Date ParseToDate(String s){
Date release;
try {
release = new SimpleDateFormat("dd.MM.yyyy").parse(s);
}
catch (ParseException ex){
return null;
}
return release;
}
@Transactional
public Book addBook(String name, String release, File cover){
if (!StringUtils.hasText(name) || !StringUtils.hasText(release)) {
throw new IllegalArgumentException("Book name and release is null or empty");
}
final Book book = new Book(name, ParseToDate(release), ImageHelper.ImageToByte(cover));
validatorUtil.validate(book);
return bookRepository.save(book);
}
@Transactional
public Book addBook(BookDto bookDto, Long userId) throws IOException {
User currentUser = userService.findUser(userId);
final Book book = new Book(bookDto);
book.setUser(currentUser);
validatorUtil.validate(book);
return bookRepository.save(book);
}
@Transactional(readOnly = true)
public Book findBook(Long id) {
final Optional<Book> book = bookRepository.findById(id);
return book.orElseThrow(() -> new BookNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Book> findAllBooks() {
return bookRepository.findAll();
}
@Transactional(readOnly = true)
public List<Genre> bookGenres(Long id){
return bookRepository.findById(id).get().getGenres();
}
@Transactional
public Book updateBook(Long id, String name, String release, File cover) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(release)) {
throw new IllegalArgumentException("Book name and release is null or empty");
}
final Book currentBook = findBook(id);
currentBook.setName(name);
currentBook.setRelease(ParseToDate(release));
currentBook.setCover(ImageHelper.ImageToByte(cover));
validatorUtil.validate(currentBook);
return bookRepository.save(currentBook);
}
@Transactional
public Book updateBook(Long id, BookDto bookDto, Long userId){
User currentUser = userService.findUser(userId);
final Book currentBook = findBook(id);
if(currentUser.getId() != currentBook.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null;
}
currentBook.setName(bookDto.getName());
currentBook.setRelease(bookDto.getRelease());
currentBook.setCover(bookDto.getCover().getBytes());
validatorUtil.validate(currentBook);
return bookRepository.save(currentBook);
}
@Transactional
public void deleteBook(Long id, Long userId) {
User currentUser = userService.findUser(userId);
final Book currentBook = findBook(id);
if(currentUser.getId() != currentBook.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
bookRepository.deleteById(id);
}
@Transactional
public void deleteAllBooks() {
bookRepository.deleteAll();
}
@Transactional
public void addGenreToBook(Long id, Long genreId, Long userId){
User currentUser = userService.findUser(userId);
Optional<Book> book = bookRepository.findById(id);
if(currentUser.getId() != book.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if (book.isPresent() && !book.get().getGenres().contains(genreService.findGenre(genreId))){
book.get().addGenre(genreService.findGenre(genreId));
}
bookRepository.save(book.get());
}
@Transactional
public void removeGenreFromBook(Long id, Long genreId, Long userId){
User currentUser = userService.findUser(userId);
Optional<Book> book = bookRepository.findById(id);
if(currentUser.getId() != book.get().getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
if(book.isPresent() && book.get().getGenres().contains(genreService.findGenre(genreId))){
book.get().removeGenre(genreService.findGenre(genreId));
}
bookRepository.save(book.get());
}
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.service;
public class GenreNotFoundException extends RuntimeException{
public GenreNotFoundException(Long id) {
super(String.format("Genre with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,96 @@
package ru.ip.labworks.labworks.bookshop.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ip.labworks.labworks.bookshop.controller.GenreDto;
import ru.ip.labworks.labworks.bookshop.model.Genre;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.repository.GenreRepository;
import ru.ip.labworks.labworks.util.validation.ValidatorUtil;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
@Service
public class GenreService {
@Autowired
private final GenreRepository genreRepository;
@Autowired
private final ValidatorUtil validatorUtil;
@Autowired
private final UserService userService;
public GenreService(GenreRepository genreRepository, ValidatorUtil validatorUtil, UserService userService){
this.genreRepository = genreRepository;
this.validatorUtil = validatorUtil;
this.userService = userService;
}
@Transactional
public Genre addGenre(String name){
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Genre name is null or empty");
}
final Genre genre = new Genre(name);
return genreRepository.save(genre);
}
@Transactional
public Genre addGenre(GenreDto genreDto, Long userId) throws IOException {
User currentUser = userService.findUser(userId);
final Genre genre = new Genre(genreDto);
genre.setUser(currentUser);
validatorUtil.validate(genre);
return genreRepository.save(genre);
}
@Transactional(readOnly = true)
public Genre findGenre(Long id) {
final Optional<Genre> genre = genreRepository.findById(id);
return genre.orElseThrow(() -> new BookNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Genre> findAllGenres() {
return genreRepository.findAll();
}
@Transactional
public Genre updateGenre(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Genre name is null or empty");
}
final Genre currentGenre = findGenre(id);
currentGenre.setName(name);
return genreRepository.save(currentGenre);
}
@Transactional
public Genre updateGenre(Long id, GenreDto genreDto, Long userId){
User currentUser = userService.findUser(userId);
final Genre currentGenre = findGenre(id);
if(currentUser.getId() != currentGenre.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return null;
}
currentGenre.setName(genreDto.getName());
return genreRepository.save(currentGenre);
}
@Transactional
public void deleteGenre(Long id, Long userId) {
User currentUser = userService.findUser(userId);
final Genre currentGenre = findGenre(id);
if(currentUser.getId() != currentGenre.getUser().getId() && currentUser.getRole() != UserRole.ADMIN){
return;
}
genreRepository.deleteById(id);
}
@Transactional
public void deleteAllGenres() {
genreRepository.deleteAll();
}
}

View File

@ -0,0 +1,21 @@
package ru.ip.labworks.labworks.bookshop.service;
//import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
public class ImageHelper {
public static byte[] ImageToByte(File image){
try {
/*BufferedImage bufferedImage = ImageIO.read(image);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();*/
}
catch (Exception ex) {
return null;
}
return null;
}
}

View File

@ -0,0 +1,7 @@
package ru.ip.labworks.labworks.bookshop.service;
public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,66 @@
package ru.ip.labworks.labworks.bookshop.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ip.labworks.labworks.bookshop.model.User;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.repository.UserRepository;
import jakarta.validation.ValidationException;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
final User user = new User(login, passwordEncoder.encode(password), role);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
}

View File

@ -0,0 +1,14 @@
package ru.ip.labworks.labworks.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,68 @@
package ru.ip.labworks.labworks.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import ru.ip.labworks.labworks.bookshop.controller.UserSignUpMvcController;
import ru.ip.labworks.labworks.bookshop.model.UserRole;
import ru.ip.labworks.labworks.bookshop.service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.defaultSuccessUrl("/author", true)
.and()
.logout().permitAll();
return http.userDetailsService(userService).build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**");
}
}

View File

@ -0,0 +1,21 @@
package ru.ip.labworks.labworks.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,37 @@
package ru.ip.labworks.labworks.util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import ru.ip.labworks.labworks.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
public class AdviceController {
@ExceptionHandler({
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,9 @@
package ru.ip.labworks.labworks.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package ru.ip.labworks.labworks.util.validation;
import org.springframework.stereotype.Component;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1 +1,11 @@
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,7 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).

View File

@ -0,0 +1,19 @@
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<title>Data Type Calculator</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
{
"name": "spa-vue",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"fake-server": "json-server --watch data.json -p 8079",
"start": "npm-run-all --parallel dev fake-server",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.2.41",
"vue-router": "^4.1.6",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"vite": "^3.2.3",
"@vitejs/plugin-vue": "^3.2.0",
"npm-run-all": "^4.1.5",
"json-server": "^0.17.1"
}
}

View File

@ -0,0 +1,9 @@
<script setup>
</script>
<template>
<router-view>
</router-view>
</template>

View File

@ -0,0 +1,17 @@
<template>
<footer class="container pt-4 my-md-5 pt-md-5 text-center border-top">
<div class="row">
<div class="col-12 col-md">
<h5 class=""><strong>End</strong></h5>
</div>
</div>
</footer>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>

View File

@ -0,0 +1,21 @@
<template>
<header class="fixed-top">
<nav class="navbar navbar-expand-lg bg-success" data-bs-theme="dark">
<div class="container">
<a class="navbar-brand" href="#">
<strong>{ OBS } Online Book Service</strong>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="/authors">Authors</a>
<a class="nav-link active" href="/books">Books</a>
<a class="nav-link active" href="/genres">Genres</a>
</div>
</div>
</div>
</nav>
</header>
</template>

View File

@ -0,0 +1,7 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router/router.js"
const app = createApp(App)
app.use(router).mount("#app");

View File

@ -0,0 +1,8 @@
export default class Author{
constructor(data){
this.id = data?.id;
this.firstname = data?.firstname;
this.lastname = data?.lastname;
this.photo = data?.photo;
}
}

View File

@ -0,0 +1,8 @@
export default class Book{
constructor(data){
this.id = data?.id;
this.name = data?.name;
this.release = data?.release;
this.cover = data?.cover;
}
}

View File

@ -0,0 +1,6 @@
export default class Genre{
constructor(data){
this.id = data?.id;
this.name = data?.name;
}
}

View File

@ -0,0 +1,300 @@
<script>
import 'axios';
import axios from "axios";
import Header from '../components/Header.vue';
import Footer from '../components/Footer.vue';
import Author from '../models/Author';
export default{
components:{
Header,
Footer
},
created(){
this.getAuthors();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data(){
return{
authors: [],
authorBooks: [],
allBooks: [],
mapAuthorsBooks: new Object(),
bookid: 0,
URL: "http://localhost:8080/",
author: new Author(),
}
},
methods:{
getAuthors(){
axios.get(this.URL + "author")
.then(response => {
this.authors = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
async addAuthor(){
await this.toBase64();
console.log(this.author);
axios.post(this.URL + "author", this.author)
.then((response) => {
this.getAuthors();
this.closeModal();
this.author = response.data;
this.openManyToManyModal();
})
.catch(error => {
console.log(error);
});
},
deleteAuthor(id){
axios.delete(this.URL + `author/${id}`)
.then(() =>{
this.getAuthors();
})
},
async updateAuthor(author){
if(author.photo === undefined) await this.toBase64();
axios.put(this.URL + `author/${author.id}`, this.author)
.then(() =>{
this.getAuthors();
})
this.closeModal();
},
openModal() {
document.getElementById("editModal").style.display = "block";
},
openManyToManyModal(){
this.getAuthorBooks();
this.getAllBooks();
document.getElementById("manyToManyModal").style.display = "block";
},
openAuthorsBooksModal(){
this.getAuthorsBooks();
document.getElementById("authorsBooksModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
closeManyToManyModal() {
document.getElementById("manyToManyModal").style.display = "none";
},
closeAuthorsBooksModal(){
document.getElementById("authorsBooksModal").style.display = "none";
},
async toBase64(){
var file = document.getElementById("photo").files[0];
var reader = new FileReader();
var phototemp = this.author;
reader.readAsDataURL(file);
await new Promise((resolve, reject) => {
reader.onload = function () {
phototemp.photo = reader.result;
console.log(phototemp);
resolve();
};
reader.onerror = function (error) {
console.log('Error: ', error);
reject(error);
};
});
},
getAllBooks(){
axios.get(this.URL + "book")
.then(response => {
this.allBooks = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getAuthorBooks(){
axios.get(this.URL + `author/${this.author.id}/books`)
.then(response => {
this.authorBooks = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addBook(){
console.log(this.bookid + " " + this.author.id);
axios.post(this.URL + `author/${this.author.id}/Book/${this.bookid}`)
.then(() => {
this.getAuthorBooks();
})
.catch(error => {
console.log(error);
});
},
removeBook(id){
axios.delete(this.URL + `author/${this.author.id}/Book/${id}`)
.then(() =>{
this.getAuthorBooks();
})
},
getAuthorsBooks(){
axios.get(this.URL + "author/books")
.then(response => {
console.log(response.data);
this.mapAuthorsBooks = response.data;
console.log(this.mapAuthorsBooks);
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
<template>
<Header></Header>
<main style="margin-top: 50pt;">
<div class="container mt-4">
<h1 class="text-center mb-4">Author Table:</h1>
<button class="btn btn-success mr-2" @click="openModal(); author = new Object(); author.status = `create`">Добавить</button>
<button class="btn btn-primary mr-2" @click="openAuthorsBooksModal();">Посмотреть весь список</button>
<table class="table table-striped">
<thead>
<tr>
<th>Имя:</th>
<th>Фамилия:</th>
<th>Фото:</th>
<th>Реадактировать запись:</th>
</tr>
</thead>
<tbody>
<tr v-for="aut in authors" :key="aut.id">
<td>{{ aut.firstname }}</td>
<td>{{ aut.lastname }}</td>
<td><img :src="aut.photo" class="img-thumbnail mw-50 mh-50"/></td>
<td>
<button class="btn btn-warning" @click="openModal(); author = Object.assign({}, aut); author.status = `edit`">Изменить</button>
<button class="btn btn-danger" @click="deleteAuthor(aut.id)">Удалить</button>
<button class="btn btn-primary" @click="author = aut; openManyToManyModal()">Книги</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Author</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="firstname">Имя:</label>
<input type="text" class="form-control" id="firstname" name="firstname" v-model="author.firstname">
<label for="lastname">Фамилия:</label>
<input type="text" class="form-control" id="lastname" name="lastname" v-model="author.lastname">
<label for="photo">Фотография:</label>
<input class="form-control" type="file" id="photo" name="photo" @change="toBase64()">
<img :src="author.photo" class="img-thumbnail"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-success" v-if="author.status === `create`"
@click="addAuthor">Создать</button>
<button type="button" class="btn btn-primary" v-else
@click="updateAuthor(author)">Сохранить</button>
</div>
</div>
</div>
</div>
<div class="modal" tabindex="-1" id="manyToManyModal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Books to Author</h5>
</div>
<div class="modal-body">
<form>
<table class="table table-striped">
<thead>
<tr>
<th>Название:</th>
<th>Дата релиза:</th>
<th>Обложка:</th>
<th>Реадактировать запись:</th>
</tr>
</thead>
<tbody>
<tr v-for="bk in authorBooks" :key="bk.id">
<td>{{ bk.name }}</td>
<td>{{ bk.release }}</td>
<td><img :src="bk.cover" class="img-thumbnail mw-50 mh-50"/></td>
<td>
<button class="btn btn-primary" type="button" @click="removeBook(bk.id)">Удалить</button>
</td>
</tr>
</tbody>
</table>
<div class="input-group mb-3">
<select class="form-select" v-model="bookid">
<option v-for="sbk in allBooks" :key="sbk.id" :value="sbk.id">{{ sbk.name }}</option>
</select>
<button class="btn btn-outline-secondary" type="button" @click="addBook()">Добавить</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeManyToManyModal()">Закрыть</button>
</div>
</div>
</div>
</div>
<div class="modal" tabindex="-1" id="authorsBooksModal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">All Books of Authors</h5>
</div>
<div class="modal-body">
<form>
<table class="table table-striped">
<thead>
<tr>
<th>Фамилия автора:</th>
<th>Название книг:</th>
</tr>
</thead>
<tbody>
<tr v-for="[key, value] in Object.entries(mapAuthorsBooks)" :key="key">
<td>{{ key }}</td>
<td>
<ul>
<li v-for="book in value" :key="book">{{ book }}</li>
</ul>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeAuthorsBooksModal()">Закрыть</button>
</div>
</div>
</div>
</div>
<Footer></Footer>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,241 @@
<script>
import 'axios';
import axios from "axios";
import Header from '../components/Header.vue';
import Footer from '../components/Footer.vue';
import Book from '../models/Book';
export default{
components:{
Header,
Footer
},
created(){
this.getBooks();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data(){
return{
books: [],
bookGenres: [],
allGenres: [],
genreid: 0,
URL: "http://localhost:8080/",
book: new Book(),
}
},
methods:{
getBooks(){
axios.get(this.URL + "book")
.then(response => {
this.books = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
async addBook(){
await this.toBase64();
console.log(this.book);
axios.post(this.URL + "book", this.book)
.then((response) => {
this.getBooks();
this.closeModal();
this.book = response.data;
this.openManyToManyModal();
})
.catch(error => {
console.log(error);
});
},
deleteBook(id){
axios.delete(this.URL + `book/${id}`)
.then(() =>{
this.getBooks();
})
},
async updateBook(book){
if(book.cover === undefined) await this.toBase64();
axios.put(this.URL + `book/${book.id}`, this.book)
.then(() =>{
this.getBooks();
})
this.closeModal();
},
openModal() {
document.getElementById("editModal").style.display = "block";
},
openManyToManyModal(){
this.getBookGenres();
this.getAllGenres();
document.getElementById("manyToManyModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
closeManyToManyModal() {
document.getElementById("manyToManyModal").style.display = "none";
},
async toBase64(){
var file = document.getElementById("cover").files[0];
var reader = new FileReader();
var phototemp = this.book;
reader.readAsDataURL(file);
await new Promise((resolve, reject) => {
reader.onload = function () {
phototemp.cover = reader.result;
console.log(phototemp);
resolve();
};
reader.onerror = function (error) {
console.log('Error: ', error);
reject(error);
};
});
},
getAllGenres(){
axios.get(this.URL + "genre")
.then(response => {
this.allGenres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getBookGenres(){
axios.get(this.URL + `book/${this.book.id}/genres`)
.then(response => {
this.bookGenres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addGenre(){
axios.post(this.URL + `book/${this.book.id}/Genre/${this.genreid}`)
.then(() => {
this.getBookGenres();
})
.catch(error => {
console.log(error);
});
},
removeGenre(id){
axios.delete(this.URL + `book/${this.book.id}/Genre/${id}`)
.then(() =>{
this.getBookGenres();
})
}
}
}
</script>
<template>
<Header></Header>
<main style="margin-top: 50pt;">
<div class="container mt-4">
<h1 class="text-center mb-4">Book Table:</h1>
<button class="btn btn-success mr-2" @click="openModal(); book = new Object(); book.status = `create`">Добавить</button>
<table class="table table-striped">
<thead>
<tr>
<th>Название:</th>
<th>Дата релиза:</th>
<th>Обложка:</th>
<th>Реадактировать запись:</th>
</tr>
</thead>
<tbody>
<tr v-for="bk in books" :key="bk.id">
<td>{{ bk.name }}</td>
<td>{{ bk.release }}</td>
<td><img :src="bk.cover" class="img-thumbnail mw-50 mh-50"/></td>
<td>
<button class="btn btn-warning" @click="openModal(); book = Object.assign({},bk); book.status = `edit`">Изменить</button>
<button class="btn btn-danger" @click="deleteBook(bk.id)">Удалить</button>
<button class="btn btn-primary" @click="book = bk; openManyToManyModal()">Жанры</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Book</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input type="text" class="form-control" id="name" name="name" v-model="book.name">
<label for="release">Дата релиза:</label>
<input type="date" class="form-control" id="release" name="release" v-model="book.release">
<label for="cover">Обложка:</label>
<input class="form-control" type="file" id="cover" name="cover" @change="toBase64()">
<img :src="book.cover" class="img-thumbnail"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-success" v-if="book.status === `create`"
@click="addBook">Создать</button>
<button type="button" class="btn btn-primary" v-else
@click="updateBook(book)">Сохранить</button>
</div>
</div>
</div>
</div>
<div class="modal" tabindex="-1" id="manyToManyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Genres to Book</h5>
</div>
<div class="modal-body">
<form>
<table class="table table-striped">
<thead>
<tr>
<th>Название:</th>
<th>Реадактировать запись:</th>
</tr>
</thead>
<tbody>
<tr v-for="gen in bookGenres" :key="gen.id">
<td>{{ gen.name }}</td>
<td>
<button class="btn btn-primary" type="button" @click="removeGenre(gen.id)">Удалить</button>
</td>
</tr>
</tbody>
</table>
<div class="input-group mb-3">
<select class="form-select" v-model="genreid">
<option v-for="sgen in allGenres" :key="sgen.id" :value="sgen.id">{{ sgen.name }}</option>
</select>
<button class="btn btn-outline-secondary" type="button" @click="addGenre()">Добавить</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeManyToManyModal()">Закрыть</button>
</div>
</div>
</div>
</div>
<Footer></Footer>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,127 @@
<script>
import 'axios';
import axios from "axios";
import Header from '../components/Header.vue';
import Footer from '../components/Footer.vue';
import Genre from '../models/Genre';
export default{
components:{
Header,
Footer
},
created(){
this.getGenres();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data(){
return{
genres: [],
URL: "http://localhost:8080/",
genre: new Genre(),
}
},
methods:{
getGenres(){
axios.get(this.URL + "genre")
.then(response => {
this.genres = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addGenre(){
console.log(this.genre);
axios.post(this.URL + "genre", this.genre)
.then(() => {
this.getGenres();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteGenre(id){
axios.delete(this.URL + `genre/${id}`)
.then(() =>{
this.getGenres();
})
},
updateGenre(genre){
this.genre = genre;
axios.put(this.URL + `genre/${genre.id}`, this.genre)
.then(() =>{
this.getGenres();
})
this.closeModal();
},
openModal() {
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
}
}
}
</script>
<template>
<Header></Header>
<main style="margin-top: 50pt;">
<div class="container mt-4">
<h1 class="text-center mb-4">Genre Table:</h1>
<button class="btn btn-success mr-2" @click="openModal(); genre = new Object(); genre.status = `create`">Добавить</button>
<table class="table table-striped">
<thead>
<tr>
<th>Название:</th>
<th>Реадактировать запись:</th>
</tr>
</thead>
<tbody>
<tr v-for="gen in genres" :key="gen.id">
<td>{{ gen.name }}</td>
<td>
<button class="btn btn-warning" @click="openModal(); genre = Object.assign({},gen); genre.status = `edit`">Изменить</button>
<button class="btn btn-danger" @click="deleteGenre(gen.id)">Удалить</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Genre</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Название:</label>
<input type="text" class="form-control" id="name" name="name" v-model="genre.name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-success" v-if="genre.status === `create`"
@click="addGenre">Создать</button>
<button type="button" class="btn btn-primary" v-else
@click="updateGenre(genre)">Сохранить</button>
</div>
</div>
</div>
</div>
<Footer></Footer>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,41 @@
<script>
import Header from '../components/Header.vue'
import Footer from '../components/Footer.vue'
export default{
components:{
Header,
Footer
},
data(){
return {
action: "",
type: "",
str_1: "",
str_2: "",
result: ""
}
},
methods:{
GetRepuest(){
if (this.action.length == 0 || this.str_1.length == 0 || this.str_2.length == 0){
console.warn("Invalid input to fetch!");
}
console.log("http://localhost:8080/" + this.action + "?type=" + this.type + "&arg1=" + this.str_1 + "&arg2=" + this.str_2)
fetch("http://localhost:8080/" + this.action + "?type=" + this.type + "&arg1=" + this.str_1 + "&arg2=" + this.str_2)
.then(res => res.text())
.then(res => {
this.result = res;
})
}
}
}
</script>
<template>
<Header></Header>
<Footer></Footer>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,20 @@
import {createRouter, createWebHistory} from "vue-router"
import Index from '../pages/Index.vue'
import Authors from '../pages/Authors.vue'
import Books from '../pages/Books.vue'
import Genres from '../pages/Genres.vue'
const routes = [
{path: '/', component: Index},
{path: '/authors', component: Authors},
{path: '/books', component: Books},
{path: '/genres', component: Genres},
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
export default router;

View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
})

View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Автор</th>
<th scope="col">Название книг</th>
</tr>
</thead>
<tbody>
<tr th:each="ab, iterator: ${authorsbooks}">
<td th:text="${ab.key}" style="width: 25%"/>
<td>
<ul>
<li th:each="value : ${ab.value}">
<span th:text="${value}"></span>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<a class="btn btn-secondary" th:href="@{/author}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Дата релиза</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="ab, iterator: ${authorbooks}">
<td th:text="${ab.name}" style="width: 25%"/>
<td th:text="${ab.release}" style="width: 25%"/>
<td><img th:src="${ab.cover}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${ab.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/author/{id}/books/{bookid}(id=${author.id}, bookid=${ab.id})}" method="post">
<button th:id="'remove-' + ${ab.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<form th:action="@{/author/{id}/books(id=${author.id})}" enctype="bookid/form-data" method="post">
<div class="input-group mb-3">
<select class="form-select" th:name="bookid">
<option th:each="book, iterator: ${books}" th:value="${book.id}" th:text="${book.name}"></option>
</select>
<button class="btn btn-outline-secondary" type="submit">Добавить</button>
</div>
</form>
<div>
<a class="btn btn-secondary" th:href="@{/author}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/author/{id}(id=${id})}" th:object="${authorDto}" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="firstname" class="form-label">Имя</label>
<input type="text" class="form-control" id="firstname" th:field="${authorDto.firstname}" required="true">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Фамилия</label>
<input type="text" class="form-control" id="lastname" th:field="${authorDto.lastname}" required="true">
</div>
<div class="mb-3">
<label for="photo" class="form-label">Фото</label>
<input type="file" class="form-control" id="photo" th:name="multipartFile" required="true">
<img th:src="${authorDto.photo}" class="img-thumbnail mw-50 mh-50"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/author}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/author/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
<a class="btn btn-primary button-fixed"
th:href="@{/author/books}">
<i class="fa-solid fa-plus"></i> Список авторов с книгами
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Имя</th>
<th scope="col">Фамилия</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="author, iterator: ${authors}">
<td th:text="${author.firstname}" style="width: 15%"/>
<td th:text="${author.lastname}" style="width: 15%"/>
<td><img th:src="${author.photo}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/author/update/{id}(id=${author.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${author.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/author/{id}/books(id=${author.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Книга
</a>
</div>
<form th:action="@{/author/delete/{id}(id=${author.id})}" method="post">
<button th:id="'remove-' + ${author.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="bg, iterator: ${bookgenres}">
<td th:text="${bg.name}" style="width: 25%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${bg.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/book/{id}/genres/{genreid}(id=${book.id}, genreid=${bg.id})}" method="post">
<button th:id="'remove-' + ${bg.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<form th:action="@{/book/{id}/genres(id=${book.id})}" enctype="genreid/form-data" method="post">
<div class="input-group mb-3">
<select class="form-select" th:name="genreid">
<option th:each="genre, iterator: ${genres}" th:value="${genre.id}" th:text="${genre.name}"></option>
</select>
<button class="btn btn-outline-secondary" type="submit">Добавить</button>
</div>
</form>
<div>
<a class="btn btn-secondary" th:href="@{/book}">Закрыть</a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/book/{id}(id=${id})}" th:object="${bookDto}" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${bookDto.name}" required="true">
</div>
<div class="mb-3">
<label for="release" class="form-label">Дата релиза</label>
<input type="date" class="form-control" id="release" th:field="${bookDto.release}" required="true">
</div>
<div class="mb-3">
<label for="cover" class="form-label">Обложка</label>
<input type="file" class="form-control" id="cover" th:name="multipartFile" required="true">
<img th:src="${bookDto.cover}" class="img-thumbnail mw-50 mh-50"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/book}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/book/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Дата релиза</th>
<th scope="col">Фото</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="book, iterator: ${books}">
<td th:text="${book.name}" style="width: 25%"/>
<td th:text="${book.release}" style="width: 25%"/>
<td><img th:src="${book.cover}" class="img-thumbnail mw-50 mh-50"/></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/book/update/{id}(id=${book.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${book.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/book/{id}/genres(id=${book.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Жанры
</a>
</div>
<form th:action="@{/book/delete/{id}(id=${book.id})}" method="post">
<button th:id="'remove-' + ${book.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Онлайн библиотека</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
</head>
<body>
<header class="fixed-top">
<nav class="navbar navbar-expand-lg bg-success" data-bs-theme="dark">
<div class="container">
<a class="navbar-brand" href="#">
<strong class="text-white">{ OBS } Online Book Service</strong>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active text-white" aria-current="page" href="/author" th:classappend="${#strings.equals(activeLink, '/author')} ? 'active' : ''">Authors</a>
<a class="nav-link active text-white" href="/book" th:classappend="${#strings.equals(activeLink, '/book')} ? 'active' : ''">Books</a>
<a class="nav-link active text-white" href="/genre" th:classappend="${#strings.equals(activeLink, '/genre')} ? 'active' : ''">Genres</a>
<a class="nav-link active text-white" href="/users" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Users</a>
<a class="nav-link active text-white" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Logout</a>
</div>
</div>
</div>
</nav>
</header>
<div class="container-fluid" style="margin-top: 50pt;">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
<footer class="container pt-4 my-md-5 pt-md-5 text-center border-top">
<div class="row">
<div class="col-12 col-md">
<h5 class=""><strong>End</strong></h5>
</div>
</div>
</footer>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/author">На главную</a>
</div>
</body>
</html>

View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/genre/{id}(id=${id})}" th:object="${genreDto}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${genreDto.name}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">
<span th:if="${id == null}">
<i class="fa-solid fa-plus"></i> Добавить
</span>
<span th:if="${id != null}">
<i class="fa fa-pencil" aria-hidden="true"></i> Сохранить
</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/genre}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div>
<a class="btn btn-success button-fixed"
th:href="@{/genre/update}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Редактировать запись</th>
</tr>
</thead>
<tbody>
<tr th:each="genre, iterator: ${genres}">
<td th:text="${genre.name}" style="width: 60%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/genre/update/{id}(id=${genre.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${genre.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/genre/delete/{id}(id=${genre.id})}" method="post">
<button th:id="'remove-' + ${genre.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.w3.org/1999/xhtml"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
User not found
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Logout success
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
User '<span th:text="${param.created}"></span>' was successfully created
</div>
<form th:action="@{/login}" method="post">
<div class="mb-3">
<p class="mb-1">Login</p>
<input name="username" id="username" class="form-control"
type="text" required autofocus />
</div>
<div class="mb-3">
<p class="mb-1">Password</p>
<input name="password" id="password" class="form-control"
type="password" required />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">
Sign in
</button>
</div>
<div>
<p>
<span>Not a member yet?</span>
<a href="/signup">Sign Up here</a>
</p>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container container-padding mt-3" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${UserDTO}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${UserDTO.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mx-4">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active">
</a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,115 @@
package ru.ip.labworks.labworks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labworks.labworks.bookshop.model.Author;
import ru.ip.labworks.labworks.bookshop.model.Book;
import ru.ip.labworks.labworks.bookshop.service.AuthorService;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SpringBootTest
public class JpaAuthorTests {
/*@Autowired
AuthorService authorService;
@Autowired
BookService bookService;
@Test
void TestAddAuthor(){
authorService.deleteAllAuthors();
final Author author = authorService.addAuthor("test", "test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
Assertions.assertNotNull(author.getId());
}
@Test
void TestFindAuthor(){
authorService.deleteAllAuthors();
final Author author = authorService.addAuthor("test", "test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final Author findAuthor = authorService.findAuthor(author.getId());
Assertions.assertEquals(author, findAuthor);
}
@Test
void TestAuthorReadNotFound(){
authorService.deleteAllAuthors();
Assertions.assertThrows(EntityNotFoundException.class, () -> authorService.findAuthor(-1L));
}
@Test
void TestFindAllAuthor(){
authorService.deleteAllAuthors();
final Author author1 = authorService.addAuthor("Test1","Test1", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final Author author2 = authorService.addAuthor("Test2","Test2", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final List<Author> authors = authorService.findAllAuthors();
Assertions.assertEquals(authors.size(), 2);
}
@Test
void TestAuthorReadAllEmpty() {
authorService.deleteAllAuthors();
final List<Author> authors = authorService.findAllAuthors();
Assertions.assertEquals(authors.size(), 0);
}
@Test
void TestAuthorUpdate(){
authorService.deleteAllAuthors();
Author author = authorService.addAuthor("Test1","Test1", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
author = authorService.updateAuthor(author.getId(), "Test2", "Test2", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
Assertions.assertEquals(author.getFirstnameName(), "Test2");
Assertions.assertEquals(author.getLastName(), "Test2");
Assertions.assertNotNull(author.getPhoto());
}
@Test
void TestDeleteAuthor(){
authorService.deleteAllAuthors();
final Author author = authorService.addAuthor("Test","Test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
authorService.deleteAuthor(author.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> authorService.findAuthor(1L));
}
@Test
void TestAddBookToAuthor(){
authorService.deleteAllAuthors();
Author author = authorService.addAuthor("Test", "Test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final Book book = bookService.addBook("Test2", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
authorService.addBookToAuthor(author.getId(), book);
author = authorService.findAuthor(author.getId());
Assertions.assertEquals(author.getBooks().size(), 1);
bookService.deleteAllBooks();
}
@Test
void TestRemoveBookFromAuthor(){
authorService.deleteAllAuthors();
bookService.deleteAllBooks();
Author author = authorService.addAuthor("Test", "Test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final Book book = bookService.addBook("Test2", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
authorService.addBookToAuthor(author.getId(), book);
authorService.removeBookFromAuthor(author.getId(), book);
author = authorService.findAuthor(author.getId());
Assertions.assertEquals(author.getBooks().size(), 0);
}
@Test
void TestAllAB(){
authorService.deleteAllAuthors();
bookService.deleteAllBooks();
Author author = authorService.addAuthor("Test", "Test", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\SK.jpg"));
final Book book = bookService.addBook("Test2", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
authorService.addBookToAuthor(author.getId(), book);
Map<String, List<String>> result = new HashMap<>();
List<String> temp = new ArrayList<>();
temp.add(book.getName());
result.put(author.getLastName(), temp);
Assertions.assertEquals(authorService.AllAuthorsAndBooks(), result);
Assertions.assertNotNull(authorService.AllAuthorsAndBooks());
}*/
}

View File

@ -0,0 +1,101 @@
package ru.ip.labworks.labworks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labworks.labworks.bookshop.model.Book;
import ru.ip.labworks.labworks.bookshop.model.Genre;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;
@SpringBootTest
public class JpaBookTests {
/*@Autowired
BookService bookService;
@Autowired
GenreService genreService;
@Test
void TestAddBook(){
bookService.deleteAllBooks();
final Book book = bookService.addBook("test", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
Assertions.assertNotNull(book.getId());
}
@Test
void TestFindBook(){
bookService.deleteAllBooks();
final Book book = bookService.addBook("Test","03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
final Book findBook = bookService.findBook(book.getId());
Assertions.assertEquals(book, findBook);
}
@Test
void TestBookReadNotFound(){
bookService.deleteAllBooks();
Assertions.assertThrows(EntityNotFoundException.class, () -> bookService.findBook(-1L));
}
@Test
void TestFindAllBook(){
bookService.deleteAllBooks();
final Book book1 = bookService.addBook("Test1","03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
final Book book2 = bookService.addBook("Test2","03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
final List<Book> books = bookService.findAllBooks();
Assertions.assertEquals(books.size(), 2);
}
@Test
void TestBookReadAllEmpty() {
bookService.deleteAllBooks();
final List<Book> books = bookService.findAllBooks();
Assertions.assertEquals(books.size(), 0);
}
@Test
void TestBookUpdate(){
bookService.deleteAllBooks();
Book book = bookService.addBook("Test1","03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
book = bookService.updateBook(book.getId(), "Test2", "02.03.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
Assertions.assertEquals(book.getName(), "Test2");
Assertions.assertEquals(book.getRelease().toString(), "Thu Mar 02 00:00:00 GMT+04:00 2023");
Assertions.assertNotNull(book.getCover());
}
@Test
void TestDeleteBook(){
bookService.deleteAllBooks();
final Book book = bookService.addBook("Test","03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
bookService.deleteBook(book.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> bookService.findBook(1L));
}
@Test
void TestAddGenreToBook(){
bookService.deleteAllBooks();
genreService.deleteAllGenres();
Book book = bookService.addBook("Test", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
final Genre genre = genreService.addGenre("Test2");
bookService.addGenreToBook(book.getId(), genre);
book = bookService.findBook(book.getId());
Assertions.assertEquals(book.getGenres().size(), 1);
}
@Test
void TestRemoveGenreFromBook(){
bookService.deleteAllBooks();
genreService.deleteAllGenres();
Book book = bookService.addBook("Test", "03.04.2023", new File("D:\\Учёба\\Интернет программирование\\PIbd-22_Bondarenko_M.S._IP\\src\\main\\resources\\glow.png"));
final Genre genre = genreService.addGenre("Test2");
bookService.addGenreToBook(book.getId(), genre);
bookService.removeGenreFromBook(book.getId(), genre);
book = bookService.findBook(book.getId());
Assertions.assertEquals(book.getGenres().size(), 0);
}*/
}

View File

@ -0,0 +1,68 @@
package ru.ip.labworks.labworks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labworks.labworks.bookshop.model.Genre;
import ru.ip.labworks.labworks.bookshop.service.GenreService;
import java.util.List;
@SpringBootTest
public class JpaGenreTests {
/*@Autowired
GenreService genreService;
@Test
void TestAddGenre(){
genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("test");
Assertions.assertNotNull(genre.getId());
}
@Test
void TestFindGenre(){
genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Test");
final Genre findGenre = genreService.findGenre(genre.getId());
Assertions.assertEquals(genre, findGenre);
}
@Test
void TestGenreReadNotFound(){
genreService.deleteAllGenres();
Assertions.assertThrows(EntityNotFoundException.class, () -> genreService.findGenre(-1L));
}
@Test
void TestFindAllGenre(){
genreService.deleteAllGenres();
final Genre genre1 = genreService.addGenre("Test1");
final Genre genre2 = genreService.addGenre("Test2");
final List<Genre> genres = genreService.findAllGenres();
Assertions.assertEquals(genres.size(), 2);
}
@Test
void TestGenreReadAllEmpty() {
genreService.deleteAllGenres();
final List<Genre> genres = genreService.findAllGenres();
Assertions.assertEquals(genres.size(), 0);
}
@Test
void TestGenreUpdate(){
genreService.deleteAllGenres();
Genre genre = genreService.addGenre("Test1");
genre = genreService.updateGenre(genre.getId(), "Test2");
Assertions.assertEquals(genre.getName(), "Test2");
}
@Test
void TestDeleteGenre(){
genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Test");
genreService.deleteGenre(genre.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> genreService.findGenre(1L));
}*/
}

View File

@ -1,13 +1,90 @@
package ru.ip.labworks.labworks; package ru.ip.labworks.labworks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest @SpringBootTest
class LabworksApplicationTests { class LabworksApplicationTests {
/*@Autowired
CalculatorService calculatorService;
@Test @Test
void contextLoads() { void IntPlus() {
final String res = calculatorService.Plus("int", 10, 2).toString();
Assertions.assertEquals("12", res);
} }
@Test
void IntMinus() {
final String res = calculatorService.Minus("int", 10, 2).toString();
Assertions.assertEquals("8", res);
}
@Test
void IntMulti() {
final String res = calculatorService.Multi("int", 10, 2).toString();
Assertions.assertEquals("20", res);
}
@Test
void IntDiv() {
final String res = calculatorService.Div("int", 10, 2).toString();
Assertions.assertEquals("5", res);
}
@Test
void StrPlus() {
final String res = calculatorService.Plus("string", "10", "2").toString();
Assertions.assertEquals("102", res);
}
@Test
void StrMinus() {
final String res = calculatorService.Minus("string", "10", "0").toString();
Assertions.assertEquals("1", res);
}
@Test
void StrMulti() {
final String res = calculatorService.Multi("string", "10", "2").toString();
Assertions.assertEquals("1010", res);
}
@Test
void StrDiv() {
final String res = calculatorService.Div("string", "1010", "2").toString();
Assertions.assertEquals("10", res);
}
@Test
void ArrayPlus() {
final String res = calculatorService.Plus("array", "2,2", "3,3").toString();
Assertions.assertEquals("[23, 23]", res);
}
@Test
void ArrayMinus() {
final String res = calculatorService.Minus("array", "24,23", "4,3").toString();
Assertions.assertEquals("[2, 2]", res);
}
@Test
void ArrayMulti() {
final String res = calculatorService.Multi("array", "23,24", "2,2").toString();
Assertions.assertEquals("[2323, 2424]", res);
}
@Test
void ArrayDiv() {
final String res = calculatorService.Div("array", "23,24", "1,1").toString();
Assertions.assertEquals("[2, 2]", res);
}
@Test
void testErrorErrorWired() {
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calculatorService.Plus("date", 1, 2));
}*/
} }