Compare commits

...

20 Commits

Author SHA1 Message Date
maxnes3
0ba3312dae Сдал 2023-05-15 19:06:57 +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
51 changed files with 8848 additions and 2 deletions

View File

@ -15,6 +15,10 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator:6.0.17.Final'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
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.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class LabworksApplication {
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 javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/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,25 @@
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;}
}

View File

@ -0,0 +1,59 @@
package ru.ip.labworks.labworks.bookshop.controller;
import org.springframework.web.bind.annotation.*;
import ru.ip.labworks.labworks.bookshop.service.BookService;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/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,26 @@
package ru.ip.labworks.labworks.bookshop.controller;
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;
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;}
}

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 javax.validation.Valid;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/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,17 @@
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;}
}

View File

@ -0,0 +1,77 @@
package ru.ip.labworks.labworks.bookshop.model;
import ru.ip.labworks.labworks.bookshop.controller.AuthorDto;
import javax.persistence.*;
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;
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);
}
}

View File

@ -0,0 +1,83 @@
package ru.ip.labworks.labworks.bookshop.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import ru.ip.labworks.labworks.bookshop.controller.BookDto;
import javax.persistence.*;
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;
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);
}
}

View File

@ -0,0 +1,48 @@
package ru.ip.labworks.labworks.bookshop.model;
import ru.ip.labworks.labworks.bookshop.controller.GenreDto;
import javax.persistence.*;
import java.util.*;
@Entity
public class Genre {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
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 + '\'' +
'}';
}
}

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,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,135 @@
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 org.hibernate.query.Query;
import ru.ip.labworks.labworks.bookshop.repository.AuthorRepository;
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.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;
public AuthorService(AuthorRepository authorRepository, BookService bookService, ValidatorUtil validatorUtil){
this.authorRepository = authorRepository;
this.bookService = bookService;
this.validatorUtil = validatorUtil;
}
@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) throws IOException {
final Author author = new Author(authorDto);
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){
final Author currentAuthor = findAuthor(id);
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) {
authorRepository.deleteById(id);
}
@Transactional
public void deleteAllAuthors() {
authorRepository.deleteAll();
}
@Transactional
public void addBookToAuthor(Long id, Long bookId){
Optional<Author> author = authorRepository.findById(id);
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){
Optional<Author> author = authorRepository.findById(id);
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,129 @@
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.repository.BookRepository;
import ru.ip.labworks.labworks.bookshop.repository.GenreRepository;
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;
public BookService(BookRepository bookRepository, ValidatorUtil validatorUtil, GenreService genreService){
this.bookRepository = bookRepository;
this.validatorUtil = validatorUtil;
this.genreService = genreService;
}
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) throws IOException {
final Book book = new Book(bookDto);
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){
final Book currentBook = findBook(id);
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) {
bookRepository.deleteById(id);
}
@Transactional
public void deleteAllBooks() {
bookRepository.deleteAll();
}
@Transactional
public void addGenreToBook(Long id, Long genreId){
Optional<Book> book = bookRepository.findById(id);
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){
Optional<Book> book = bookRepository.findById(id);
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,80 @@
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.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;
public GenreService(GenreRepository genreRepository, ValidatorUtil validatorUtil){
this.genreRepository = genreRepository;
this.validatorUtil = validatorUtil;
}
@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) throws IOException {
final Genre genre = new Genre(genreDto);
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){
final Genre currentGenre = findGenre(id);
currentGenre.setName(genreDto.getName());
return genreRepository.save(currentGenre);
}
@Transactional
public void deleteGenre(Long id) {
genreRepository.deleteById(id);
}
@Transactional
public void deleteAllGenres() {
genreRepository.deleteAll();
}
}

View File

@ -0,0 +1,20 @@
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;
}
}
}

View File

@ -0,0 +1,13 @@
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.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,36 @@
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 ru.ip.labworks.labworks.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice
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 javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.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,116 @@
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 javax.persistence.EntityNotFoundException;
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,102 @@
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 javax.persistence.EntityNotFoundException;
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,69 @@
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 javax.persistence.EntityNotFoundException;
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,91 @@
package ru.ip.labworks.labworks;
import org.junit.jupiter.api.Assertions;
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 ru.ip.labworks.labworks.calculator.service.CalculatorService;
@SpringBootTest
class LabworksApplicationTests {
@Autowired
CalculatorService calculatorService;
@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));
}
}