From 18756cd64106b602bfee3de7e48f94dfe45fabe4 Mon Sep 17 00:00:00 2001 From: Remy9926 <95456114+Remy9926@users.noreply.github.com> Date: Tue, 14 Nov 2023 18:25:31 +0800 Subject: [PATCH] Bug fixes (#100) v2.1 --- src/main/java/seedu/duke/Duke.java | 36 +--- .../java/seedu/duke/commands/HelpCommand.java | 6 +- .../commands/goal/AchieveGoalCommand.java | 21 -- .../commands/goal/AchievementCommand.java | 21 -- .../duke/commands/goal/DeleteGoalCommand.java | 31 --- .../seedu/duke/commands/goal/GoalCommand.java | 50 ----- .../duke/commands/goal/ViewGoalCommand.java | 19 -- .../seedu/duke/commands/meal/AddCommand.java | 11 +- .../duke/commands/meal/DeleteCommand.java | 13 -- .../seedu/duke/commands/meal/ListCommand.java | 55 ----- .../seedu/duke/commands/meal/MealCommand.java | 6 - src/main/java/seedu/duke/data/Date.java | 2 +- src/main/java/seedu/duke/data/DateTime.java | 2 +- src/main/java/seedu/duke/data/GoalList.java | 193 ------------------ src/main/java/seedu/duke/data/meal/Meal.java | 22 -- src/main/java/seedu/duke/parser/Parser.java | 23 +-- .../seedu/duke/storagefile/AchmStorage.java | 74 ------- .../seedu/duke/storagefile/DataManager.java | 181 ---------------- .../seedu/duke/storagefile/GoalStorage.java | 112 ---------- src/main/java/seedu/duke/ui/TextUi.java | 80 +------- .../java/seedu/duke/parser/ParserTest.java | 16 -- 21 files changed, 15 insertions(+), 959 deletions(-) delete mode 100644 src/main/java/seedu/duke/commands/goal/GoalCommand.java delete mode 100644 src/main/java/seedu/duke/commands/meal/ListCommand.java delete mode 100644 src/main/java/seedu/duke/data/GoalList.java delete mode 100644 src/main/java/seedu/duke/data/meal/Meal.java delete mode 100644 src/main/java/seedu/duke/storagefile/AchmStorage.java delete mode 100644 src/main/java/seedu/duke/storagefile/DataManager.java delete mode 100644 src/main/java/seedu/duke/storagefile/GoalStorage.java diff --git a/src/main/java/seedu/duke/Duke.java b/src/main/java/seedu/duke/Duke.java index 9f2a1baa5b..7cb3284a65 100644 --- a/src/main/java/seedu/duke/Duke.java +++ b/src/main/java/seedu/duke/Duke.java @@ -1,19 +1,10 @@ package seedu.duke; -import java.util.ArrayList; - import seedu.duke.commands.Command; import seedu.duke.commands.CommandResult; import seedu.duke.commands.ExitCommand; -import seedu.duke.commands.meal.MealCommand; -import seedu.duke.data.GoalList; -import seedu.duke.data.meal.Meal; -import seedu.duke.exerciselog.Exercise; import seedu.duke.parser.Parser; import seedu.duke.exerciselog.Log; -import seedu.duke.storagefile.AchmStorage; -import seedu.duke.storagefile.DataManager; -import seedu.duke.storagefile.GoalStorage; import seedu.duke.ui.TextUi; import seedu.duke.storagefile.ExerciseLogStorage; @@ -27,13 +18,8 @@ public class Duke { * Version info of the program. */ public static final String VERSION = "Version-2.1"; - public static GoalList goals = new GoalList(); - public static GoalList achievedGoals = new GoalList(); public static Log exerciseLog = new Log(); public static ExerciseLogStorage exerciseLogStorage; - public static GoalStorage goalStorage; - public static AchmStorage achmStorage; - private static ArrayList meals = new ArrayList(); public static TextUi ui; private final String dirPath = "data"; private final String exerciseLogFilePath = "./data/ExerciseLog.txt"; @@ -63,21 +49,10 @@ public void run(String[] launchArgs) { */ private void start(String[] launchArgs) { try { - this.ui = new TextUi(); - exerciseLogStorage = StorageFile.initializeStorage(dirPath, exerciseLogFilePath); + ui = new TextUi(); + exerciseLogStorage = ExerciseLogStorage.initializeStorage(dirPath, exerciseLogFilePath); exerciseLogStorage.checkForLogTextFile(exerciseLog); - goalStorage = GoalStorage.initializeGoalStorage(dirPath, goalFilePath); - goalStorage.restoreGoalRecord(); - achmStorage = AchmStorage.initializeGoalStorage(dirPath, achmFilePath); - achmStorage.restoreGoalRecord(); ui.showWelcomeMessage(VERSION, "storage.getPath()"); - DataManager.setRelativePath(mealSavePath); - String dataJson = DataManager.readData(); - ArrayList data = DataManager.convertFromJsonToMealList(dataJson); - if (data != null) { - meals = data; - } - MealCommand.setMeals(meals); } catch (Exception e) { // TODO: change to specific storage exceptions later ui.showInitFailedMessage(); throw new RuntimeException(e); @@ -89,11 +64,6 @@ private void start(String[] launchArgs) { */ private void exit() { ui.showGoodbyeMessage(); - try { - DataManager.saveData(DataManager.convertToJson(meals)); - } catch (Exception exception) { - ui.showToUser(exception.toString()); - } System.exit(0); } @@ -131,10 +101,8 @@ private void runCommandLoopUntilExitCommand() { private CommandResult executeCommand(Command command) { try { CommandResult result = command.execute(); - // storage.save(addressBook); return result; } catch (Exception e) { - ui.showToUser(e.getMessage()); throw new RuntimeException(e); } } diff --git a/src/main/java/seedu/duke/commands/HelpCommand.java b/src/main/java/seedu/duke/commands/HelpCommand.java index 39bc7615b8..95de1ea029 100644 --- a/src/main/java/seedu/duke/commands/HelpCommand.java +++ b/src/main/java/seedu/duke/commands/HelpCommand.java @@ -2,7 +2,6 @@ import seedu.duke.commands.goal.AchieveGoalCommand; import seedu.duke.commands.goal.AchievementCommand; -import seedu.duke.commands.goal.GoalCommand; import seedu.duke.commands.goal.ViewGoalCommand; import seedu.duke.commands.logcommands.LogCommand; import seedu.duke.commands.logcommands.ViewLogCommand; @@ -21,15 +20,14 @@ public class HelpCommand extends Command { @Override public CommandResult execute() { - String HelpMsg = HelpCommand.MESSAGE_USAGE + "\n"; + String helpMsg = HelpCommand.MESSAGE_USAGE + "\n"; return new CommandResult( - HelpMsg + helpMsg + "\n" + LogCommand.MESSAGE_USAGE + "\n" + DeleteLogCommand.MESSAGE_USAGE + "\n" + UpdateLogCommand.MESSAGE_USAGE + "\n" + ViewLogCommand.MESSAGE_USAGE - + "\n" + GoalCommand.MESSAGE_USAGE + "\n" + DeleteLogCommand.MESSAGE_USAGE + "\n" + ViewGoalCommand.MESSAGE_USAGE + "\n" + AchieveGoalCommand.MESSAGE_USAGE diff --git a/src/main/java/seedu/duke/commands/goal/AchieveGoalCommand.java b/src/main/java/seedu/duke/commands/goal/AchieveGoalCommand.java index f08530b1dd..d801a612dc 100644 --- a/src/main/java/seedu/duke/commands/goal/AchieveGoalCommand.java +++ b/src/main/java/seedu/duke/commands/goal/AchieveGoalCommand.java @@ -1,10 +1,6 @@ package seedu.duke.commands.goal; import seedu.duke.commands.Command; -import seedu.duke.commands.CommandResult; - -import seedu.duke.data.GoalList; -import seedu.duke.data.exception.IncorrectFormatException; public class AchieveGoalCommand extends Command { public static final String COMMAND_WORD = "achieve"; @@ -15,21 +11,4 @@ public class AchieveGoalCommand extends Command { public AchieveGoalCommand(String cmd) { super(cmd); } - - @Override - public CommandResult execute() { - try { - feedbackToUser = GoalList.achieveGoal(this.userCommand); - - } catch (NumberFormatException nfe) { - feedbackToUser = "Please use a valid arabic number as index."; - } catch (IncorrectFormatException ife) { - feedbackToUser = ife.getMessage(); - } catch (Exception e) { - feedbackToUser = "Something went wrong, please try again."; - } - - return new CommandResult(feedbackToUser); - } - } diff --git a/src/main/java/seedu/duke/commands/goal/AchievementCommand.java b/src/main/java/seedu/duke/commands/goal/AchievementCommand.java index a35d60a779..9b36bfb645 100644 --- a/src/main/java/seedu/duke/commands/goal/AchievementCommand.java +++ b/src/main/java/seedu/duke/commands/goal/AchievementCommand.java @@ -1,10 +1,6 @@ package seedu.duke.commands.goal; import seedu.duke.commands.Command; -import seedu.duke.commands.CommandResult; -import seedu.duke.data.GoalList; -import seedu.duke.data.exception.IncorrectFormatException; -import seedu.duke.ui.TextUi; public class AchievementCommand extends Command { public static final String COMMAND_WORD = "achievement"; @@ -15,21 +11,4 @@ public class AchievementCommand extends Command { public AchievementCommand(String cmd) { super(cmd); } - - @Override - public CommandResult execute() { - try { - GoalList.verifyViewAchievementInput(this.userCommand); - feedbackToUser = TextUi.showAchievement(); - - } catch (IncorrectFormatException ife) { - feedbackToUser = ife.getMessage(); - } catch (Exception e) { - feedbackToUser = "Something went wrong, please try again."; - } - - return new CommandResult(feedbackToUser); - } - - } diff --git a/src/main/java/seedu/duke/commands/goal/DeleteGoalCommand.java b/src/main/java/seedu/duke/commands/goal/DeleteGoalCommand.java index 9e2c36cd48..c552ad4a24 100644 --- a/src/main/java/seedu/duke/commands/goal/DeleteGoalCommand.java +++ b/src/main/java/seedu/duke/commands/goal/DeleteGoalCommand.java @@ -1,11 +1,6 @@ package seedu.duke.commands.goal; import seedu.duke.commands.Command; -import seedu.duke.commands.CommandResult; -import seedu.duke.data.GoalList; -import seedu.duke.data.exception.IncorrectFormatException; - -import java.io.IOException; public class DeleteGoalCommand extends Command { public static final String COMMAND_WORD = "deleteg"; @@ -16,30 +11,4 @@ public class DeleteGoalCommand extends Command { public DeleteGoalCommand(String cmd) { super(cmd); } - - /** - * execute to remove a goal object from global goal list, by indexing - * If failed to delete a goal, tells user the specific problem. - * @return feedback to user of either success or fail - */ - @Override - public CommandResult execute() { - try { - feedbackToUser = GoalList.deleteGoal(this.userCommand); - - } catch (NumberFormatException nfe) { - feedbackToUser = "Please input a valid number for delete index."; - } catch (IncorrectFormatException ife) { - feedbackToUser = ife.getMessage(); - } catch (IOException io) { - feedbackToUser = "Failed to save data. Please check the output file and restart the app."; - } catch (Exception e) { - feedbackToUser = "Something went wrong, please try again."; - } - - - return new CommandResult(feedbackToUser); - } - - } diff --git a/src/main/java/seedu/duke/commands/goal/GoalCommand.java b/src/main/java/seedu/duke/commands/goal/GoalCommand.java deleted file mode 100644 index 73f9c6d1a8..0000000000 --- a/src/main/java/seedu/duke/commands/goal/GoalCommand.java +++ /dev/null @@ -1,50 +0,0 @@ -package seedu.duke.commands.goal; - -import seedu.duke.Duke; -import seedu.duke.commands.Command; -import seedu.duke.commands.CommandResult; -import seedu.duke.data.GoalList; -import seedu.duke.data.exception.IncorrectFormatException; - -import java.io.IOException; - - -public class GoalCommand extends Command { - - public static final String COMMAND_WORD = "set"; - public static final String MESSAGE_USAGE = COMMAND_WORD + ": Add a new goal into the goal list\n" - + "\tExample: " + COMMAND_WORD + " 123 on 18/12/2023"; - public String feedbackToUser; - - - public GoalCommand(String cmd) { - super(cmd); - } - - /** - * The execution of goalCommand new a goal record into the goal list. - * If error occurs in creating goal record, possibly includes - * incorrect format of command or invalid number is input. - * @return result of adding goal successfully message - */ - @Override - public CommandResult execute() { - try { - feedbackToUser = GoalList.addGoal(this.userCommand, Duke.goalList, Duke.goalStorage); - } catch (IncorrectFormatException ife) { - feedbackToUser = ife.getMessage(); - } catch (NumberFormatException nfe) { - feedbackToUser = "Please input a valid number for calories."; - } catch (IOException io) { - feedbackToUser = "Failed to save data. Please check the output file and restart the app."; - } catch (Exception e) { - feedbackToUser = "Something went wrong, please try again."; - } - - - - - return new CommandResult(feedbackToUser); - } - -} diff --git a/src/main/java/seedu/duke/commands/goal/ViewGoalCommand.java b/src/main/java/seedu/duke/commands/goal/ViewGoalCommand.java index d000aade58..143e94f61a 100644 --- a/src/main/java/seedu/duke/commands/goal/ViewGoalCommand.java +++ b/src/main/java/seedu/duke/commands/goal/ViewGoalCommand.java @@ -1,10 +1,6 @@ package seedu.duke.commands.goal; import seedu.duke.commands.Command; -import seedu.duke.commands.CommandResult; -import seedu.duke.data.GoalList; -import seedu.duke.data.exception.IncorrectFormatException; -import seedu.duke.ui.TextUi; public class ViewGoalCommand extends Command { @@ -16,19 +12,4 @@ public class ViewGoalCommand extends Command { public ViewGoalCommand(String cmd) { super(cmd); } - - @Override - public CommandResult execute() { - try { - GoalList.verifyViewGoalInput(this.userCommand); - feedbackToUser = TextUi.showGoalList(); - } catch (IncorrectFormatException ife) { - feedbackToUser = ife.getMessage(); - } catch (Exception e) { - feedbackToUser = "Something went wrong, please try again."; - } - - return new CommandResult(feedbackToUser); - } - } diff --git a/src/main/java/seedu/duke/commands/meal/AddCommand.java b/src/main/java/seedu/duke/commands/meal/AddCommand.java index e6eb8b73cd..e0fb1d5ea1 100644 --- a/src/main/java/seedu/duke/commands/meal/AddCommand.java +++ b/src/main/java/seedu/duke/commands/meal/AddCommand.java @@ -1,11 +1,8 @@ package seedu.duke.commands.meal; -import seedu.duke.commands.CommandResult; -import seedu.duke.data.meal.Meal; import seedu.duke.data.Date; import java.util.List; -import java.util.Locale.Category; public class AddCommand extends MealCommand { public static final String COMMAND_WORD = "meal_add"; @@ -25,13 +22,7 @@ public AddCommand(List arguments) throws Exception { if (arguments.size() >= 4) { time = new Date(arguments.get(3)); } else { - time = Date.Now(); + time = Date.now(); } } - - @Override - public CommandResult execute() throws Exception { - meals.add(new Meal(name, calories, category, time)); - return new CommandResult("Successfully add meal " + meals.get(meals.size() - 1) + "!"); - } } diff --git a/src/main/java/seedu/duke/commands/meal/DeleteCommand.java b/src/main/java/seedu/duke/commands/meal/DeleteCommand.java index d00b83fb7d..3b28126710 100644 --- a/src/main/java/seedu/duke/commands/meal/DeleteCommand.java +++ b/src/main/java/seedu/duke/commands/meal/DeleteCommand.java @@ -1,7 +1,5 @@ package seedu.duke.commands.meal; -import seedu.duke.commands.CommandResult; - import java.util.List; public class DeleteCommand extends MealCommand { @@ -18,15 +16,4 @@ public DeleteCommand(List arguments) throws Exception { throw new Exception("Invalid index!"); } } - - @Override - public CommandResult execute() throws Exception { - if (meals.size() <= index) { - return new CommandResult("Exceeded index!"); - } - CommandResult result = new CommandResult( - "Successfully delete meal at index " + index + "!\n" + meals.get(index)); - meals.remove(index); - return result; - } } diff --git a/src/main/java/seedu/duke/commands/meal/ListCommand.java b/src/main/java/seedu/duke/commands/meal/ListCommand.java deleted file mode 100644 index b01ff00a2f..0000000000 --- a/src/main/java/seedu/duke/commands/meal/ListCommand.java +++ /dev/null @@ -1,55 +0,0 @@ -package seedu.duke.commands.meal; - -import seedu.duke.commands.CommandResult; -import seedu.duke.data.meal.Category; -import seedu.duke.data.meal.CategoryParser; -import seedu.duke.data.meal.Meal; - -import java.util.ArrayList; -import java.util.List; - -public class ListCommand extends MealCommand { - public static final String COMMAND_WORD = "meal_list"; - public static final String MESSAGE_USAGE = COMMAND_WORD + ": List all the meals that have been recorded.\n" - + "Example: " + COMMAND_WORD; - private static final int[] validArgumentAmounts = new int[] { 0, 1 }; - private final Category category; - - public ListCommand(List arguments) throws Exception { - checkArgument(arguments, validArgumentAmounts); - if (arguments.size() == 1 && arguments.get(0) != "") { - category = CategoryParser.Parse(arguments.get(0)); - } else { - category = null; - } - } - - @Override - public CommandResult execute() throws Exception { - ArrayList selectedMeals = new ArrayList(); - for (int i = 0; i < meals.size(); i++) { - Meal meal = meals.get(i); - if (category == null || meal.category == category) { - selectedMeals.add(meal); - } - } - - if (selectedMeals.size() == 0) { - if (category == null) { - return new CommandResult("The meal list is empty!"); - } - return new CommandResult("The selected meal list with category '" + category.toString() + "' is empty!"); - } - String listString = ""; - int total = 0; - for (int i = 0; i < selectedMeals.size(); i++) { - Meal meal = selectedMeals.get(i); - listString += "\n" + (i + 1) + "." + meal.toString(); - total += meal.calories; - } - listString += "\nTotal calories: " + total; - return new CommandResult( - (category == null ? "Here's the meal list:" - : "Here's the selected meal list with category '" + category.toString() + "':") + listString); - } -} diff --git a/src/main/java/seedu/duke/commands/meal/MealCommand.java b/src/main/java/seedu/duke/commands/meal/MealCommand.java index a91e136309..732655c9c0 100644 --- a/src/main/java/seedu/duke/commands/meal/MealCommand.java +++ b/src/main/java/seedu/duke/commands/meal/MealCommand.java @@ -1,14 +1,11 @@ package seedu.duke.commands.meal; import java.util.List; -import java.util.ArrayList; import seedu.duke.commands.Command; import seedu.duke.commands.CommandResult; -import seedu.duke.data.meal.Meal; public class MealCommand extends Command { - protected static ArrayList meals; public MealCommand() { super(); @@ -18,9 +15,6 @@ public MealCommand(List meals) { } - public static void setMeals(ArrayList meals) { - MealCommand.meals = meals; - } protected void checkArgument(List arguments, int[] validArgumentAmounts) throws Exception { Boolean isValid = false; diff --git a/src/main/java/seedu/duke/data/Date.java b/src/main/java/seedu/duke/data/Date.java index 91d09135e9..e6086174e2 100644 --- a/src/main/java/seedu/duke/data/Date.java +++ b/src/main/java/seedu/duke/data/Date.java @@ -55,7 +55,7 @@ public String toString() { return date.format(toStringFormatter); } - public static Date Now() throws Exception { + public static Date now() throws Exception { Date now = new Date(LocalDate.now().format(toStringFormatter)); return now; } diff --git a/src/main/java/seedu/duke/data/DateTime.java b/src/main/java/seedu/duke/data/DateTime.java index 7ddafb52e0..2848099e86 100644 --- a/src/main/java/seedu/duke/data/DateTime.java +++ b/src/main/java/seedu/duke/data/DateTime.java @@ -85,7 +85,7 @@ public int compareDate(Date date) { return 0; } - public static DateTime Now() throws Exception { + public static DateTime now() throws Exception { DateTime now = new DateTime(LocalDateTime.now().format(toStringFormatter)); return now; } diff --git a/src/main/java/seedu/duke/data/GoalList.java b/src/main/java/seedu/duke/data/GoalList.java deleted file mode 100644 index 595ded291e..0000000000 --- a/src/main/java/seedu/duke/data/GoalList.java +++ /dev/null @@ -1,193 +0,0 @@ -package seedu.duke.data; - -import seedu.duke.Duke; -import seedu.duke.data.exception.IllegalValueException; -import seedu.duke.data.exception.IncorrectFormatException; -import seedu.duke.data.exception.InvalidDateException; -import seedu.duke.storagefile.GoalStorage; -import seedu.duke.ui.TextUi; - -import java.io.IOException; -import java.util.ArrayList; - -public class GoalList extends ArrayList { - private static final String DATEKEYWORD = "on"; - - private ArrayList goals; - private int goalCount; - - public GoalList() { - goals = new ArrayList<>(); - this.goalCount = 0; - } - - public GoalList(ArrayList goals) { - this.goals = goals; - this.goalCount = goals.size(); - } - - public Goal getGoal(int index) { - return this.goals.get(index); - } - - public int getGoalCount() { - return this.goalCount; - } - - /** - * This method removes a goal object from the global field goals list by indexing - * It also decrements goalCount by 1 - * @param cmd Raw user Command - * @return message of succeeding to delete goal and tell user the updated total number of goals - */ - public static String deleteGoal(String cmd) throws IncorrectFormatException, - NumberFormatException, IOException { - verifyDeleteGoalInput(cmd); - String[] cmdSplit = cmd.toLowerCase().trim().split(" "); - int index = Integer.parseInt(cmdSplit[1]); - Goal targetGoal = Duke.goalList.goals.remove(index - 1); - Duke.goalList.goalCount--; - Duke.goalStorage.overwriteGoalToFile(Duke.goalList); - - return TextUi.deleteGoalMsg(targetGoal) + TextUi.noOfGoalMsg(Duke.goalList.goalCount); - } - - public static String achieveGoal(String cmd) throws IncorrectFormatException, - NumberFormatException, IOException { - verifyAchieveGoalInput(cmd); - String[] cmdSplit = cmd.split(" "); - int index = Integer.parseInt(cmdSplit[1]); - Goal achievedGoal = Duke.goalList.goals.remove(index - 1); - Duke.goalList.goalCount--; - Duke.goalStorage.overwriteGoalToFile(Duke.goalList); //update goal file - Duke.achievedGoals.goals.add(achievedGoal); - Duke.achievedGoals.goalCount++; - Duke.achmStorage.overwriteGoalToFile(Duke.achievedGoals); // update achievement file - return "Congratulation! You have achieved one goal!\n" - + "[Finished]" + achievedGoal + " (:"; - } - - /** - * Begins to format user input by change to small letter, remove leading and - * checks if the user Input is valid by: - * 1. check if the length of the command equals 4 - * 2. detect keywords "on" - * 3. check if user inputs a calories number at valid range - * The userCmd should be like: set 1234 on Date - * @param userCmd represents the raw userInput - * @throws IncorrectFormatException - */ - private static void verifyGoalInput(String userCmd) throws IncorrectFormatException, NumberFormatException { - - String[] cmdSplit = userCmd.split(" "); - if (cmdSplit.length != 4) { - throw new IncorrectFormatException("Oops! The goal instruction is in wrong format."); - } - - if (!cmdSplit[2].equals(DATEKEYWORD)) { - throw new IncorrectFormatException("Sorry. I cannot detect the [" + DATEKEYWORD + "] keyword." ); - } - - int calories = Integer.parseInt(cmdSplit[1]); //throws number exception if not a number string - if (calories <= 0 ){ - throw new IllegalValueException("Please input a positive value."); - } - - } - - /** - * Possible exceptions: - * 1. Missing target index or index is invalid, includes wrong range or even not a number - * 2. Command length not equals to 2 - * @param cmd Raw User Command - * @throws IncorrectFormatException if the input command is in incorrect format, - */ - private static void verifyDeleteGoalInput(String cmd) throws IncorrectFormatException, NumberFormatException { - String[] cmdSplit = cmd.split(" "); - if (cmdSplit.length == 1) { - throw new IncorrectFormatException("Oops! Please provide the target index."); - } - - if (cmdSplit.length != 2) { - throw new IncorrectFormatException("Oops! Wrong format of delete goal instruction."); - } - - int index = Integer.parseInt(cmdSplit[1]); //throws number format exception if not a number string - if (index <= 0 || index > Duke.goalList.goalCount){ - throw new IllegalValueException("Please input a valid index by referring to your goals list."); - } - } - - /** - * This method is similar to verifyDeleteGoalInput method as the input of each command is similar - * @param cmd Raw User Command - * @throws IncorrectFormatException Either missing the target index or command contains more than 2 words - * @throws NumberFormatException if an invalid number string is input, e.g. achieve one - */ - private static void verifyAchieveGoalInput(String cmd) throws IncorrectFormatException, NumberFormatException { - String[] cmdSplit = cmd.split(" "); - if (cmdSplit.length == 1) { - throw new IncorrectFormatException("Oops! Please tell me the target index."); - } - - if (cmdSplit.length != 2) { - throw new IncorrectFormatException("Oops! Wrong format of achieve goal instruction."); - } - - int index = Integer.parseInt(cmdSplit[1]); //throws number format exception if not a number string - if (index <= 0 || index > Duke.goalList.goalCount){ - throw new IllegalValueException("Please input a valid index by referring to your goals list."); - } - } - - /** - * This method will first check if the raw user input is in the correct format. - * If not, terminate the method and throws error message. - * If yes, continue to add a new goal object into the goals list. - * @param userCmd represents raw user input - * @param targetList represents to target list to add new goal - * @param storage represents the target storage to update goal data - * @throws IncorrectFormatException if user input is in wrong format - * @throws NumberFormatException if the user does not input a valid number - */ - public static String addGoal(String userCmd, GoalList targetList, GoalStorage storage) - throws IncorrectFormatException, NumberFormatException, InvalidDateException, IOException { - verifyGoalInput(userCmd); //if invalid, exceptions is thrown - - String[] cmdSplit = userCmd.split(" "); - int calories = Integer.parseInt(cmdSplit[1]); - String date = cmdSplit[3]; - - targetList.goals.add(new Goal(calories, date)); - targetList.goalCount++; - storage.overwriteGoalToFile(targetList); - - return TextUi.addGoalSuccessMessage(); - } - - /** - * Exception appears if the length of view goal command does not equal to 1 - * i.e. containing extra information - * @param cmd Raw user command - * @throws IncorrectFormatException if user command format is incorrect. - */ - public static void verifyViewGoalInput(String cmd) throws IncorrectFormatException { - String[] cmdSplit = cmd.split(" "); - if (cmdSplit.length != 1){ - throw new IncorrectFormatException("Use single word [viewG] to view your goal list."); - } - } - - /** - * similar implementation to verify view goal list command - * @param cmd Raw user command - * @throws IncorrectFormatException if more than one word is input - */ - public static void verifyViewAchievementInput(String cmd) throws IncorrectFormatException { - String[] cmdSplit = cmd.split(" "); - if (cmdSplit.length != 1){ - throw new IncorrectFormatException("Use single word [achievement] to view your achievement."); - } - } - -} diff --git a/src/main/java/seedu/duke/data/meal/Meal.java b/src/main/java/seedu/duke/data/meal/Meal.java deleted file mode 100644 index 1ca6e5ade5..0000000000 --- a/src/main/java/seedu/duke/data/meal/Meal.java +++ /dev/null @@ -1,22 +0,0 @@ -package seedu.duke.data.meal; - -import seedu.duke.data.Date; - -public class Meal { - public String name; - public int calories; - public Date time; - public Category category; - - public Meal(String name, int calories, String category, Date time) throws Exception { - this.name = name; - this.calories = calories; - this.time = time; - this.category = CategoryParser.Parse(category); - } - - @Override - public String toString() { - return name + "(" + calories + " calories, " + category + ", on " + time.toString() + ")"; - } -} diff --git a/src/main/java/seedu/duke/parser/Parser.java b/src/main/java/seedu/duke/parser/Parser.java index 2d773e385f..abd089cf4f 100644 --- a/src/main/java/seedu/duke/parser/Parser.java +++ b/src/main/java/seedu/duke/parser/Parser.java @@ -11,12 +11,9 @@ import java.util.regex.Pattern; import seedu.duke.commands.Command; -import seedu.duke.commands.ExitCommand; -import seedu.duke.commands.goal.GoalCommand; import seedu.duke.commands.goal.DeleteGoalCommand; import seedu.duke.commands.goal.ViewGoalCommand; import seedu.duke.commands.goal.AchieveGoalCommand; -import seedu.duke.commands.goal.AchievementCommand; import seedu.duke.commands.HelpCommand; import seedu.duke.commands.IncorrectCommand; import seedu.duke.commands.logcommands.LogCommand; @@ -24,7 +21,7 @@ import seedu.duke.commands.logcommands.ViewLogCommand; import seedu.duke.commands.logcommands.UpdateLogCommand; import seedu.duke.data.exception.IllegalValueException; -import seedu.duke.commands.meal.*; +import seedu.duke.commands.ExitCommand; public class Parser { @@ -67,18 +64,6 @@ public Command parseCommand(String userInput) throws Exception { case UpdateLogCommand.COMMAND_WORD: return new UpdateLogCommand(Arrays.asList(arguments.trim().split(" "))); - case AddCommand.COMMAND_WORD: - return new AddCommand(Arrays.asList(arguments.trim().split(" "))); - - case DeleteCommand.COMMAND_WORD: - return new DeleteCommand(Arrays.asList(arguments.trim().split(" "))); - - case ListCommand.COMMAND_WORD: - return new ListCommand(Arrays.asList(arguments.trim().split(" "))); - - case GoalCommand.COMMAND_WORD: - return new GoalCommand(userInput); - case DeleteGoalCommand.COMMAND_WORD: return new DeleteGoalCommand(userInput); @@ -91,8 +76,12 @@ public Command parseCommand(String userInput) throws Exception { case HelpCommand.COMMAND_WORD: return new HelpCommand(); + case ExitCommand.COMMAND_WORD: + return new ExitCommand(); + default: - return new IncorrectCommand("The command you inputted does not exist. Run `help` to see a list of available commands.0"); + return new IncorrectCommand("The command you inputted does not exist. Run `help` to see a" + + "list of available commands."); } } diff --git a/src/main/java/seedu/duke/storagefile/AchmStorage.java b/src/main/java/seedu/duke/storagefile/AchmStorage.java deleted file mode 100644 index 3881b44fe4..0000000000 --- a/src/main/java/seedu/duke/storagefile/AchmStorage.java +++ /dev/null @@ -1,74 +0,0 @@ -package seedu.duke.storagefile; - -import seedu.duke.Duke; -import seedu.duke.data.GoalList; -import seedu.duke.ui.TextUi; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Scanner; - -public class AchmStorage extends GoalStorage { - - public AchmStorage(String dirName, String textFileName) { - super(dirName, textFileName); - } - - public static AchmStorage initializeGoalStorage(String dirName, String textFilePath) { - return new AchmStorage(dirName, textFilePath); - } - - /** - * Note that this function exhibits the same structure as the method in parent class - * except that the nested method textToGoalObject is overridden - * @throws IOException if failed to write into file - */ - @Override - public void restoreGoalRecord() throws IOException { - if (dir.exists() && textFile.exists()) { - try { - Scanner s = new Scanner(textFile); - while (s.hasNextLine()) { - String line = s.nextLine(); - if (!line.trim().isEmpty()) { - textToGoalObject(line); - } - } - s.close(); - } catch (FileNotFoundException fnf) { - System.out.println("Saved file cannot be found! FItNus will start with empty goal records."); - System.out.println(TextUi.buildingFileMsg()); - Duke.goalList = new GoalList(); - } catch (Exception e) { - System.out.println("Saved goal file is corrupted! FitNus will start with empty goal records."); - System.out.println(TextUi.buildingFileMsg()); - Duke.goalList = new GoalList(); //start with an empty goal list - } - } - - if (!dir.exists()) { - dir.mkdir(); - } - if (!textFile.exists()) { - textFile.createNewFile(); - Duke.goalList = new GoalList(); //start with an empty goal list - } - - } - - /** - * This is used to restore achievement by - * adding achieved goal into achieved goal list - * It has similar mechanism as restoring goal records - * @param goalRecord refers to saved goal record - * @throws Exception if failed to restore records - */ - @Override - protected void textToGoalObject(String goalRecord) throws Exception { - String restoredCommand = restoreOrigionalCommand(goalRecord); - GoalList.addGoal(restoredCommand, Duke.achievedGoals, Duke.achmStorage); - } - - - -} diff --git a/src/main/java/seedu/duke/storagefile/DataManager.java b/src/main/java/seedu/duke/storagefile/DataManager.java deleted file mode 100644 index 237bac3f6f..0000000000 --- a/src/main/java/seedu/duke/storagefile/DataManager.java +++ /dev/null @@ -1,181 +0,0 @@ -package seedu.duke.storagefile; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.reflect.TypeToken; - -import seedu.duke.Duke; -import seedu.duke.data.Date; -import seedu.duke.data.DateTime; -import seedu.duke.data.meal.Meal; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.Type; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; - -/** - * A util used for managing the data of the program, using the io stream to - * save and read the data at a local address. - */ -public class DataManager { - private static String absolutePath; - private static String home = System.getProperty("user.home"); - - /** - * Set the relative path to make clear which exact address the data file is - * going to save and read.Using relative path may make the program easier to - * modify when you need to change the absolute saving path. - * - * @param relativePath The address containing the name of the data file under - * the data folder, ignoring the address of the data folder. - * @throws IOException - */ - public static void setRelativePath(String relativePath) throws IOException { - String dataFolderPath = home + "\\AppData\\LocalLow\\FITNUS\\"; - // Logger.customPrint(dataFolderPath); - Files.createDirectories(Paths.get(dataFolderPath)); - - absolutePath = dataFolderPath + relativePath; - // Logger.customPrint(absolutePath); - } - - /** - * Read the data from the path that has been previously set. - * - * @throws IOException - */ - public static String readData() throws IOException { - File file = new File(absolutePath); - - // No existing file - if (file.createNewFile()) { - return ""; - } - BufferedReader reader = new BufferedReader(new FileReader(file)); - - String result = "", line; - while ((line = reader.readLine()) != null) { - result += line + "\n"; - } - reader.close(); - return result.trim(); - } - - /** - * Save the data to a file at the path that has been previously set. - * - * @param content The serialized data json that is going to be saved. - * @throws IOException - */ - public static void saveData(String content) throws Exception { - File file = new File(absolutePath); - file.createNewFile(); - - FileWriter writer = new FileWriter(file); - writer.write(content); - writer.close(); - Duke.ui.showToUser("Your data has been saved at the path:\n " + absolutePath); - } - - /** - * Convert a json String to a CustomType that is set by the user. - * - * @param content A valid json String indicates a CustomType instance. - */ - public static CustomType convertFromJson(String json) { - Type type = new TypeToken() { - }.getType(); - - Gson gson = new Gson(); - - return gson.fromJson(json, type); - } - - /** - * Convert a json String to an ArrayList. - * - * @param content A valid json String indicates an ArrayList. - */ - public static ArrayList convertFromJsonToMealList(String json) { - Type type = new TypeToken>() { - }.getType(); - - Gson gson = new GsonBuilder() - // .registerTypeAdapter(Meal.class, new MealAdapter()) - // .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) - .registerTypeAdapter(Date.class, new DateAdapter()) - .create(); - - return gson.fromJson(json, type); - } - - /** - * Serialize any object to json. - * - * @param object Any variable that you want to serialize. - */ - public static String convertToJson(Object object) { - Gson gson = new Gson(); - return gson.toJson(object); - } - - /** - * Used for deserializing Meal with a custom rule. - */ - private static class MealAdapter implements JsonDeserializer { - @Override - public Meal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - JsonObject jsonObject = json.getAsJsonObject(); - return context.deserialize(jsonObject, Meal.class); - } - } - - /** - * Used for deserializing DateTime with a custom rule. - */ - private static class DateTimeAdapter implements JsonDeserializer { - @Override - public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { - JsonObject jsonObject = json.getAsJsonObject(); - - String rawData = jsonObject.get("rawData").getAsString(); - try { - return new DateTime(rawData); - } catch (Exception exception) { - Duke.ui.showToUser(exception.toString()); - } - return null; - } - } - - /** - * Used for deserializing Date with a custom rule. - */ - private static class DateAdapter implements JsonDeserializer { - @Override - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { - JsonObject jsonObject = json.getAsJsonObject(); - - String rawData = jsonObject.get("standardString").getAsString(); - try { - return new Date(rawData); - } catch (Exception exception) { - Duke.ui.showToUser(exception.toString()); - } - return null; - } - } -} diff --git a/src/main/java/seedu/duke/storagefile/GoalStorage.java b/src/main/java/seedu/duke/storagefile/GoalStorage.java deleted file mode 100644 index ee5145ce2e..0000000000 --- a/src/main/java/seedu/duke/storagefile/GoalStorage.java +++ /dev/null @@ -1,112 +0,0 @@ -package seedu.duke.storagefile; - -import seedu.duke.Duke; -import seedu.duke.data.GoalList; -import seedu.duke.ui.TextUi; - -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Scanner; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.Locale; - -public class GoalStorage extends ExerciseLogStorage { - - public GoalStorage(String dirName, String textFileName) { - super(dirName, textFileName); - } - - public static GoalStorage initializeGoalStorage(String dirName, String textFilePath) { - return new GoalStorage(dirName, textFilePath); - } - - /** - * This method restore any saved goal into goal list at the beginning to start the app. - * Both directory or save file not found will cause the app to start with an empty goal list - * if error occurs in loading saved date, the app will start with empty list immediately - * without loading part of data - * Note that this method also set up the file writer into overwrite mode - */ - public void restoreGoalRecord() throws IOException { - if (dir.exists() && textFile.exists()) { - try { - Scanner s = new Scanner(textFile); - while (s.hasNextLine()) { - String line = s.nextLine(); - if (!line.trim().isEmpty()) { - textToGoalObject(line); - } - } - s.close(); - } catch (FileNotFoundException fnf) { - System.out.println("Saved file cannot be found! FItNus will start with empty goal records."); - System.out.println(TextUi.buildingFileMsg()); - Duke.goalList = new GoalList(); - } catch (Exception e) { - System.out.println("Saved goal file is corrupted! FitNus will start with empty goal records."); - System.out.println(TextUi.buildingFileMsg()); - Duke.goalList = new GoalList(); //start with an empty goal list - } - } - - if (!dir.exists()) { - dir.mkdir(); - } - if (!textFile.exists()) { - textFile.createNewFile(); - Duke.goalList = new GoalList(); //start with an empty goal list - } - - } - - /** - * This method update the content of this.textFile by using content from - * source goalList goals - * Note that in the following implementation, the field writeFile in not used - * Instead, everytime a new file writer is created to update content of file - * @param goals represents source of goalList to retrieve content - * @throws IOException if failed to access file - */ - public void overwriteGoalToFile(GoalList goals) throws IOException { - String content = TextUi.contentOfGoalList(goals); - if (content == null) { - return; - } - FileWriter fw = new FileWriter(textFile.toPath().toString(), false); - fw.write(content); - fw.close(); - } - - protected void textToGoalObject(String goalRecord) throws Exception { - String restoredCommand = restoreOrigionalCommand(goalRecord); - GoalList.addGoal(restoredCommand, Duke.goalList, Duke.goalStorage); - } - - protected static String restoreOrigionalCommand(String goalRecord) { - String[] goalRecordParts = goalRecord.split(" ", 5); - //example of saved record: Consume 1230 kcal on Nov 11, 2023 - int amount =Integer.parseInt(goalRecordParts[1]); - String savedDateString = goalRecordParts[4]; - String date = convertDateFormat(savedDateString); - return "set " + amount + " on " + date; - } - - - /** - * This method is used to convert a date String with format MMM d, yyyy into a date String with format dd/MM/yyyy - * @param originalDateString date String with format MMM d, yyyy, e.g. 11 Nov, 2023 - * @return date String with format dd/MM/yyyy, e.g. 11/11/2023 - */ - private static String convertDateFormat(String originalDateString) { - DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH); - LocalDate originalDate = LocalDate.parse(originalDateString, originalFormatter); - DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("dd/M/yyyy"); - return originalDate.format(newFormatter); - } - - -} - - diff --git a/src/main/java/seedu/duke/ui/TextUi.java b/src/main/java/seedu/duke/ui/TextUi.java index 3e7246ed64..6b978a4a5d 100644 --- a/src/main/java/seedu/duke/ui/TextUi.java +++ b/src/main/java/seedu/duke/ui/TextUi.java @@ -2,7 +2,6 @@ import static seedu.duke.common.Messages.MESSAGE_GOODBYE; import static seedu.duke.common.Messages.MESSAGE_INIT_FAILED; -import static seedu.duke.common.Messages.MESSAGE_PROGRAM_LAUNCH_ARGS_USAGE; import static seedu.duke.common.Messages.MESSAGE_USING_STORAGE_FILE; import static seedu.duke.common.Messages.MESSAGE_WELCOME; @@ -13,10 +12,8 @@ import java.util.Optional; import java.util.Scanner; -import seedu.duke.Duke; import seedu.duke.commands.CommandResult; import seedu.duke.data.Goal; -import seedu.duke.data.GoalList; import seedu.duke.data.Printable; /** @@ -119,8 +116,6 @@ public void showWelcomeMessage(String version, String storageFilePath) { DIVIDER, MESSAGE_WELCOME, version, - MESSAGE_PROGRAM_LAUNCH_ARGS_USAGE, - storageFileInfo, DIVIDER); } @@ -135,7 +130,7 @@ public void showInitFailedMessage() { /** * Shows message(s) to the user * - * @param message + * @param message the message to show to the user */ public void showToUser(String... message) { for (String m : message) { @@ -151,7 +146,7 @@ public void showToUser(String... message) { * formatting to demarcate different * command execution segments. * - * @param result + * @param result the command result to be shown to the user */ public void showResultToUser(CommandResult result) { final Optional> resultItems = result.getRelevantItems(); @@ -213,77 +208,6 @@ public static String deleteGoalMsg(Goal deletedGoal) { } - /** - * This method is used to implement Goal commend execution, when adding a new - * goal - * - * @return string contains information of generating a new goal successfully - */ - public static String addGoalSuccessMessage() { - int currentNoOfGoal = Duke.goalList.getGoalCount(); - Goal newlyAddedGoal = Duke.goalList.getGoal(currentNoOfGoal - 1); - return "Nice! I have added the following goal to your goals list: \n\t" + newlyAddedGoal; - } - - /** - * This is used to show the content inside the goal list. - * It first checks if the list contains at least one goal, - * then print the goal by using string builder. - * - * @return String containing all the inserted goal in the global field goal list - */ - public static String showGoalList() { - int numberOfGoal = Duke.goalList.getGoalCount(); - if (numberOfGoal == 0) { - return "Oh not! You don't have any goal to achieve currently."; - } - StringBuilder sb = new StringBuilder(); - sb.append("Here you go! Remember to stick to your exercise and meal plans.\n"); - for (int i = 0; i < numberOfGoal; i++) { - sb.append(i + 1).append(". ").append(Duke.goalList.getGoal(i)).append("\n"); - } - - return sb.toString(); - } - - /** - * Similar to show Goal List. This method is used to list out all achieved goal - * in record. - * - * @return String containing all achieved goal - */ - public static String showAchievement() { - int numberOfGoal = Duke.achievedGoals.getGoalCount(); - if (numberOfGoal == 0) { - return "Add oil! There is no achievement found."; - } - StringBuilder sb = new StringBuilder(); - sb.append("Congratulation! See your achievements below: \n"); - for (int i = 0; i < numberOfGoal; i++) { - sb.append(i + 1).append(". [A]").append(Duke.achievedGoals.getGoal(i)).append("\n"); - } - - return sb.toString(); - } - - /** - * This method return content of goal list in any goalList object - * It is typically used to overwrite save file whenever change in goal records - * - * @param goals a GoalList object - * @return String containing goal information of the goal object - */ - public static String contentOfGoalList(GoalList goals) { - if (goals.getGoalCount() == 0) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < goals.getGoalCount(); i++) { - sb.append(goals.getGoal(i)).append("\n"); - } - return sb.toString(); - } - public static String buildingFileMsg() { return "Building new save file...\n" + "Building new file succeed!"; } diff --git a/src/test/java/seedu/duke/parser/ParserTest.java b/src/test/java/seedu/duke/parser/ParserTest.java index fd76b80b0b..10b28d7cd6 100644 --- a/src/test/java/seedu/duke/parser/ParserTest.java +++ b/src/test/java/seedu/duke/parser/ParserTest.java @@ -1,7 +1,6 @@ package seedu.duke.parser; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.duke.common.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.jupiter.api.BeforeEach; @@ -68,19 +67,4 @@ private void parseAndAssertIncorrectWithMessage(String feedbackMessage, String.. assertEquals(result.feedbackToUser, feedbackMessage); } } - - /** - * Parses input and asserts the class/type of the returned command object. - * - * @param input to be parsed - * @param expectedCommandClass expected class of returned command - * @return the parsed command object - * @throws Exception - */ - private T parseAndAssertCommandType(String input, Class expectedCommandClass) - throws Exception { - final Command result = parser.parseCommand(input); - assertTrue(result.getClass().isAssignableFrom(expectedCommandClass)); - return (T) result; - } }