- package com.mycompany.vegeapp;
- import java.io.BufferedOutputStream;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.RandomAccessFile;
- import java.nio.channels.Channels;
- import java.nio.channels.FileChannel;
- import java.nio.channels.FileLock;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.concurrent.TimeUnit;
- import java.io.Serializable;
- import javax.persistence.*;
- import lombok.Getter;
- import lombok.NoArgsConstructor;
- import lombok.Setter;
- /**
- * Entity class
- *
- * The class represents the vegan food place. It will be somehow the page of a
- * vegan restaurant or coffee. It has its name, type (restaurant/coffee),
- * address and grade which is an average of user marks assigned to the place.
- */
- @Entity
- @Table(name = "VeganFoodPlace")
- @NoArgsConstructor
- public class VeganFoodPlace extends TheVeganBase implements Cloneable, Serializable {
- @Getter
- @Id
- @GeneratedValue
- private Long id;
- @Getter
- @Setter
- private String type;
- @Getter
- @Setter
- @OneToOne
- private Address address;
- @Getter
- @Setter
- private ArrayList<Meal> menu = new ArrayList<Meal>();
- @OneToMany//(mappedBy = "place")
- private List<Meal> meals;
- /**
- * Initializes new instance of VeganFoodPlace.
- *
- * @param n - place name
- * @param t - place type coffee or restaurant
- * @param a - place address @see Address
- * @param g - place grade
- * @param numbGrad - number of grades
- */
- public VeganFoodPlace(String n, String t, Address a, double g, int numbGrad) {
- super(n, g, numbGrad);
- this.type = t;
- this.address = a;
- }
- /**
- * Initializes new instance of VeganFoodPlace.
- *
- * @param n - place name
- * @param t - place type coffee or restaurant
- * @param a - place address @see Address
- */
- public VeganFoodPlace(String n, String t, Address a) {
- super(n, 0.0, 0);
- this.type = t;
- this.address = a;
- }
- /**
- * An abstract method that have to be implemented. Method used to grade the
- * place.
- *
- * @param g - grade for the place
- */
- @Override
- public void gradeIt(int g) {
- double sum = ((this.getGrade() * this.getNumberOfGrades()) + g);
- this.setNumberOfGrades((this.getNumberOfGrades() + 1));
- this.setGrade((sum / (this.getNumberOfGrades())));
- }
- /**
- * An abstract method that have to be implemented. Method used to share with
- * friends opinion about the place.
- *
- * @param v - object of a class TheVeganBase
- * @see TheVeganBase
- */
- @Override
- public void shareWithFriend(TheVeganBase v) {
- System.out.println("That " + this.type + " is soo cool!");
- System.out.println("That is the address: " + this.address);
- System.out.println("Check it out!");
- }
- /**
- * Method adds meal to menu
- *
- * @param m - meal to be added to menu
- */
- public void addMealToMenu(Meal m) {
- this.menu.add(m);
- System.out.println(m.getName() + " was added to menu, under number: " + m.getNumberOnMenu());
- }
- /**
- * Method used to compare two meals
- *
- * @param a - object of Meal class to compare to
- * @param b - object of Meal class to compare with
- */
- public void compareTwoMeals(Meal a, Meal b) {
- System.out.println("\nMEALS COMPARER");
- System.out.println("+--------------------------------------------------------------------+");
- System.out.printf("%20s %20s %2s %4d %2s %4d %10s", a.getName(), "| " + a.getCuisine(), "| ",
- a.getNumberOnMenu(), "| ", a.getNumberOfLikes(), "| " + a.getType() + "|\n");
- System.out.printf("%20s %20s %2s %4d %2s %4d %10s", b.getName(), "| " + b.getCuisine(), "| ",
- b.getNumberOnMenu(), "| ", b.getNumberOfLikes(), "| " + b.getType() + "|\n");
- System.out.println("+--------------------------------------------------------------------+");
- }
- /**
- * All meals from menu.
- *
- * @param m - list of meals on menu
- */
- public void printMenu(List<Meal> m) {
- System.out.println("\n--------- Menu ---------");
- for (Meal meal : m) {
- System.out.println(meal.getNumberOnMenu() + ". " + meal.getName());
- }
- System.out.println("------------------------\n");
- }
- /**
- * Method used when we open another vegan place just in different location!
- *
- * @return - returns new VeganFoodPlace with the same name but different
- * address
- */
- public VeganFoodPlace openInDifferentPlace() {
- try {
- Object obj = this.clone();
- VeganFoodPlace newPlace = (VeganFoodPlace) obj;
- newPlace.getAddress().setStreet("Another street");
- newPlace.getAddress().setBuildingNumb(77);
- newPlace.getAddress().setHomeNumb(3);
- newPlace.getAddress().setCity("Another city");
- newPlace.getAddress().setCountry("Poland");
- System.out.println("\nOld place: ");
- System.out.println(this.getName() + ": " + this.getType() + " " + this.getAddress().getStreet() + " "
- + this.getAddress().getBuildingNumb() + " " + this.getAddress().getHomeNumb() + " "
- + this.getAddress().getCity() + " " + this.getAddress().getCountry());
- System.out.println("\nNew place: ");
- System.out.println(newPlace.getName() + ": " + newPlace.getType() + " " + newPlace.getAddress().getStreet()
- + " " + newPlace.getAddress().getBuildingNumb() + " " + newPlace.getAddress().getHomeNumb() + " "
- + newPlace.getAddress().getCity() + " " + newPlace.getAddress().getCountry());
- System.out.println();
- return newPlace;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * overriden clone method from Clonable interface
- *
- * @return cloned object
- */
- @Override
- public Object clone() throws CloneNotSupportedException {
- VeganFoodPlace newPlaceOpened = (VeganFoodPlace) super.clone();
- newPlaceOpened.setAddress(new Address(getAddress().getStreet(), getAddress().getBuildingNumb(),
- getAddress().getHomeNumb(), getAddress().getCity(), getAddress().getCountry()));
- return newPlaceOpened;
- }
- /**
- * Method that is used to deserialization
- *
- * @param line
- * @return returns object that was extracted from string
- */
- public Meal deserialization(String line) {
- String[] lineComp = line.split("#");
- Meal mealFromFile;
- mealFromFile = new Meal(lineComp[0], CuisineTypeEnum.valueOf(lineComp[1]), lineComp[2],
- Integer.parseInt(lineComp[3]), Integer.parseInt(lineComp[4]));
- return mealFromFile;
- }
- /**
- * Method that is used to serialization
- *
- * @param meal - object to be serialized
- * @return -returns string that represents line to be written to a file
- */
- public String serialization(Meal meal) {
- String objectAsString = (meal.getName() + "#" + meal.getCuisine() + "#" + meal.getType() + "#"
- + meal.getNumberOnMenu() + "#" + meal.getNumberOfLikes() + "\n");
- return objectAsString;
- }
- /**
- * Method used when the file does not exist. It asks user if he want to
- * create the file.
- *
- * @param path - file path
- * @return - true - file has been created false - file does not been created
- */
- public boolean fileDoesNotExist(String path) {
- File f = new File(path);
- System.out.println("File does not exist. \nDo u want to create it?\n1. YES\n2. NO");
- Scanner s = new Scanner(System.in);
- String decision = s.nextLine();
- switch (decision) {
- case "1":
- try {
- f.createNewFile();
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- break;
- case "2":
- break;
- }
- return false;
- }
- /**
- * Method that is used to write objects of class Meal to the txt file which
- * was introduced by user in configuratoFile
- *
- * @param meal Object of a meal class to be written into the file
- * @param filePath File path that is destination to save an object
- */
- public synchronized void writeToFileMealText(Meal meal, String filePath) {
- try (FileOutputStream out = new FileOutputStream(filePath, true);
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));) {
- FileLock lock = out.getChannel().tryLock();
- if (null != lock) {
- String line = serialization(meal);
- bw.write(line);
- TimeUnit.SECONDS.sleep(10);
- lock.release();
- } else {
- System.out.println("\nYou are trying to write to the text file, but it is in use, try later.\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- /**
- * Method that is used to read from a txt file specified by user in
- * configuration file configuratioFile
- *
- * @param path File path that is used as source to read objects from files
- */
- public synchronized boolean readFormFileMealText(String path) {
- File f = new File(path);
- boolean help = true;
- while (help) {
- try (RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
- FileChannel channel = randomAccessFile.getChannel()) {
- FileLock lock = channel.tryLock();
- if (null != lock) {
- if (f.exists()) {
- this.menu.clear();
- try {
- String line = randomAccessFile.readLine();
- while (line != null) {
- this.menu.add(deserialization(line));
- line = randomAccessFile.readLine();
- }
- this.printMenu(this.menu);
- return true;
- } catch (FileNotFoundException e) {
- System.out.println("File that you specified in configuratioFile does not exist.");
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- } else {
- boolean wasCreated = fileDoesNotExist(path);
- if (!wasCreated) {
- help = false;
- }
- }
- lock.release();
- } else {
- System.out.println("\nYou are trying to read from the text file, but it is in use, try later.\n");
- help = false;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
- /**
- * Method that is used to write objects of class Meal to the binary file
- * which was introduced by user in configuratoFile
- *
- * @param meal Object of a meal class to be written into the file
- * @param filePath File path that is destination to save an object
- */
- public synchronized void writeToFileMealBinary(Meal meal, String path) {
- File file = new File(path);
- RandomAccessFile f;
- try {
- f = new RandomAccessFile(path, "rw");
- FileChannel fc = f.getChannel();
- FileLock fileLock = fc.tryLock();
- if (file.exists() == true) {
- if (null != fileLock) {
- try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path, true))) {
- String line = serialization(meal);
- byte[] lineInByte = line.getBytes();
- for (int i = 0; i < lineInByte.length; i++) {
- outputStream.write(lineInByte[i]);
- }
- TimeUnit.SECONDS.sleep(10);
- fileLock.release();
- } catch (IOException ex) {
- ex.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- fileLock.release();
- }
- } else {
- System.out.println("\nYou are trying to write to the binary file, but it is in use, try later.\n");
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * Method that is used to read from a binary file specified by user in
- * configuration file configuratioFile
- *
- * @param path File path that is used as source to read objects from files
- */
- public synchronized void readFormFileMealBinary(String path) {
- File menuFile = new File(path);
- boolean booleanVariable = true;
- while (booleanVariable) {
- try (RandomAccessFile ra = new RandomAccessFile(path, "rw"); FileChannel channel = ra.getChannel();) {
- FileLock lock = channel.tryLock();
- if (lock != null) {
- if (menuFile.exists() == true) {
- this.menu.clear();
- InputStream fileInStream = Channels.newInputStream(ra.getChannel());
- int singleCharInt;
- byte[] byteArray = new byte[(int) menuFile.length()];
- int iterator = 0;
- while ((singleCharInt = fileInStream.read()) != -1) {
- byteArray[iterator] = (byte) singleCharInt;
- iterator++;
- }
- if (byteArray.length != 0) {
- String byteArrToString = new String(byteArray);
- String[] lines = byteArrToString.split("\n");
- for (int i = 0; i < lines.length; i++) {
- this.menu.add(deserialization(lines[i]));
- }
- this.printMenu(this.menu);
- booleanVariable = false;
- } else {
- printMenu(this.menu);
- booleanVariable = false;
- }
- fileInStream.close();
- } else {
- boolean wasCreated = fileDoesNotExist(path);
- if (!wasCreated) {
- booleanVariable = false;
- }
- }
- } else {
- System.out.println("\nYou are trying to read from the binary file, but it is in use, try later.\n");
- booleanVariable = false;
- }
- } catch (FileNotFoundException e) {
- System.out.println("File that you specified in configuratioFile does not exist.");
- booleanVariable = false;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }