Skip to content
Snippets Groups Projects
Commit 3ae78945 authored by HSoreide's avatar HSoreide
Browse files

File handler reads recipes from file and creates a RecipeRegister

parent 062d2a39
No related branches found
No related tags found
3 merge requests!42Hs frontend recipes,!41Hs frontend recipes,!36Hs rewrite file handling for recipes and ingredients
...@@ -3,6 +3,9 @@ package no.ntnu.idatt1002.demo.data.recipes; ...@@ -3,6 +3,9 @@ package no.ntnu.idatt1002.demo.data.recipes;
import no.ntnu.idatt1002.demo.data.Economics.*; import no.ntnu.idatt1002.demo.data.Economics.*;
import java.io.*; import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner; import java.util.Scanner;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
import java.time.LocalDate; import java.time.LocalDate;
...@@ -10,11 +13,12 @@ import java.time.LocalDate; ...@@ -10,11 +13,12 @@ import java.time.LocalDate;
public class FileHandler { 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 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 date = "date=";
private static final String description = "description="; private static final String description = "description=";
private static final String amount = "amount="; private static final String amount = "amount=";
...@@ -22,12 +26,12 @@ public class FileHandler { ...@@ -22,12 +26,12 @@ public class FileHandler {
private static final String category = "category=";*/ private static final String category = "category=";*/
public static void writeRegister(RecipeRegister recipeRegister) { public static void writeRegister(RecipeRegister recipeRegister, String title) {
if(recipeRegister == null) { if(recipeRegister == null) {
throw new IllegalArgumentException("Only a valid register object can be written to file."); 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) -> recipeRegister.getRecipes().forEach((recipe) ->
{ {
try { try {
...@@ -52,11 +56,6 @@ public class FileHandler { ...@@ -52,11 +56,6 @@ public class FileHandler {
.append("\n") .append("\n")
.append(recipe.getInstructions()) .append(recipe.getInstructions())
.append("\n\n"); .append("\n\n");
/* story.getPassages().values().forEach((p) -> {
sb.append(formatPassage(p))
.append("\n\n");
});*/
return sb; return sb;
} }
...@@ -69,159 +68,82 @@ public class FileHandler { ...@@ -69,159 +68,82 @@ public class FileHandler {
.append(" | ") .append(" | ")
.append(ingredient.getAmount()) .append(ingredient.getAmount())
.append(" | ") .append(" | ")
.append(ingredient.getUnit()); .append(ingredient.getUnit())
.append("\n");
}); });
return sb; return sb;
} }
//TODO: Midlertidig for testing. //TODO: Midlertidig for testing.
public static void readToTerminal(String title) throws FileNotFoundException { 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); Scanner sc = new Scanner(file);
while(sc.hasNext()) { while(sc.hasNext()) {
System.out.println(sc.nextLine()); 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());
}
}
*/ public static RecipeRegister readRecipeRegister(String title) throws FileNotFoundException {
/** File file = new File(filePath + title + fileType);
* Method for checking if a .register file is empty.
* RecipeRegister register = new RecipeRegister();
* @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;
}
}
}
*/ try (Scanner sc = new Scanner(file)) {
/** sc.useDelimiter("#");
* 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))) {
String line; String line;
String nextLine = br.readLine();
while ((line = nextLine) != null) { while (sc.hasNext()) {
nextLine = br.readLine(); line = sc.next();
if(line.startsWith(FileHandling.date)) { if(!line.isBlank()) {
date = LocalDate.parse(line.replace(FileHandling.date, "")); register.addRecipe(readRecipe(line));
} 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 = "";
} }
} }
}catch(FileNotFoundException e) {
System.out.println("The file was not found.");
return null;
} }
return incomeRegister;
return register;
} }
*/ public static Recipe readRecipe(String readRecipe) {
/**
* Method for reading (getting) an ExpenseRegister from a file. Scanner sc = new Scanner(readRecipe);
*
* @param fileTitle the name of the file you want to read from. Recipe recipe;
* @return the ExpenseRegister from the file. String instructions = "None";
* @throws IOException if an input or output exception occurred String recipeName = sc.nextLine().strip();
*//* StringBuilder sb = new StringBuilder();
public ExpenseRegister readExpenseRegisterFromFile(String fileTitle) throws IOException {
ExpenseRegister expenseRegister = new ExpenseRegister(); String line;
LocalDate date = null; recipe = new Recipe(recipeName, instructions);
String description = "";
double amount = 0; while (sc.hasNextLine()) {
boolean reoccuring = false; line = sc.nextLine();
ExpenseCategory expenseCategory = null;
try (BufferedReader br = new BufferedReader(new FileReader(filePath + fileTitle + fileType))) { if(line.startsWith("-")) {
String line; String[] ingredientParts = line.split("\\|");
String nextLine = br.readLine();
while ((line = nextLine) != null) { FoodItem ingredientType = FoodItem.valueOf(ingredientParts[0].replaceFirst("-", "").strip());
nextLine = br.readLine(); double ingredientAmount = Double.parseDouble(ingredientParts[1].strip());
if (line.startsWith(FileHandling.date)) { MeasuringUnit ingredientUnit = MeasuringUnit.valueOf(ingredientParts[2].strip());
date = LocalDate.parse(line.replace(FileHandling.date, ""));
} else if (line.startsWith(FileHandling.description)) { recipe.addIngredient(ingredientType, ingredientAmount, ingredientUnit);
description = line.replace(FileHandling.description, "");
} else if (line.startsWith(FileHandling.amount)) { } else {
amount = Double.parseDouble(line.replace(FileHandling.amount, "")); if(!line.isBlank()) {
} else if (line.startsWith(FileHandling.isRecurring)) { sb.append(line).append("\n");
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 = "";
} }
} }
} }
return expenseRegister; recipe.setInstructions(String.valueOf(sb));
}
}
*/
return recipe;
}
} }
# 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
...@@ -38,10 +38,31 @@ class FileHandlerTest { ...@@ -38,10 +38,31 @@ class FileHandlerTest {
@Test @Test
@DisplayName("Write recipe register correctly to file as text.") @DisplayName("Write recipe register correctly to file as text.")
void writeRecipeRegisterToFile() throws FileNotFoundException { void writeRecipeRegisterToFile() throws FileNotFoundException {
assertAll(() -> FileHandler.writeRegister(recipeRegister)); assertAll(() -> FileHandler.writeRegister(recipeRegister, "RecipeRegister"));
FileHandler.readToTerminal("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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment