Facebook
From Gracious Prairie Dog, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 127
  1. package com.mycompany.vegeapp;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.io.OutputStreamWriter;
  12. import java.io.RandomAccessFile;
  13. import java.nio.channels.Channels;
  14. import java.nio.channels.FileChannel;
  15. import java.nio.channels.FileLock;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.Scanner;
  19. import java.util.concurrent.TimeUnit;
  20. import java.io.Serializable;
  21. import javax.persistence.*;
  22. import lombok.Getter;
  23. import lombok.NoArgsConstructor;
  24. import lombok.Setter;
  25.  
  26. /**
  27.  * Entity class
  28.  *
  29.  * The class represents the vegan food place. It will be somehow the page of a
  30.  * vegan restaurant or coffee. It has its name, type (restaurant/coffee),
  31.  * address and grade which is an average of user marks assigned to the place.
  32.  */
  33. @Entity
  34. @Table(name = "VeganFoodPlace")
  35. @NoArgsConstructor
  36. public class VeganFoodPlace extends TheVeganBase implements Cloneable, Serializable {
  37.  
  38.     @Getter
  39.     @Id
  40.     @GeneratedValue
  41.     private Long id;
  42.  
  43.     @Getter
  44.     @Setter
  45.     private String type;
  46.  
  47.     @Getter
  48.     @Setter
  49.     @OneToOne
  50.     private Address address;
  51.  
  52.     @Getter
  53.     @Setter
  54.     private ArrayList<Meal> menu = new ArrayList<Meal>();
  55.    
  56.     @OneToMany//(mappedBy = "place")
  57.     private List<Meal> meals;
  58.  
  59.     /**
  60.      * Initializes new instance of VeganFoodPlace.
  61.      *
  62.      * @param n - place name
  63.      * @param t - place type coffee or restaurant
  64.      * @param a - place address @see Address
  65.      * @param g - place grade
  66.      * @param numbGrad - number of grades
  67.      */
  68.     public VeganFoodPlace(String n, String t, Address a, double g, int numbGrad) {
  69.         super(n, g, numbGrad);
  70.         this.type = t;
  71.         this.address = a;
  72.     }
  73.  
  74.     /**
  75.      * Initializes new instance of VeganFoodPlace.
  76.      *
  77.      * @param n - place name
  78.      * @param t - place type coffee or restaurant
  79.      * @param a - place address @see Address
  80.      */
  81.     public VeganFoodPlace(String n, String t, Address a) {
  82.         super(n, 0.0, 0);
  83.  
  84.         this.type = t;
  85.         this.address = a;
  86.     }
  87.  
  88.     /**
  89.      * An abstract method that have to be implemented. Method used to grade the
  90.      * place.
  91.      *
  92.      * @param g - grade for the place
  93.      */
  94.     @Override
  95.     public void gradeIt(int g) {
  96.         double sum = ((this.getGrade() * this.getNumberOfGrades()) + g);
  97.         this.setNumberOfGrades((this.getNumberOfGrades() + 1));
  98.         this.setGrade((sum / (this.getNumberOfGrades())));
  99.     }
  100.  
  101.     /**
  102.      * An abstract method that have to be implemented. Method used to share with
  103.      * friends opinion about the place.
  104.      *
  105.      * @param v - object of a class TheVeganBase
  106.      * @see TheVeganBase
  107.      */
  108.     @Override
  109.     public void shareWithFriend(TheVeganBase v) {
  110.         System.out.println("That " + this.type + " is soo cool!");
  111.         System.out.println("That is the address: " + this.address);
  112.         System.out.println("Check it out!");
  113.     }
  114.  
  115.     /**
  116.      * Method adds meal to menu
  117.      *
  118.      * @param m - meal to be added to menu
  119.      */
  120.     public void addMealToMenu(Meal m) {
  121.         this.menu.add(m);
  122.         System.out.println(m.getName() + " was added to menu, under number: " + m.getNumberOnMenu());
  123.     }
  124.  
  125.     /**
  126.      * Method used to compare two meals
  127.      *
  128.      * @param a - object of Meal class to compare to
  129.      * @param b - object of Meal class to compare with
  130.      */
  131.     public void compareTwoMeals(Meal a, Meal b) {
  132.         System.out.println("\nMEALS COMPARER");
  133.         System.out.println("+--------------------------------------------------------------------+");
  134.         System.out.printf("%20s %20s %2s %4d %2s %4d %10s", a.getName(), "| " + a.getCuisine(), "| ",
  135.                 a.getNumberOnMenu(), "| ", a.getNumberOfLikes(), "| " + a.getType() + "|\n");
  136.         System.out.printf("%20s %20s %2s %4d %2s %4d %10s", b.getName(), "| " + b.getCuisine(), "| ",
  137.                 b.getNumberOnMenu(), "| ", b.getNumberOfLikes(), "| " + b.getType() + "|\n");
  138.         System.out.println("+--------------------------------------------------------------------+");
  139.     }
  140.  
  141.     /**
  142.      * All meals from menu.
  143.      *
  144.      * @param m - list of meals on menu
  145.      */
  146.     public void printMenu(List<Meal> m) {
  147.         System.out.println("\n--------- Menu ---------");
  148.         for (Meal meal : m) {
  149.             System.out.println(meal.getNumberOnMenu() + ". " + meal.getName());
  150.         }
  151.         System.out.println("------------------------\n");
  152.     }
  153.  
  154.     /**
  155.      * Method used when we open another vegan place just in different location!
  156.      *
  157.      * @return - returns new VeganFoodPlace with the same name but different
  158.      * address
  159.      */
  160.     public VeganFoodPlace openInDifferentPlace() {
  161.         try {
  162.             Object obj = this.clone();
  163.             VeganFoodPlace newPlace = (VeganFoodPlace) obj;
  164.  
  165.             newPlace.getAddress().setStreet("Another street");
  166.             newPlace.getAddress().setBuildingNumb(77);
  167.             newPlace.getAddress().setHomeNumb(3);
  168.             newPlace.getAddress().setCity("Another city");
  169.             newPlace.getAddress().setCountry("Poland");
  170.  
  171.             System.out.println("\nOld place: ");
  172.             System.out.println(this.getName() + ": " + this.getType() + " " + this.getAddress().getStreet() + " "
  173.                     + this.getAddress().getBuildingNumb() + " " + this.getAddress().getHomeNumb() + " "
  174.                     + this.getAddress().getCity() + " " + this.getAddress().getCountry());
  175.             System.out.println("\nNew place: ");
  176.             System.out.println(newPlace.getName() + ": " + newPlace.getType() + " " + newPlace.getAddress().getStreet()
  177.                     + " " + newPlace.getAddress().getBuildingNumb() + " " + newPlace.getAddress().getHomeNumb() + " "
  178.                     + newPlace.getAddress().getCity() + " " + newPlace.getAddress().getCountry());
  179.             System.out.println();
  180.  
  181.             return newPlace;
  182.  
  183.         } catch (Exception e) {
  184.             e.printStackTrace();
  185.         }
  186.         return null;
  187.     }
  188.  
  189.     /**
  190.      * overriden clone method from Clonable interface
  191.      *
  192.      * @return cloned object
  193.      */
  194.     @Override
  195.     public Object clone() throws CloneNotSupportedException {
  196.         VeganFoodPlace newPlaceOpened = (VeganFoodPlace) super.clone();
  197.         newPlaceOpened.setAddress(new Address(getAddress().getStreet(), getAddress().getBuildingNumb(),
  198.                 getAddress().getHomeNumb(), getAddress().getCity(), getAddress().getCountry()));
  199.  
  200.         return newPlaceOpened;
  201.     }
  202.  
  203.     /**
  204.      * Method that is used to deserialization
  205.      *
  206.      * @param line
  207.      * @return returns object that was extracted from string
  208.      */
  209.     public Meal deserialization(String line) {
  210.         String[] lineComp = line.split("#");
  211.         Meal mealFromFile;
  212.         mealFromFile = new Meal(lineComp[0], CuisineTypeEnum.valueOf(lineComp[1]), lineComp[2],
  213.                 Integer.parseInt(lineComp[3]), Integer.parseInt(lineComp[4]));
  214.         return mealFromFile;
  215.     }
  216.  
  217.     /**
  218.      * Method that is used to serialization
  219.      *
  220.      * @param meal - object to be serialized
  221.      * @return -returns string that represents line to be written to a file
  222.      */
  223.     public String serialization(Meal meal) {
  224.         String objectAsString = (meal.getName() + "#" + meal.getCuisine() + "#" + meal.getType() + "#"
  225.                 + meal.getNumberOnMenu() + "#" + meal.getNumberOfLikes() + "\n");
  226.         return objectAsString;
  227.     }
  228.  
  229.     /**
  230.      * Method used when the file does not exist. It asks user if he want to
  231.      * create the file.
  232.      *
  233.      * @param path - file path
  234.      * @return - true - file has been created false - file does not been created
  235.      */
  236.     public boolean fileDoesNotExist(String path) {
  237.         File f = new File(path);
  238.         System.out.println("File does not exist. \nDo u want to create it?\n1. YES\n2. NO");
  239.         Scanner s = new Scanner(System.in);
  240.         String decision = s.nextLine();
  241.         switch (decision) {
  242.             case "1":
  243.                 try {
  244.                     f.createNewFile();
  245.                     return true;
  246.                 } catch (IOException e) {
  247.                     e.printStackTrace();
  248.                 }
  249.                 break;
  250.             case "2":
  251.                 break;
  252.  
  253.         }
  254.         return false;
  255.  
  256.     }
  257.  
  258.     /**
  259.      * Method that is used to write objects of class Meal to the txt file which
  260.      * was introduced by user in configuratoFile
  261.      *
  262.      * @param meal Object of a meal class to be written into the file
  263.      * @param filePath File path that is destination to save an object
  264.      */
  265.     public synchronized void writeToFileMealText(Meal meal, String filePath) {
  266.         try (FileOutputStream out = new FileOutputStream(filePath, true);
  267.                 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));) {
  268.             FileLock lock = out.getChannel().tryLock();
  269.             if (null != lock) {
  270.                 String line = serialization(meal);
  271.                 bw.write(line);
  272.                 TimeUnit.SECONDS.sleep(10);
  273.                 lock.release();
  274.             } else {
  275.                 System.out.println("\nYou are trying to write to the text file, but it is in use, try later.\n");
  276.             }
  277.  
  278.         } catch (IOException e) {
  279.             e.printStackTrace();
  280.         } catch (InterruptedException e) {
  281.             e.printStackTrace();
  282.         }
  283.     }
  284.  
  285.     /**
  286.      * Method that is used to read from a txt file specified by user in
  287.      * configuration file configuratioFile
  288.      *
  289.      * @param path File path that is used as source to read objects from files
  290.      */
  291.     public synchronized boolean readFormFileMealText(String path) {
  292.         File f = new File(path);
  293.         boolean help = true;
  294.         while (help) {
  295.             try (RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
  296.                     FileChannel channel = randomAccessFile.getChannel()) {
  297.                 FileLock lock = channel.tryLock();
  298.                 if (null != lock) {
  299.                     if (f.exists()) {
  300.                         this.menu.clear();
  301.                         try {
  302.                             String line = randomAccessFile.readLine();
  303.                             while (line != null) {
  304.                                 this.menu.add(deserialization(line));
  305.  
  306.                                 line = randomAccessFile.readLine();
  307.                             }
  308.                             this.printMenu(this.menu);
  309.                             return true;
  310.                         } catch (FileNotFoundException e) {
  311.                             System.out.println("File that you specified in configuratioFile does not exist.");
  312.                             e.printStackTrace();
  313.                         } catch (IOException e) {
  314.                             e.printStackTrace();
  315.                         }
  316.                         return false;
  317.                     } else {
  318.                         boolean wasCreated = fileDoesNotExist(path);
  319.                         if (!wasCreated) {
  320.                             help = false;
  321.                         }
  322.                     }
  323.                     lock.release();
  324.                 } else {
  325.                     System.out.println("\nYou are trying to read from the text file, but it is in use, try later.\n");
  326.                     help = false;
  327.                 }
  328.             } catch (IOException e) {
  329.                 e.printStackTrace();
  330.             }
  331.         }
  332.         return false;
  333.     }
  334.  
  335.     /**
  336.      * Method that is used to write objects of class Meal to the binary file
  337.      * which was introduced by user in configuratoFile
  338.      *
  339.      * @param meal Object of a meal class to be written into the file
  340.      * @param filePath File path that is destination to save an object
  341.      */
  342.     public synchronized void writeToFileMealBinary(Meal meal, String path) {
  343.         File file = new File(path);
  344.         RandomAccessFile f;
  345.         try {
  346.             f = new RandomAccessFile(path, "rw");
  347.             FileChannel fc = f.getChannel();
  348.             FileLock fileLock = fc.tryLock();
  349.             if (file.exists() == true) {
  350.                 if (null != fileLock) {
  351.  
  352.                     try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path, true))) {
  353.                         String line = serialization(meal);
  354.                         byte[] lineInByte = line.getBytes();
  355.  
  356.                         for (int i = 0; i < lineInByte.length; i++) {
  357.                             outputStream.write(lineInByte[i]);
  358.                         }
  359.  
  360.                         TimeUnit.SECONDS.sleep(10);
  361.  
  362.                         fileLock.release();
  363.  
  364.                     } catch (IOException ex) {
  365.                         ex.printStackTrace();
  366.                     } catch (InterruptedException e) {
  367.                         e.printStackTrace();
  368.                     } finally {
  369.                         fileLock.release();
  370.                     }
  371.                 } else {
  372.                     System.out.println("\nYou are trying to write to the binary file, but it is in use, try later.\n");
  373.                 }
  374.             }
  375.         } catch (IOException e) {
  376.             e.printStackTrace();
  377.         }
  378.     }
  379.  
  380.     /**
  381.      * Method that is used to read from a binary file specified by user in
  382.      * configuration file configuratioFile
  383.      *
  384.      * @param path File path that is used as source to read objects from files
  385.      */
  386.     public synchronized void readFormFileMealBinary(String path) {
  387.         File menuFile = new File(path);
  388.         boolean booleanVariable = true;
  389.         while (booleanVariable) {
  390.             try (RandomAccessFile ra = new RandomAccessFile(path, "rw"); FileChannel channel = ra.getChannel();) {
  391.                 FileLock lock = channel.tryLock();
  392.                 if (lock != null) {
  393.                     if (menuFile.exists() == true) {
  394.                         this.menu.clear();
  395.                         InputStream fileInStream = Channels.newInputStream(ra.getChannel());
  396.  
  397.                         int singleCharInt;
  398.                         byte[] byteArray = new byte[(int) menuFile.length()];
  399.                         int iterator = 0;
  400.  
  401.                         while ((singleCharInt = fileInStream.read()) != -1) {
  402.                             byteArray[iterator] = (byte) singleCharInt;
  403.                             iterator++;
  404.                         }
  405.  
  406.                         if (byteArray.length != 0) {
  407.                             String byteArrToString = new String(byteArray);
  408.                             String[] lines = byteArrToString.split("\n");
  409.                             for (int i = 0; i < lines.length; i++) {
  410.                                 this.menu.add(deserialization(lines[i]));
  411.                             }
  412.                             this.printMenu(this.menu);
  413.                             booleanVariable = false;
  414.                         } else {
  415.                             printMenu(this.menu);
  416.                             booleanVariable = false;
  417.                         }
  418.  
  419.                         fileInStream.close();
  420.                     } else {
  421.                         boolean wasCreated = fileDoesNotExist(path);
  422.  
  423.                         if (!wasCreated) {
  424.                             booleanVariable = false;
  425.                         }
  426.                     }
  427.                 } else {
  428.                     System.out.println("\nYou are trying to read from the binary file, but it is in use, try later.\n");
  429.                     booleanVariable = false;
  430.                 }
  431.             } catch (FileNotFoundException e) {
  432.                 System.out.println("File that you specified in configuratioFile does not exist.");
  433.  
  434.                 booleanVariable = false;
  435.             } catch (IOException e) {
  436.                 e.printStackTrace();
  437.             }
  438.         }
  439.     }
  440.  
  441. }
  442.