diff --git a/src/main/java/com/epam/izh/rd/online/Main.java b/src/main/java/com/epam/izh/rd/online/Main.java index e3939a4b..bd28b8eb 100644 --- a/src/main/java/com/epam/izh/rd/online/Main.java +++ b/src/main/java/com/epam/izh/rd/online/Main.java @@ -1,9 +1,419 @@ package com.epam.izh.rd.online; +import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.entity.SchoolBook; +import com.epam.izh.rd.online.repository.SimpleAuthorRepository; +import com.epam.izh.rd.online.repository.SimpleSchoolBookRepository; +import com.epam.izh.rd.online.service.SimpleAuthorService; +import com.epam.izh.rd.online.service.SimpleSchoolBookService; +import com.sun.org.apache.xerces.internal.xs.datatypes.ObjectList; +import org.springframework.util.Assert; + + +import java.time.LocalDate; +import java.util.ArrayList; + public class Main { public static void main(String[] args) { + {/* SECTION FOR PLAYING WITH ASSERTIONS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH ASSERTIONS */\n"); + + try { + Assert.isTrue(1 == 1, "What? 1 == 2? That's not true!!!"); + System.out.println("Assertion is successful. The requirement was met. Good job, man!"); + } /*catch ( IllegalArgumentException e ) { + System.out.println("What was that?!"); + }*/ catch ( Exception e ) { + System.out.println("It was just an exception. Don't worry, be happy."); + } + + System.out.println("\n/* END OF PLAYING WITH ASSERTIONS */\n"); + + }/* END OF DEBUGGING ASSERTIONS */ + + + {/* SECTION FOR PLAYING WITH CONSTRUCTORS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH CONSTRUCTORS */\n"); + + class A { + A() { + System.out.println("A() constructor is working ..."); + } + + A( String a ) { + System.out.println("A('" + a + "') constructor is working ..."); + } + + @Override + public String toString() { + return "instance of class A = {}"; + } + } + + class B extends A { + String bField; + B() { + System.out.println("B() constructor is working ..."); + } + + @Override + public String toString() { + return "instance of class B = { " + + "bField='" + bField + '\'' + + " }"; + } + } + + class C extends B { + C() { + System.out.println("C() constructor is working ..."); + } + + C(String s) { + System.out.println("C('" + s + "') constructor is working ..."); + bField = s; + } + + @Override + public String toString() { + return "instance of class C = { " + + "bField='" + bField + '\'' + + " }"; + } + } + + System.out.println("Creating instance of class A with the A() constructor:"); + A aInstance1 = new A(); + System.out.println("aInstance1 was just born: " + aInstance1.toString()); + + System.out.println("\nCreating instance of class A with the A(String) constructor:"); + A aInstance2 = new A("just a string"); + System.out.println("aInstance2 was just born: " + aInstance2.toString()); + + System.out.println("\nCreating instance of class B with the B() constructor:"); + B bInstance = new B(); + System.out.println("bInstance was just born: " + bInstance.toString()); + + System.out.println("\nCreating instance of class C with the C() constructor:"); + C cInstance1 = new C(); + System.out.println("cInstance1 was just born: " + cInstance1.toString()); + + System.out.println("\nCreating instance of class C with the C(String) constructor:"); + C cInstance2 = new C("some string"); + System.out.println("cInstance2 was just born: " + cInstance2.toString()); + + System.out.println("\n/* END OF DEBUGGING CONSTRUCTORS */\n"); + + }/* END OF DEBUGGING CONSTRUCTORS */ + + + {/* SECTION FOR PLAYING WITH OVERLOADING METHODS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH OVERLOADING METHODS */\n"); + + //Есть 3 перегруженных метода, которые принимают Object List и ArrayList. + // Мы вызываем функцию с параметром null. Какой метод выполнится? + + class A { + + void method(ObjectList objList) { + System.out.println("Method(ObjectList) is running ..."); + } + + void method(ArrayList arrList) { + System.out.println("Method(ArrayList) is running ..."); + } + + void method(ObjectList objList, ArrayList arrList) { + System.out.println("Method(ObjectList,ArrayList) is running ..."); + } + } + + A a = new A(); + ObjectList ol = null; + ArrayList al = null; + + a.method(ol); + a.method(al); + a.method(ol, al); + + System.out.println("\n/* END OF DEBUGGING OVERLOADING METHODS */\n"); + + }/* END OF DEBUGGING OVERLOADING METHODS */ + + + {/* SECTION FOR PLAYING WITH BINDING METHODS */ + + System.out.println("\n/* SECTION FOR PLAYING WITH BINDING METHODS */\n"); + + class Base { + void method() { + System.out.println("The version of method() declared in class Base is running ..."); + } + + void subtleMethod( int par ) { + System.out.println("The version of subtleMethod(int par=" + par + ") declared in class Base is running ..."); + } + } + + class Derived extends Base { + void method() { + System.out.println("The version of method() declared in class Derived is running ..."); + } + + void subtleMethod( byte par ) { + System.out.println("The version of subtleMethod(byte par=0b" + Integer.toBinaryString(par) + "=" + par + ") declared in class Derived is running ..."); + } + } + + // Type of reference variable instance1 is --> Base ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Base ( INFO FOR JVM = for late binding ) + Base instanceBB = new Base(); + + // Type of reference variable instance2 is --> Base! ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Derived ( INFO FOR JVM = for late binding ) + Base instanceBD = new Derived(); + + // Type of reference variable instance2 is --> Derived ( INFO FOR COMPILER = for early binding ) + // Type of the created referenced instance/object is --> Derived ( INFO FOR JVM = for late binding ) + Derived instanceDD = new Derived(); + + System.out.println("************** Overriding method() ****************"); + + System.out.println("\nBase instanceBB = new Base(); --> instanceBB.method():"); + instanceBB.method(); + + System.out.println("\nBase instanceBD = new Derived(); --> instanceBD.method():"); + instanceBD.method(); + + System.out.println("\nDerived instanceDD = new Derived(); --> instanceDD.method():"); + instanceDD.method(); + + System.out.println("\n************** Overloading subtlemethod() ****************\n"); + + int parII = 1; + int parIB = 0b0000010; + byte parBI = (byte) 3; + byte parBB = 0b0000100; + + System.out.println("1) Base instanceBB = new Base();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parII):"); + instanceBB.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parIB):"); + instanceBB.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parBI):"); + instanceBB.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceBB.subtleMethod(parBB):"); + instanceBB.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Base type of the reference instanceBB tells compiler that it has to look for the method subtleMethod() inside class Base."); + System.out.println("\tCompiler sees the only one version of the method subtleMethod() in the class Base so it decides to bind it with the call places in the code - early binding takes place. "); + System.out.println("\tThere is no late run-time binding because there is no other alternative of the body of the subtleMethod()."); + + + System.out.println("\n2) Base instanceBD = new Derived();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parII):"); + instanceBD.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parIB):"); + instanceBD.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parBI):"); + instanceBD.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parBB):"); + instanceBD.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Base type of the reference instanceBD tells compiler that it should search for the method subtleMethod() inside class Base."); + System.out.println("\tCompiler sees the only one version of the method subtleMethod() in the class Base so it decides to bind it with the call places in the code - early binding takes place. "); + System.out.println("\tThere is no late run-time binding because there is no other alternative of the body of the subtleMethod()."); + + + System.out.println("\n3) Derived instanceDD = new Derived();"); + + System.out.println("\nint parII = 1; ( 0b" + Integer.toBinaryString(parII) + " )"); + System.out.println("Trying instanceBD.subtleMethod(parII):"); + instanceDD.subtleMethod(parII); + + System.out.println("\nint parIB = 0b0000010; ( " + Integer.toString(parIB) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parIB):"); + instanceDD.subtleMethod(parIB); + + System.out.println("\nbyte parBI = (byte) 3; ( 0b" + Integer.toBinaryString(parBI) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parBI):"); + instanceDD.subtleMethod(parBI); + + System.out.println("\nbyte parBB = 0b0000100; ( " + Integer.toString(parBB) + " )"); + System.out.println("Trying instanceDD.subtleMethod(parBB):"); + instanceDD.subtleMethod(parBB); + + System.out.println("\nRESUME:\n\tThe Derived type of the reference instanceDD tells compiler that it should search for the method subtleMethod() inside class Derived."); + System.out.println("\tCompiler sees two alternative versions of the method subtleMethod() in the class Derived - inherited from class Base and reloaded version."); + System.out.println("\tSo the compiler decides that it's not yet the time to bind the body of the subtleMethod() and so this time the early ( static ) binding is declined."); + System.out.println("\tDuring run-time JVM chooses proper version of the subtleMethod() body and binds it with the call place - the late ( dynamic ) binding occurs."); + + System.out.println("\n/* END OF DEBUGGING BINDING METHODS */\n"); + + }/* END OF DEBUGGING BINDING METHODS */ + + + {/* SECTION FOR DEBUGGING CLASSES */ + + System.out.println("\n/* SECTION FOR DEBUGGING CLASSES */\n"); + + System.out.println("********** Working with authors repository **********\n"); + + Author author1 = new Author("Yaroslav", "Kozlov", LocalDate.of(1974,10,05), "Russia"); + Author author2 = new Author("James", "Bond", null, "UK"); + Author author3 = new Author("Wolfgang", "Mozart", LocalDate.of(1756,01,27), "Austria"); + + SimpleAuthorRepository rep4Authors = new SimpleAuthorRepository(); + + System.out.println("author1.toString(): " + author1.toString()); + System.out.println("author2.toString(): " + author2.toString()); + System.out.println("author3.toString(): " + author3.toString()); + + System.out.println("\nNumber of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author1 in repository"); + rep4Authors.save(author1); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author2 in repository"); + rep4Authors.save(author2); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + System.out.println("\nSaving author3 in repository"); + rep4Authors.save(author3); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + Author found; + found = rep4Authors.findByFullName("James", "Bond"); + System.out.println("\nIs James Bond in repository? " + (found == null ? "No: " : "Yes: ") + found); + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + Author vasya = new Author("Vasya","Pupkin",null, null); + System.out.println("\nSaving author Vasya Pupkin in repository"); + rep4Authors.save(vasya); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + System.out.println("\nRemoving author Vasya Pupkin from repository"); + rep4Authors.remove(vasya); + System.out.println("Number of authors saved in repository is " + rep4Authors.count()); + found = rep4Authors.findByFullName("Vasya", "Pupkin"); + System.out.println("Is Vasya Pupkin in repository? " + (found == null ? "No: " : "Yes: ") + found); + + System.out.println("\n********** Working with books repository **********\n"); + + SchoolBook book1 = new SchoolBook(250, "The hound of the Baskervilles", "Arthur", "Conan Doyle", null); + SchoolBook book2 = new SchoolBook(300, "The hound of the Baskervilles", "Arthur", "Doyle", null); + SchoolBook book3 = new SchoolBook(1000, "Short stories", "James", "Bond", null); + + SimpleSchoolBookRepository rep4Books = new SimpleSchoolBookRepository(); + + System.out.println("book1.toString(): " + book1.toString()); + System.out.println("book2.toString(): " + book2.toString()); + System.out.println("book3.toString(): " + book3.toString()); + + System.out.println("\nNumber of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book1 in repository"); + rep4Books.save(book1); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book2 in repository"); + rep4Books.save(book2); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nSaving book3 in repository"); + rep4Books.save(book3); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + SchoolBook[] foundBooks; + foundBooks = rep4Books.findByName("The hound of the Baskervilles"); + System.out.println("\nIs \"The hound of the Baskervilles\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + SchoolBook vasyasBook = new SchoolBook(500, "Memoirs", "Vasya", "Pupkin", null); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\nSaving the book \"Memoirs\" by Vasya Pupkin in repository"); + rep4Books.save(vasyasBook); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\nRemoving \"Memoirs\" from repository"); + rep4Books.removeByName("Memoirs"); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + System.out.println("\nRemoving \"The hound of the Baskervilles\" from repository"); + rep4Books.removeByName("The hound of the Baskervilles"); + System.out.println("Number of books saved in repository is " + rep4Books.count()); + + foundBooks = rep4Books.findByName("Memoirs"); + System.out.println("\nIs \"Memoirs\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + foundBooks = rep4Books.findByName("The hound of the Baskervilles"); + System.out.println("\nIs \"The hound of the Baskervilles\" in repository? " + (foundBooks.length == 0 ? "No books with such a title!" : "Yes: 1 of " + foundBooks.length + " is an " + foundBooks[0].toString() )); + + System.out.println("\n********** Using services ***********\n"); + + // Creating service with methods for authors repository + SimpleAuthorService ser4Authors = new SimpleAuthorService(rep4Authors); + + // Creating service with functionality to work with books taking in account given authors repository + SimpleSchoolBookService ser4Books = new SimpleSchoolBookService(rep4Books, ser4Authors); + + System.out.println("Number of books in storage is: " + ser4Books.count()); + System.out.println("Number of authors registered is: " + ser4Authors.count()); + + System.out.println("\nRecording author Vasya Pupkin into authors repository ..."); + rep4Authors.save(vasya); + System.out.println("Now the number of registered authors is: " + ser4Authors.count()); + + System.out.println("\nAdding 5 instances of the book \"Memoirs\" by Vasya Pupkin to book storage ..."); + for (int i=0; i < 5; i++) { + rep4Books.save(vasyasBook); + } + System.out.println("Now total number of books in the storage is: " + ser4Books.count()); + System.out.println("Number of book \"Memoirs\" in the storage is: " + ser4Books.getNumberOfBooksByName("Memoirs") + " of " + ser4Books.count()); + System.out.println("1st found \"Memoirs\" is: " + ser4Books.findByName("Memoirs")[0]); + System.out.println("The author of \"Memoirs\" is: " + ser4Books.findAuthorByBookName("Memoirs")); + + System.out.println("\nRemoving all (5) instances of the book \"Memoirs\" by Vasya Pupkin from the book storage ..."); + ser4Books.removeByName("Memoirs"); + System.out.println("Now total number of books in the storage is: " + ser4Books.count()); + System.out.println("Number of book \"Memoirs\" in the storage is: " + ser4Books.getNumberOfBooksByName("Memoirs") + " of " + ser4Books.count()); + + System.out.println("\n/* END OF DEBUGGING CLASSES */\n"); + + }/* END OF DEBUGGING CLASSES */ + + System.exit(0); } } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Author.java b/src/main/java/com/epam/izh/rd/online/entity/Author.java index 166be587..e8a37df2 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Author.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Author.java @@ -20,4 +20,82 @@ */ public class Author { + private String name; + private String lastName; + private LocalDate birthdate; + private String country; + + public Author() { + } + + public Author(String name, String lastName, LocalDate birthdate, String country) { + this.name = name; + this.lastName = lastName; + this.birthdate = birthdate; + this.country = country; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public LocalDate getBirthdate() { + return birthdate; + } + + public void setBirthdate(LocalDate birthdate) { + this.birthdate = birthdate; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Author author = (Author) o; + + if (name != null ? !name.equals(author.name) : author.name != null) return false; + if (lastName != null ? !lastName.equals(author.lastName) : author.lastName != null) return false; + if (birthdate != null ? !birthdate.equals(author.birthdate) : author.birthdate != null) return false; + return country != null ? country.equals(author.country) : author.country == null; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (lastName != null ? lastName.hashCode() : 0); + result = 31 * result + (birthdate != null ? birthdate.hashCode() : 0); + result = 31 * result + (country != null ? country.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "instance of class Author = { " + + "name='" + name + '\'' + + ", lastName='" + lastName + '\'' + + ", birthdate=" + birthdate + + ", country='" + country + '\'' + + " }"; + } } diff --git a/src/main/java/com/epam/izh/rd/online/entity/Book.java b/src/main/java/com/epam/izh/rd/online/entity/Book.java index 08bdccb8..c537342d 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/Book.java +++ b/src/main/java/com/epam/izh/rd/online/entity/Book.java @@ -17,4 +17,56 @@ */ public abstract class Book { + private int numberOfPages; + private String name; + + public Book() { + } + + public Book(int numberOfPages, String name) { + this.numberOfPages = numberOfPages; + this.name = name; + } + + public int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } + + 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; + + Book book = (Book) o; + + if (numberOfPages != book.numberOfPages) return false; + return name != null ? name.equals(book.name) : book.name == null; + } + + @Override + public int hashCode() { + int result = numberOfPages; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "instance of class Book = { " + + "numberOfPages=" + numberOfPages + + ", name='" + name + '\'' + + "' }"; + } } diff --git a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java index a9834db4..283f5cdc 100644 --- a/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java +++ b/src/main/java/com/epam/izh/rd/online/entity/SchoolBook.java @@ -21,4 +21,75 @@ */ public class SchoolBook extends Book { + private String authorName; + private String authorLastName; + private LocalDate publishDate; + + public SchoolBook() { + } + + public SchoolBook(int numberOfPages, String name, String authorName, String authorLastName, LocalDate publishDate) { + super(numberOfPages, name); + this.authorName = authorName; + this.authorLastName = authorLastName; + this.publishDate = publishDate; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public String getAuthorLastName() { + return authorLastName; + } + + public void setAuthorLastName(String authorLastName) { + this.authorLastName = authorLastName; + } + + public LocalDate getPublishDate() { + return publishDate; + } + + public void setPublishDate(LocalDate publishDate) { + this.publishDate = publishDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + + SchoolBook that = (SchoolBook) o; + + if (authorName != null ? !authorName.equals(that.authorName) : that.authorName != null) return false; + if (authorLastName != null ? !authorLastName.equals(that.authorLastName) : that.authorLastName != null) + return false; + return publishDate != null ? publishDate.equals(that.publishDate) : that.publishDate == null; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (authorName != null ? authorName.hashCode() : 0); + result = 31 * result + (authorLastName != null ? authorLastName.hashCode() : 0); + result = 31 * result + (publishDate != null ? publishDate.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "instance of class SchoolBook = { " + + "Number of pages = " + this.getNumberOfPages() + + ", Name='" + this.getName() + '\'' + + ", authorName='" + authorName + '\'' + + ", authorLastName='" + authorLastName + '\'' + + ", publishDate=" + publishDate + + "' }"; + } } diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java new file mode 100644 index 00000000..3bbc5dda --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleAuthorRepository.java @@ -0,0 +1,119 @@ +package com.epam.izh.rd.online.repository; + +import com.epam.izh.rd.online.entity.Author; + +import java.util.Arrays; + +/** + * Класс SimpleAuthorRepository репозитория для хранения данных об авторах. + * + * Необходимо: + * 1) Имплементировать в данном классе интерфейс AuthorRepository + * 2) Добавить все методы интерфейса (пока можно не писать реализацию) + * 3) Добавить приватное поле "Author[] authors" для хранения авторов + * 4) Инициалазировать его пустым массивом + * 5) Написать реализацию для всех методов (коллекции не используем, работаем только с массивами) + */ +public class SimpleAuthorRepository implements AuthorRepository { + + private Author[] authors = {}; + private int counter = 0; + + /** + * Метод должен сохранять автора в массив authors. + * Массив при каждом сохранении должен увеличиваться в размере ровно на 1. + * То есть он ровно того размера, сколько сущностей мы в него сохранили. + *
+ * Если на вход для сохранения приходит автор, который уже есть в массиве (сохранен), то автор не сохраняется и + * метод возвращает false. + *
+ * Можно сравнивать только по полному имени (имя и фамилия), считаем, что двух авторов + * с одинаковыми именем и фамилией быть не может. + * Подсказка - можно использовать для проверки метод findByFullName. + *
+ * Если сохранение прошло успешно, метод должен вернуть true. + */ + @Override + public boolean save(Author author) { + + if (findByFullName(author.getName(), author.getLastName()) != null) { + return false; + } else { + + Author[] temp; + temp = authors; + authors = new Author[counter + 1]; + + for (int i = 0; i < counter; i++) { + authors[i] = temp[i]; + } + + authors[counter++] = author; + return true; + } + } + + /** + * Метод должен находить в массиве authors автора по имени и фамилии (считаем, что двух авторов + * с одинаковыми именем и фамилией быть не может.) + *
+ * Если автор с таким именем и фамилией найден - возвращаем его, если же не найден, метод должен вернуть null. + */ + @Override + public Author findByFullName(String name, String lastname) { + + if (authors.length == 0) { + return null; + } + + for(Author a : authors) { + if ((a.getName() == name) && (a.getLastName() == lastname)) { + return a; + } + } + + return null; + } + + /** + * Метод должен удалять автора из массива authors, если он там имеется. + * Автора опять же, можно определять только по совпадению имении и фамилии. + *
+ * Важно: при удалении автора из массива размер массива должен уменьшиться! + * То есть, если мы сохранили 2 авторов и вызвали count() (метод ниже), то он должен вернуть 2. + * Если после этого мы удалили 1 автора, метод count() должен вернуть 1. + *
+ * Если автор был найден и удален, метод должен вернуть true, в противном случае, если автор не был найден, метод + * должен вернуть false. + */ + @Override + public boolean remove(Author author) { + + if (findByFullName(author.getName(), author.getLastName()) == null) { + return false; + } else { + + Author[] temp; + temp = authors; + authors = new Author[counter - 1]; + + for (int i = 0, k = 0; i < counter; i++) { + if(temp[i] == author) { + continue; + } + authors[k++] = temp[i]; + } + + counter--; + return true; + } + } + + /** + * Метод возвращает количество сохраненных сущностей в массиве authors. + */ + @Override + public int count() { + return counter; + } +} diff --git a/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java new file mode 100644 index 00000000..2cd09fb8 --- /dev/null +++ b/src/main/java/com/epam/izh/rd/online/repository/SimpleSchoolBookRepository.java @@ -0,0 +1,133 @@ +package com.epam.izh.rd.online.repository; + +import com.epam.izh.rd.online.entity.Author; +import com.epam.izh.rd.online.entity.SchoolBook; + +/** + * Класс SimpleSchoolBookRepository репозитория для хранения данных о книгах + *
+ * Необходимо:
+ * 1) Имплементировать интерфейс BookRepository
+ * Одну и ту же книгу МОЖНО сохранить в массиве несколько раз, проверки на то, что такая книга уже сохранена, делать не нужно.
+ *
+ * Если сохранение прошло успешно, метод должен вернуть true.
+ */
+ @Override
+ public boolean save(SchoolBook book) {
+
+ try {
+
+ SchoolBook[] temp;
+ temp = schoolBooks;
+ schoolBooks = new SchoolBook[counter + 1];
+
+ for (int i = 0; i < counter; i++) {
+ schoolBooks[i] = temp[i];
+ }
+
+ schoolBooks[counter++] = book;
+ return true;
+
+ } catch (Exception e) { // If saving failed, return false
+ return false;
+ }
+ }
+
+ /**
+ * Метод должен находить в массиве schoolBooks все книги по имени.
+ *
+ * Если книги найдены - метод должен их вернуть.
+ * Если найденных по имени книг нет, должен вернуться пустой массив.
+ */
+ @Override
+ public SchoolBook[] findByName(String name) {
+
+ int match = 0;
+
+ // Counting number of books in repository with the same given name
+ for (SchoolBook b : schoolBooks) {
+ if(b.getName() == name) {
+ match++;
+ }
+ }
+
+ if (match == 0) { // If no matching, return empty SchoolBook array
+ return new SchoolBook[0];
+ } else { // If there is something, add books with same name to special temp[] array and return it
+
+ SchoolBook[] temp = new SchoolBook[match];
+
+ for (int i = 0, k = 0; i < counter; i++) {
+ if (schoolBooks[i].getName() == name) {
+ temp[k++] = schoolBooks[i];
+ }
+ }
+
+ return temp;
+ }
+ }
+
+ /**
+ * Метод должен удалять книги из массива schoolBooks по названию.
+ * Если книг с одинаковым названием в массиве несколько, метод должен удалить их все.
+ *
+ * Важно: при удалении книги из массива размер массива должен уменьшиться!
+ * То есть, если мы сохранили 2 разные книги и вызвали count() (метод ниже), то он должен вернуть 2.
+ * Если после этого мы удалили 1 книгу, метод count() должен вернуть 1.
+ *
+ * Если хотя бы одна книга была найдена и удалена, метод должен вернуть true, в противном случае,
+ * если книга не была найдена, метод должен вернуть false.
+ */
+ @Override
+ public boolean removeByName(String name) {
+
+ int match = 0;
+
+ // Counting number of books in repository with the same given name
+ for (SchoolBook b : schoolBooks) {
+ if(b.getName() == name) {
+ match++;
+ }
+ }
+
+ if (match == 0) { // If no matching, return false
+ return false;
+ } else { // If there is something, create new schoolBooks[] array without books with the given name and return true
+
+ SchoolBook[] temp = new SchoolBook[counter - match];
+
+ for (int i = 0, k = 0; i < counter; i++) {
+ if (schoolBooks[i].getName() != name) {
+ temp[k++] = schoolBooks[i];
+ }
+ }
+
+ schoolBooks = temp;
+ counter = schoolBooks.length;
+ return true;
+ }
+ }
+
+ /**
+ * Метод возвращает количество сохраненных сущностей в массиве schoolBooks.
+ */
+ @Override
+ public int count() {
+ return counter;
+ }
+}
diff --git a/src/main/java/com/epam/izh/rd/online/service/BookService.java b/src/main/java/com/epam/izh/rd/online/service/BookService.java
index e221033b..1dfdc577 100644
--- a/src/main/java/com/epam/izh/rd/online/service/BookService.java
+++ b/src/main/java/com/epam/izh/rd/online/service/BookService.java
@@ -4,7 +4,7 @@
import com.epam.izh.rd.online.entity.Book;
/**
- * Интерфейс сервиса для выполнения бизнес логики при работе с книга и авторами и взаимодействием с
+ * Интерфейс сервиса для выполнения бизнес логики при работе с книгами и авторами и взаимодействием с
* репозиторием для книг BookRepository и сервисом для авторов AuthorService.
*
* Необходимо:
diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java
new file mode 100644
index 00000000..c2298c98
--- /dev/null
+++ b/src/main/java/com/epam/izh/rd/online/service/SimpleAuthorService.java
@@ -0,0 +1,65 @@
+package com.epam.izh.rd.online.service;
+
+import com.epam.izh.rd.online.entity.Author;
+import com.epam.izh.rd.online.repository.AuthorRepository;
+
+/**
+ * Класс SimpleAuthorService сервиса для выполнения бизнес логики при работе с авторами и взаимодействием с
+ * репозиторием для авторов AuthorRepository.
+ *
+ * Необходимо:
+ * 1) Имплементировать интерфейс AuthorService
+ * 2) Добавить все методы (пока можно не писать реализацию)
+ * 3) Добавить в SimpleAuthorService приватное поле "AuthorRepository authorRepository" - это репозиторий к котормоу
+ * вы будете обращаться в методах
+ * 4) Создать дефолтный конструтор (без параметров)
+ * 5) Создать конструтор с параметром AuthorRepository authorRepository (который будет устанвливать в поле authorRepository значение)
+ * 6) Написать реализацию для всех методов
+ */
+public class SimpleAuthorService implements AuthorService {
+
+ private AuthorRepository authorRepository;
+
+ public SimpleAuthorService() {
+ }
+
+ public SimpleAuthorService(AuthorRepository authorRepository) {
+ this.authorRepository = authorRepository;
+ }
+
+ /**
+ * Метод должен сохранять автора.
+ * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат.
+ */
+ @Override
+ public boolean save(Author author) {
+ return this.authorRepository.save(author);
+ }
+
+ /**
+ * Метод должен находить автора по имени и фамилии.
+ * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат.
+ */
+ @Override
+ public Author findByFullName(String name, String lastname) {
+ return this.authorRepository.findByFullName(name, lastname);
+ }
+
+ /**
+ * Метод должен удалять автора.
+ * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат..
+ */
+ @Override
+ public boolean remove(Author author) {
+ return this.authorRepository.remove(author);
+ }
+
+ /**
+ * Метод считать количество сохраненных авторов на текущий момент.
+ * По факту, он просто обращается к репозиторию с авторами и вызывает аналогичный метод, псоле чего возвращает результат.
+ */
+ @Override
+ public int count() {
+ return this.authorRepository.count();
+ }
+}
diff --git a/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java
new file mode 100644
index 00000000..4d602ae8
--- /dev/null
+++ b/src/main/java/com/epam/izh/rd/online/service/SimpleSchoolBookService.java
@@ -0,0 +1,132 @@
+package com.epam.izh.rd.online.service;
+
+import com.epam.izh.rd.online.entity.Author;
+import com.epam.izh.rd.online.entity.SchoolBook;
+import com.epam.izh.rd.online.repository.BookRepository;
+
+/**
+ * Класс SimpleSchoolBookService для выполнения бизнес логики при работе с книгами и авторами и взаимодействием с
+ * репозиторием для книг BookRepository и сервисом для авторов AuthorService.
+ *
+ * Необходимо:
+ * 1) Имплементировать интерфейс BookService
+ * 2) Добавить все методы (пока можно не писать реализацию)
+ * 3) Добавить приватное поле "BookRepository
+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат.
+ *
+ */
+ @Override
+ public SchoolBook[] findByName(String name) {
+ return this.schoolBookBookRepository.findByName(name);
+ }
+
+ /**
+ * Метод должен находить количество сохраненных книг по конкретному имени книги.
+ */
+ @Override
+ public int getNumberOfBooksByName(String name) {
+ return schoolBookBookRepository.findByName(name).length; // Size of the array of found books
+ }
+
+ /**
+ * Метод должен удалять все книги по имени.
+ *
+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат.
+ */
+ @Override
+ public boolean removeByName(String name) {
+ return this.schoolBookBookRepository.removeByName(name);
+ }
+
+ /**
+ * Метод должен возвращать количество всех книг.
+ *
+ * По факту, он просто обращается к репозиторию с книгами и вызывает аналогичный метод, псоле чего возвращает результат.
+ */
+ @Override
+ public int count() {
+ return this.schoolBookBookRepository.count();
+ }
+
+ /**
+ * Метод должен возвращать автора книги по названию книги.
+ *
+ * То есть придётся сходить и в репозиторий с книгами, и в сервис авторов.
+ *
+ * Если такой книги не найдено, метод должен вернуть null.
+ */
+ @Override
+ public Author findAuthorByBookName(String name) {
+
+ // Trying to find books with the given name
+ SchoolBook[] booksByName = schoolBookBookRepository.findByName(name);
+
+ if (booksByName.length == 0) { // If there are no books with the given title, return null
+ return null;
+ } else { // If we've got books with the given title
+
+ // Getting author's full name from the 1st found book
+ String xName = booksByName[0].getAuthorName();
+ String xLastName = booksByName[0].getAuthorLastName();
+
+ // Now trying to find author of the book in authors repository and return the result (Author || null)
+ return authorService.findByFullName(xName, xLastName);
+ }
+ }
+}