From 3ae78945eb11bb66528b96a6d483be61f519ea1f Mon Sep 17 00:00:00 2001 From: HSoreide <sofie.scisly@gmail.com> Date: Sat, 15 Apr 2023 19:34:33 +0200 Subject: [PATCH] File handler reads recipes from file and creates a RecipeRegister --- .../demo/data/recipes/FileHandler.java | 194 ++++++------------ .../recipes/testReadRegisterFromFile.register | 23 +++ .../demo/data/recipes/FileHandlerTest.java | 23 ++- 3 files changed, 103 insertions(+), 137 deletions(-) create mode 100644 src/main/resources/recipes/testReadRegisterFromFile.register diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java index 6aa446a2..5d8f0989 100644 --- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java +++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java @@ -3,6 +3,9 @@ package no.ntnu.idatt1002.demo.data.recipes; import no.ntnu.idatt1002.demo.data.Economics.*; import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Scanner; import java.nio.file.FileSystems; import java.time.LocalDate; @@ -10,11 +13,12 @@ import java.time.LocalDate; public class FileHandler { - private static final String filePath = FileSystems.getDefault().getPath("src", "main", "resources", "recipes").toString(); + // private static final String filePath = FileSystems.getDefault().getPath("src", "main", "resources", "recipes").toString(); private static final String fileType = ".register"; + private static final String registerName = "RecipeRegister"; - //private static final String filePath = "src/main/resources/recipes/"; + private static final String filePath = "src/main/resources/recipes/"; /* private static final String date = "date="; private static final String description = "description="; private static final String amount = "amount="; @@ -22,12 +26,12 @@ public class FileHandler { private static final String category = "category=";*/ - public static void writeRegister(RecipeRegister recipeRegister) { + public static void writeRegister(RecipeRegister recipeRegister, String title) { if(recipeRegister == null) { throw new IllegalArgumentException("Only a valid register object can be written to file."); } - try( FileWriter fileWriter = new FileWriter(filePath + "RecipeRegister" + fileType);) { + try( FileWriter fileWriter = new FileWriter(filePath + title + fileType);) { recipeRegister.getRecipes().forEach((recipe) -> { try { @@ -52,11 +56,6 @@ public class FileHandler { .append("\n") .append(recipe.getInstructions()) .append("\n\n"); - -/* story.getPassages().values().forEach((p) -> { - sb.append(formatPassage(p)) - .append("\n\n"); - });*/ return sb; } @@ -69,159 +68,82 @@ public class FileHandler { .append(" | ") .append(ingredient.getAmount()) .append(" | ") - .append(ingredient.getUnit()); + .append(ingredient.getUnit()) + .append("\n"); }); return sb; } - //TODO: Midlertidig for testing. public static void readToTerminal(String title) throws FileNotFoundException { - File file = new File(filePath + title.replace(" ","_") + fileType); + File file = new File(filePath + title + fileType); Scanner sc = new Scanner(file); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } -/* - public <T extends Item>void writeItemRegisterToFile(final ItemRegister<T> itemRegister, String fileTitle) throws IOException { - try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath + fileTitle + fileType))) { - if (itemRegister.isEmpty()){ - bw.write(""); - } else{ - bw.write(itemRegister.toString()); - } - } catch (IOException ex) { - throw new IOException("Error writing story to file: " + ex.getMessage()); - } - } - */ -/** - * Method for checking if a .register file is empty. - * - * @param fileTitle the name of the file you want to check - * @return true or false depending on if file is empty. - * @throws IOException if an input or output exception occurred. - *//* - - public boolean isEmpty(String fileTitle) throws IOException { - try (BufferedReader br = new BufferedReader(new FileReader(filePath + fileTitle + fileType))) { - if (br.readLine() == null) { - return true; - } else { - return false; - } - } - } + public static RecipeRegister readRecipeRegister(String title) throws FileNotFoundException { + File file = new File(filePath + title + fileType); + + RecipeRegister register = new RecipeRegister(); - */ -/** - * Method for reading (getting) an IncomeRegister from a file. - * - * @param fileTitle the name of the file you want to read from. - * @return the IncomeRegister from the file. - * @throws IOException if an input or output exception occurred. - *//* - - public IncomeRegister readIncomeRegisterFromFile(String fileTitle) throws IOException { - IncomeRegister incomeRegister = new IncomeRegister(); - LocalDate date = null; - String description = ""; - double amount = 0; - boolean reoccuring = false; - IncomeCategory incomeCategory = null; - try (BufferedReader br = new BufferedReader(new FileReader(filePath + fileTitle + fileType))) { + try (Scanner sc = new Scanner(file)) { + sc.useDelimiter("#"); String line; - String nextLine = br.readLine(); - while ((line = nextLine) != null) { - nextLine = br.readLine(); - if(line.startsWith(FileHandling.date)) { - date = LocalDate.parse(line.replace(FileHandling.date, "")); - } else if (line.startsWith(FileHandling.description)) { - description = line.replace(FileHandling.description,""); - } else if (line.startsWith(FileHandling.amount)) { - amount = Double.parseDouble(line.replace(FileHandling.amount,"")); - } else if (line.startsWith(FileHandling.isRecurring)) { - reoccuring = line.replace(FileHandling.isRecurring,"").equals("Recurring"); - } else if (line.startsWith(FileHandling.category)) { - line = line.replace(FileHandling.category,""); - incomeCategory = switch (line) { - case "GIFT" -> IncomeCategory.GIFT; - case "STUDENT_LOAN" -> IncomeCategory.STUDENT_LOAN; - default -> IncomeCategory.SALARY; - }; - } if(line.isEmpty() || (nextLine == null)) { - if(description.equals("")){ - incomeRegister.addItem(new Income(amount, reoccuring, incomeCategory, date)); - } else{ - incomeRegister.addItem(new Income(description, amount, reoccuring, incomeCategory, date)); - } - description = ""; + + while (sc.hasNext()) { + line = sc.next(); + if(!line.isBlank()) { + register.addRecipe(readRecipe(line)); } } + }catch(FileNotFoundException e) { + System.out.println("The file was not found."); + return null; } - return incomeRegister; + + return register; } - */ -/** - * Method for reading (getting) an ExpenseRegister from a file. - * - * @param fileTitle the name of the file you want to read from. - * @return the ExpenseRegister from the file. - * @throws IOException if an input or output exception occurred - *//* - - public ExpenseRegister readExpenseRegisterFromFile(String fileTitle) throws IOException { - ExpenseRegister expenseRegister = new ExpenseRegister(); - LocalDate date = null; - String description = ""; - double amount = 0; - boolean reoccuring = false; - ExpenseCategory expenseCategory = null; - try (BufferedReader br = new BufferedReader(new FileReader(filePath + fileTitle + fileType))) { - String line; - String nextLine = br.readLine(); - while ((line = nextLine) != null) { - nextLine = br.readLine(); - if (line.startsWith(FileHandling.date)) { - date = LocalDate.parse(line.replace(FileHandling.date, "")); - } else if (line.startsWith(FileHandling.description)) { - description = line.replace(FileHandling.description, ""); - } else if (line.startsWith(FileHandling.amount)) { - amount = Double.parseDouble(line.replace(FileHandling.amount, "")); - } else if (line.startsWith(FileHandling.isRecurring)) { - reoccuring = line.replace(FileHandling.isRecurring, "").equals("Recurring"); - } else if (line.startsWith(FileHandling.category)) { - line = line.replace(FileHandling.category, ""); - expenseCategory = switch (line) { - case "FOOD" -> ExpenseCategory.FOOD; - case "CLOTHES" -> ExpenseCategory.CLOTHES; - case "BOOKS" -> ExpenseCategory.BOOKS; - default -> ExpenseCategory.OTHER; - }; - } - if (line.isEmpty() || (nextLine == null)) { - if (description.equals("")) { - expenseRegister.addItem(new Expense(amount, reoccuring, expenseCategory, date)); - } else { - expenseRegister.addItem(new Expense(description, amount, reoccuring, expenseCategory, date)); - } - description = ""; + public static Recipe readRecipe(String readRecipe) { + + Scanner sc = new Scanner(readRecipe); + + Recipe recipe; + String instructions = "None"; + String recipeName = sc.nextLine().strip(); + StringBuilder sb = new StringBuilder(); + + + String line; + recipe = new Recipe(recipeName, instructions); + + while (sc.hasNextLine()) { + line = sc.nextLine(); + + if(line.startsWith("-")) { + String[] ingredientParts = line.split("\\|"); + + FoodItem ingredientType = FoodItem.valueOf(ingredientParts[0].replaceFirst("-", "").strip()); + double ingredientAmount = Double.parseDouble(ingredientParts[1].strip()); + MeasuringUnit ingredientUnit = MeasuringUnit.valueOf(ingredientParts[2].strip()); + + recipe.addIngredient(ingredientType, ingredientAmount, ingredientUnit); + + } else { + if(!line.isBlank()) { + sb.append(line).append("\n"); } } } - return expenseRegister; - } -} -*/ - - + recipe.setInstructions(String.valueOf(sb)); + return recipe; + } } diff --git a/src/main/resources/recipes/testReadRegisterFromFile.register b/src/main/resources/recipes/testReadRegisterFromFile.register new file mode 100644 index 00000000..1a66a200 --- /dev/null +++ b/src/main/resources/recipes/testReadRegisterFromFile.register @@ -0,0 +1,23 @@ +# Meat, cheese and potatoes +- MINCED_MEAT | 500.0 | GR +- POTATO | 750.0 | GR +- YELLOW_CHEESE | 2.0 | DL + +Instructions must be written continuously in one line. No line shifts. +Testing another line of instructions! + +# Meat, cheese and lemons +- MINCED_MEAT | 500.0 | GR +- LEMON | 750.0 | GR +- YELLOW_CHEESE | 2.0 | DL + +Instructions + + + +# Another recipe added for testing +- ONION | 5.0 | PC +- LEMON | 750.0 | GR +- POTATO | 10.0 | PC + +Instructions for another dish. \ No newline at end of file diff --git a/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java b/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java index caba974b..bb6dc460 100644 --- a/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java +++ b/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java @@ -38,10 +38,31 @@ class FileHandlerTest { @Test @DisplayName("Write recipe register correctly to file as text.") void writeRecipeRegisterToFile() throws FileNotFoundException { - assertAll(() -> FileHandler.writeRegister(recipeRegister)); + assertAll(() -> FileHandler.writeRegister(recipeRegister, "RecipeRegister")); FileHandler.readToTerminal("RecipeRegister"); } + @Test + @DisplayName("Read recipe register correctly from file to object.") + void readRecipeRegisterFromFile() throws FileNotFoundException { + // Read test register into a register object. + // Write the object and print to terminal. + + assertAll(() -> FileHandler.readRecipeRegister("testReadRegisterFromFile")); + + RecipeRegister registerReadFromTestFile = FileHandler.readRecipeRegister("testReadRegisterFromFile"); + + // Write the register object to file and read to terminal: + FileHandler.writeRegister(registerReadFromTestFile, "ReadAndWrittenRegister"); + + FileHandler.readToTerminal("ReadAndWrittenRegister"); + + // Another iteration to spot accumulating spaces or new lines. + RecipeRegister secondRegister = FileHandler.readRecipeRegister("ReadAndWrittenRegister"); + FileHandler.writeRegister(secondRegister, "secondGeneration"); + + } + } \ No newline at end of file -- GitLab