diff --git a/.gitignore b/.gitignore index f69985ef..bba24a33 100644 --- a/.gitignore +++ b/.gitignore @@ -13,5 +13,14 @@ src/main/resources/docs/ *.iml bin/ +/vcs.xml +/logs +/*.logs +/*.logs.* +modules.xml + +/*.class +*.class + /text-ui-test/ACTUAL.txt text-ui-test/EXPECTED-UNIX.TXT diff --git a/README.md b/README.md index 8715d4d9..c60697e3 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,3 @@ # Duke project template -This is a project template for a greenfield Java project. It's named after the Java mascot _Duke_. Given below are instructions on how to use it. - -## Setting up in Intellij - -Prerequisites: JDK 11, update Intellij to the most recent version. - -1. Open Intellij (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project first) -1. Open the project into Intellij as follows: - 1. Click `Open`. - 1. Select the project directory, and click `OK`. - 1. If there are any further prompts, accept the defaults. -1. Configure the project to use **JDK 11** (not other versions) as explained in [here](https://www.jetbrains.com/help/idea/sdk.html#set-up-jdk).
- In the same dialog, set the **Project language level** field to the `SDK default` option. -3. After that, locate the `src/main/java/Duke.java` file, right-click it, and choose `Run Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: - ``` - Hello from - ____ _ - | _ \ _ _| | _____ - | | | | | | | |/ / _ \ - | |_| | |_| | < __/ - |____/ \__,_|_|\_\___| - ``` +Progress: [Trello board](https://trello.com/b/OP3BJpuz/duke_) \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..304a2dac --- /dev/null +++ b/build.gradle @@ -0,0 +1,41 @@ +plugins { + id 'java' + id 'application' + id 'checkstyle' + id 'com.github.johnrengelman.shadow' version '5.1.0' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.7.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.7.0' + testCompileOnly 'junit:junit:4.12' + testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.1.0' +} + +test { + useJUnitPlatform { + includeEngines 'junit-vintage' + } +} + +application { + mainClassName = "Duke" +} + +shadowJar { + archiveBaseName = "duke" + archiveClassifier = null +} + +checkstyle { + toolVersion = '8.29' +} + +run { + standardInput = System.in + enableAssertions = true +} \ No newline at end of file diff --git a/docs/.idea/.gitignore b/docs/.idea/.gitignore new file mode 100644 index 00000000..26d33521 --- /dev/null +++ b/docs/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/docs/.idea/misc.xml b/docs/.idea/misc.xml new file mode 100644 index 00000000..639900d1 --- /dev/null +++ b/docs/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/docs/.idea/vcs.xml b/docs/.idea/vcs.xml new file mode 100644 index 00000000..6c0b8635 --- /dev/null +++ b/docs/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/duke.txt b/duke.txt new file mode 100644 index 00000000..63424470 --- /dev/null +++ b/duke.txt @@ -0,0 +1,4 @@ +todo,borrow book,1 +deadline,clean room /by 2019-12-23 21:00,1 +todo,read books,1 +event,hackathon /at 2021-12-25 18:00-21:00,0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7454180f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ffed3a25 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..1b6c7873 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..ac1b06f9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/App.java b/src/main/java/App.java new file mode 100644 index 00000000..c14b6a99 --- /dev/null +++ b/src/main/java/App.java @@ -0,0 +1,30 @@ +public class App { + private TaskManager manager; + private Config config; + private StorageDTO storage; + private UserInterface ui; + + public void init() { + config = new Config(); + storage = new StorageDTO(config.getStoragePath()); + manager = new TaskManager(); + storage.loadInto(manager); + ui = new UserInterface(manager); + } + + public void run() { + if (manager == null || config == null || storage == null || ui == null) { + System.out.println("nil init for manager or config or storage or UI"); + return; + } + ui.start(); + while (!ui.isExit()) { + ui.getInput(); + ui.parseInput(); + ui.processInput(); + } + + storage.save(manager.getTasks()); + ui.end(); + } +} diff --git a/src/main/java/Config.java b/src/main/java/Config.java new file mode 100644 index 00000000..b9f195d7 --- /dev/null +++ b/src/main/java/Config.java @@ -0,0 +1,21 @@ +public class Config { + String logPath = "duke_info.logs"; + + public String getStoragePath() { + return storagePath; + } + + public void setStoragePath(String storagePath) { + this.storagePath = storagePath; + } + + String storagePath = "~/go/src/github.com/metildachee/duke/duke.txt"; + + public String getLogPath() { + return logPath; + } + + public void setLogPath(String logPath) { + this.logPath = logPath; + } +} diff --git a/src/main/java/Deadline.java b/src/main/java/Deadline.java new file mode 100644 index 00000000..3a30e846 --- /dev/null +++ b/src/main/java/Deadline.java @@ -0,0 +1,112 @@ +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +public class Deadline extends Todo { + protected LocalDate date; + protected long endTime; + + String savable; + Parser parser = new Parser(); + Logger logger = new Logger(); + + public Deadline(String description, String endDateTime, int id) { + super(description, id); + + logger.init(""); + logger.info("get description: " + description); + logger.info("get endDateTime: " + endDateTime.trim()); + ArrayList tokens = new ArrayList(Arrays.asList(endDateTime.trim().split(" "))); + logger.info("set tokens: " + tokens); + setDate(tokens.get(0)); + setEndTime(tokens.get(1)); + setSavable(description + "/by" + endDateTime); + } + + public Deadline(String description, int id) { + super(description, id); + date = null; + } + + public Deadline(String description, LocalDate date, long time, int id) { + super(description, id); + this.date = date; + endTime = time; + } + + public Deadline(String description, String date, String endTime, int id) { + super(description, id); + setDate(date); + setEndTime(endTime); + } + + public LocalDate getDate() { + return date; + } + + public void setDate(String date) { + logger.info("set date: " + date); + if (Objects.equals(date, "")) { + return; + } + LocalDate parsedDate = parser.stringToDate(date); + if (parsedDate == null) { + logger.info("parsing date got null"); + } else { + this.date = parsedDate; + } + } + + public void setEndTime(String time) { + logger.info("set end_time: " + time); + DateFormat formatter = new SimpleDateFormat("HH:mm"); + try { + this.endTime = formatter.parse(time).getTime() + 27000000; + } catch (ParseException p) { + logger.info("parsing time got exception" + p.getMessage()); + } + } + + public String getEndTime() { + return String.format("%02d:%02d", + TimeUnit.MILLISECONDS.toHours(endTime), + TimeUnit.MILLISECONDS.toMinutes(endTime) - + TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(endTime))); + + } + + public String getSavable() { + return savable; + } + + public void setSavable(String savable) { + this.savable = savable; + } + + @Override + public String toTask() { + return getType() + "," + getSavable() + "," + (isDone ? "1" : "0"); + } + + @Override + public String toString() { + String status = isDone ? "X" : " "; + return id + ". [D][" + status + "] " + super.getDescription().trim() + + (date == null ? "" : " (at: " + date.format(DateTimeFormatter.ofPattern("MMM d yyyy"))) + + (endTime == 0 ? "" : " by: " + getEndTime()) + + ")"; + + } + + @Override + public String getType() { + return "deadline"; + } +} \ No newline at end of file diff --git a/src/main/java/Duke.java b/src/main/java/Duke.java index 5d313334..18259d0f 100644 --- a/src/main/java/Duke.java +++ b/src/main/java/Duke.java @@ -1,10 +1,7 @@ public class Duke { public static void main(String[] args) { - String logo = " ____ _ \n" - + "| _ \\ _ _| | _____ \n" - + "| | | | | | | |/ / _ \\\n" - + "| |_| | |_| | < __/\n" - + "|____/ \\__,_|_|\\_\\___|\n"; - System.out.println("Hello from\n" + logo); + App duke = new App(); + duke.init(); + duke.run(); } } diff --git a/src/main/java/Event.java b/src/main/java/Event.java new file mode 100644 index 00000000..8f8cffa5 --- /dev/null +++ b/src/main/java/Event.java @@ -0,0 +1,64 @@ +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +public class Event extends Deadline { + protected long startTime; + private static final Logger logger = new Logger(); + + public String getStartTime() { + assert startTime != 0; + return String.format("%02d:%02d", + TimeUnit.MILLISECONDS.toHours(startTime), + TimeUnit.MILLISECONDS.toMinutes(startTime) - + TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(startTime))); + } + + public Event(String description, String date, int id) { + super(description, + (String) new ArrayList(Arrays.asList(date.trim().split(" "))).get(0), + (String) new ArrayList(Arrays.asList(Arrays.asList(date.trim().split(" ")).get(1).split("-"))).get(1), + id); + setStartTime((String) new ArrayList(Arrays.asList(Arrays.asList(date.trim().split(" ")).get(1).split("-"))).get(0)); + logger.init(""); + setSavable(description + "/at" + date); + } + + public void setStartTime(String startTime) { + if (Objects.equals(startTime, "")) { + logger.info("empty time"); + return; + } + DateFormat formatter = new SimpleDateFormat("HH:mm"); + try { + this.startTime = formatter.parse(startTime).getTime() + 27000000; + } catch (ParseException p) { + logger.info("parsing time got null"); + } + } + + @Override + public String toString() { + String status = isDone ? "X" : " "; + return id + ". [E][" + status + "] " + super.getDescription() + + (date == null ? "" : " (at: " + date.format(DateTimeFormatter.ofPattern("MMM d yyyy"))) + + (startTime == 0 ? "" : " from: " + getStartTime()) + + (endTime == 0 ? "" : " to: " + getEndTime()) + + ")"; + } + + @Override + public String getType() { + return "event"; + } +} \ No newline at end of file diff --git a/src/main/java/Logger.java b/src/main/java/Logger.java new file mode 100644 index 00000000..6f5949ea --- /dev/null +++ b/src/main/java/Logger.java @@ -0,0 +1,40 @@ +import java.io.IOException; +import java.util.Objects; +import java.util.logging.FileHandler; +import java.util.logging.Level; +import java.util.logging.SimpleFormatter; + +public class Logger { + java.util.logging.Logger logger; + + public Logger() { + + } + + public void init(String path) { + if (Objects.equals(path, "")) { + path = "duke_info.logs"; + } + logger = java.util.logging.Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME); + logger.setLevel(Level.FINEST); + try { + FileHandler fileTxt = new FileHandler(path); + + SimpleFormatter formatterTxt = new SimpleFormatter(); + fileTxt.setFormatter(formatterTxt); + logger.addHandler(fileTxt); + } catch (IOException e) { + logger.info("init logger got error"); + } + } + + public java.util.logging.Logger getLogger() { + return logger; + } + + public void info(String msg) { + if (logger != null) { + logger.finest(msg); + } + } +} diff --git a/src/main/java/Parser.java b/src/main/java/Parser.java new file mode 100644 index 00000000..5616f53b --- /dev/null +++ b/src/main/java/Parser.java @@ -0,0 +1,154 @@ +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Locale; + +public class Parser { + private final Logger logger = new Logger(); + private final static String DETECT_END = "bye"; + private final static String DETECT_LIST = "list"; + private final static String DETECT_DONE = "done"; + private final static String DETECT_DELETE = "delete"; + private final static String DETECT_FIND = "find"; + private final static String DETECT_VIEW = "view"; + private final static String DETECT_EVENT = "event"; + private final static String DETECT_DEADLINE = "deadline"; + private final static String DETECT_TODO = "todo"; + + private ArrayList tokens = new ArrayList<>(); + + public Parser() { + logger.init(""); + } + + public String getInstruction() { + return instruction; + } + + public void setInstruction(String instruction) { + this.instruction = instruction; + } + + private String instruction; + + public String getTaskInfo() { + return taskInfo; + } + + public void setTaskInfo(String taskInfo) { + this.taskInfo = taskInfo; + } + + private String taskInfo; + + public ArrayList getTokens() { + return tokens; + } + + public void setTokens(ArrayList tokens) { + this.tokens = tokens; + } + + /** + * Returns a String date into a LocalDate date. + * Return will be null if error occurs. + * + * @param date the date to parse + * @return date the parsed date + * @see LocalDate + */ + public LocalDate stringToDate(String date) { + LocalDate parsedDate = null; + try { + parsedDate = LocalDate.parse(date); + } catch (DateTimeParseException e) { + logger.info("parse date time got error" + e.getMessage()); + } + return parsedDate; + } + + public void parseInput(String input) { + tokens = new ArrayList(Arrays.asList(input.split(" "))); + instruction = tokens.get(0); + taskInfo = tokens + .subList(1, tokens.size()) + .toString() + .replace(",", "") + .replace("[", "") + .replace("]", "") + .trim(); + } + + public Boolean isExit() { + return instruction.toLowerCase(Locale.ROOT).equals(DETECT_END); + } + + public Boolean isExit(String i) { + return i.toLowerCase(Locale.ROOT).equals(DETECT_END); + } + + public Boolean isList() { + return isList(instruction); + } + + public Boolean isList(String i) { + logger.info("instruction: listing task"); + return i.toLowerCase(Locale.ROOT).equals(DETECT_LIST); + } + + public Boolean isDone() { + return isDone(instruction); + } + + public Boolean isDone(String i) { + logger.info("instruction: done"); + return i.toLowerCase(Locale.ROOT).equals(DETECT_DONE) && tokens.size() >= 2; + } + + public Boolean isDelete() { + return isDelete(instruction); + } + + public Boolean isDelete(String i) { + return i.toLowerCase(Locale.ROOT).equals(DETECT_DELETE) && tokens.size() >= 2; + } + + public String getFirstToken() { + if (tokens.size() > 1) { + String firstToken = tokens.get(1); + logger.info("instruction: get first token" + firstToken); + return firstToken; + } + + return null; + } + + public Boolean isFind() { + return instruction.toLowerCase(Locale.ROOT).equals(DETECT_FIND) && tokens.size() >= 1; + } + + public Boolean isFind(String i) { + return i.toLowerCase(Locale.ROOT).equals(DETECT_FIND) && tokens.size() >= 1; + } + + public Boolean isView() { + return instruction.toLowerCase(Locale.ROOT).equals(DETECT_VIEW) && tokens.size() >= 2; + } + + public Boolean isView(String i) { + return i.toLowerCase(Locale.ROOT).equals(DETECT_VIEW) && tokens.size() >= 1; + } + + public Boolean isAdd() { + return instruction.toLowerCase(Locale.ROOT).equals(DETECT_EVENT) && tokens.size() >= 1 || + instruction.toLowerCase(Locale.ROOT).equals(DETECT_DEADLINE) && tokens.size() >= 1 || + instruction.toLowerCase(Locale.ROOT).equals(DETECT_TODO) && tokens.size() >= 1; + } + + public Boolean isAdd(String i) { + return i.toLowerCase(Locale.ROOT).equals(DETECT_EVENT) && tokens.size() >= 1 || + i.toLowerCase(Locale.ROOT).equals(DETECT_DEADLINE) && tokens.size() >= 1 || + i.toLowerCase(Locale.ROOT).equals(DETECT_TODO) && tokens.size() >= 1; + } +} diff --git a/src/main/java/StorageDAO.java b/src/main/java/StorageDAO.java new file mode 100644 index 00000000..09c7b4ca --- /dev/null +++ b/src/main/java/StorageDAO.java @@ -0,0 +1,49 @@ +import java.io.File; +import java.io.FileNotFoundException; + +public class StorageDAO { + protected File file; + protected String path; + + private final Logger logger = new Logger(); + + public StorageDAO(String path) { + this.path = "duke.txt"; + logger.init(""); + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public boolean isInit() { + return file != null; + } + + public void init() throws Exception { + logger.info("init file path: " + path); + try { + this.file = new File(this.path); + logger.info("path " + path); + path = this.file.getPath(); + boolean created = file.createNewFile(); + if (created) { + logger.info("no file detected, a new file has been created: " + this.path); + } + } catch (Exception e) { + logger.info("got err: " + e); + } + } +} diff --git a/src/main/java/StorageDTO.java b/src/main/java/StorageDTO.java new file mode 100644 index 00000000..f8520b5f --- /dev/null +++ b/src/main/java/StorageDTO.java @@ -0,0 +1,96 @@ +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Objects; +import java.util.Scanner; + +public class StorageDTO extends StorageDAO { + private final Logger logger = new Logger(); + + public StorageDTO(String path) { + super(path); + logger.init(""); + } + + public ArrayList loadInto(TaskManager tm) { + try { + init(); + ArrayList list = new ArrayList(); + int id = 0; + Scanner s = new Scanner(file); + while (s.hasNext()) { + Task t = parseLineToTask(s.nextLine(), id, tm); + list.add(t); + logger.info("added task successfully to list" + t); + id++; + } + tm.setTasks(list); + return list; + } catch (Exception e) { + logger.info("got error loading file, error: " + e); + } + return new ArrayList(); + } + + public String parseTaskToLine(Task e) throws Exception { + if (e == null) { + throw new Exception("task to parse is empty"); + } + try { + Event event = (Event) e; + return event.toTask(); + } catch (ClassCastException exception) { + logger.info("casting task from file to event class got error"); + } + + try { + Deadline deadline = (Deadline) e; + return deadline.toTask(); + } catch (ClassCastException exception) { + logger.info("casting task from file to deadline class got error"); + } + + try { + Todo todo = (Todo) e; + return todo.toTask(); + } catch (ClassCastException exception) { + logger.info("casting task from file to todo class got error"); + } + return e.toTask(); + } + + public void save(ArrayList tasks) { + try { + FileWriter fw = new FileWriter(path); + tasks.forEach(t -> { + try { + String task = parseTaskToLine(t); + fw.write(task + "\n"); + logger.info("task written properly" + task); + } catch (Exception e) { + e.printStackTrace(); + } + }); + fw.close(); + logger.info("file has been saved properly"); + } catch (Exception e) { + System.out.println("saving failed, error: " + e); + } + } + + public Task parseLineToTask(String l, int id, TaskManager tm) throws Exception { + if (Objects.equals(l, "")) { + throw new Exception("no content"); + } + + String[] parts = l.split(","); + String taskType = parts[0]; + String taskDesc = parts[1]; + int taskStatus = Integer.parseInt(parts[2]); + Task t = tm.createTask(taskDesc, taskType); + if (!Objects.equals(t.getType(), "task")) { + Todo todo = (Todo) t; + todo.setDone(taskStatus != 0); + } + return t; + } +} diff --git a/src/main/java/Task.java b/src/main/java/Task.java new file mode 100644 index 00000000..7f4d1683 --- /dev/null +++ b/src/main/java/Task.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.logging.Logger; + +public class Task { + protected String description; + protected Integer id; + + public String toTask() { + return getType() + "," + getDescription(); + } + + public Task(String description, int id) { + this.id = id; + this.description = description; + } + + public Integer getId() { + return id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String desc) { + description = desc; + } + + public String toString() { + return description; + } + + public String getType() { + return "task"; + } +} + diff --git a/src/main/java/TaskManager.java b/src/main/java/TaskManager.java new file mode 100644 index 00000000..801f72e3 --- /dev/null +++ b/src/main/java/TaskManager.java @@ -0,0 +1,142 @@ +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Objects; + +public class TaskManager { + private final static String DETECT_ADD_TODO = "todo"; + private final static String DETECT_ADD_EVENT = "event"; + private final static String DETECT_ADD_DEADLINE = "deadline"; + private final Logger logger = new Logger(); + private ArrayList tasks = new ArrayList<>(); + + public TaskManager() { + logger.init(""); + } + + public ArrayList findTask(String keyword) { + ArrayList results = new ArrayList<>(); + tasks.stream().filter(t -> t.getDescription().contains(keyword)).forEach(results::add); + return results; + } + + public void setTasks(ArrayList tasks) { + this.tasks = tasks; + } + + public ArrayList getTasks() { + return tasks; + } + + /** + * Returns a Task object based on the task's information and type. + * The task information for {@link Todo} has no restrictions. + * The task information for {@link Deadline} must contain "/by", event date and end time. + * The task information for {@link Event} must contain "/at", event date, start and end time. + * The taskType must be either {@link Todo}, {@link Event} or {@link Deadline} + * + * @param taskInfo the information of the task + * @param taskType the type of the task, e.g. event, deadline or todo + * @return Task + * @see Task + * @see Todo + * @see Deadline + * @see Event + */ + public Task createTask(String taskInfo, String taskType) { + assert !Objects.equals(taskInfo, ""); + assert (Objects.equals(taskType, "event") || Objects.equals(taskType, "todo") || Objects.equals(taskType, "deadline")); + switch (taskType.trim()) { + case DETECT_ADD_TODO: + Todo t = new Todo(taskInfo, getId()); + addTask(t); + return t; + case DETECT_ADD_EVENT: + ArrayList addInfo = new ArrayList(Arrays.asList(taskInfo.split("/at"))); + logger.info("add info for event: " + addInfo); + Event e = new Event(addInfo.get(0), addInfo.get(1), getId()); + addTask(e); + return e; + case DETECT_ADD_DEADLINE: + ArrayList deadlineInfo = new ArrayList(Arrays.asList(taskInfo.split("/by"))); + Deadline d = new Deadline(deadlineInfo.get(0), deadlineInfo.get(1), getId()); + addTask(d); + return d; + } + return new Task(taskInfo, getId()); + } + + public void listTasks() { + listTasks(tasks); + } + + public void listTasks(ArrayList l) { + if (tasks.toArray().length == 0) { + return; + } + l.forEach(x -> System.out.println(x.toString())); + } + + public void addTask(Task t) { + tasks.add(t); + } + + public Task markTaskDone(Integer taskId) { + Task tx = null; + if (tasks == null) { + return null; + } + for (int i = 0; i < tasks.size(); i++) { + Task t = tasks.get(i); + if (Objects.equals(t.getId(), taskId)) { + tx = t; + Todo todo = (Todo) t; + todo.setDone(true); + t = (Task) todo; + tasks.set(i, t); + } + } + return tx; + } + + public Task deleteTask(Integer taskId) { + for (int i = 0; i < tasks.size(); i++) { + if (tasks.get(i).getId() != null && tasks.get(i).getId().equals(taskId)) { + Task t = tasks.get(i); + tasks.remove(t); + return t; + } + } + return null; + } + + public ArrayList viewTaskOn(LocalDate date) { + logger.info("viewTasksOn date: " + date + ", current task list: " + tasks); + ArrayList results = new ArrayList<>(); + if (date == null) { + logger.info("viewTasksOn got null date"); + return results; + } + tasks.forEach(t -> { + try { + Deadline e = (Deadline) t; + logger.info("looking at task: " + t + " date for this task " + e.getDate()); + if (e.getDate().equals(date)) { + logger.info("added successfully to results " + e); + results.add(e); + } + } catch (ClassCastException e) { + logger.info("casting to deadline class got error, item could be todo type, error: " + e.getMessage() + " object: " + t); + } + }); + return results; + } + + public Integer getId() { + return getNumOfTasks(); + } + + public Integer getNumOfTasks() { + return tasks.size(); + } +} \ No newline at end of file diff --git a/src/main/java/Todo.java b/src/main/java/Todo.java new file mode 100644 index 00000000..932620a7 --- /dev/null +++ b/src/main/java/Todo.java @@ -0,0 +1,34 @@ +public class Todo extends Task { + public boolean isDone; + + public Todo(String desc, int id) { + super(desc, id); + isDone = false; + Logger logger = new Logger(); + logger.init(""); + } + + public void setDone(boolean done) { + isDone = done; + } + + public boolean isDone() { + return isDone; + } + + @Override + public String toString() { + String status = isDone ? "X" : " "; + return id + ". [T][" + status + "] " + super.toString(); + } + + @Override + public String toTask() { + return super.toTask() + "," + (isDone ? 1 : 0); + } + + @Override + public String getType() { + return "todo"; + } +} \ No newline at end of file diff --git a/src/main/java/UserInterface.java b/src/main/java/UserInterface.java new file mode 100644 index 00000000..e2d20b03 --- /dev/null +++ b/src/main/java/UserInterface.java @@ -0,0 +1,102 @@ +import java.awt.datatransfer.SystemFlavorMap; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicReference; + +public class UserInterface { + private final static String STMT_END = "Bye 👋🏻😢. Dukie hopes to see you again soon!"; + private final static String STMT_DONE = "Nice! 🚀 Dukie has marked this task as done: "; + private final static String ERROR_PREFIX = "Oops Dukie did not quite understand that."; + private final static String STMT_DELETE = "Noted 👁👄👁. Dukie has removed this task: "; + + public UserInterface(TaskManager m) { + this.manager = m; + } + + private final Parser parser = new Parser(); + private final Scanner in = new Scanner(System.in); + private final TaskManager manager; + private String input = ""; + private Boolean isExit = false; + + public String getGreeting() { + Calendar c = Calendar.getInstance(); + int timeOfDay = c.get(Calendar.HOUR_OF_DAY); + String msg = ""; + + if (timeOfDay >= 0 && timeOfDay < 12) { + msg = "Good morning ⛅️"; + } else if (timeOfDay >= 12 && timeOfDay < 16) { + msg = "Good afternoon ☀️"; + } else if (timeOfDay >= 16 && timeOfDay < 21) { + msg = "Good evening 🌥"; + } else if (timeOfDay >= 21 && timeOfDay < 24) { + msg = "Good night 🌙"; + } + msg += "! I'm Dukie 😇~\nWhat can I do for you?"; + return msg; + } + + public void start() { + System.out.println(getGreeting()); + } + + public String getInput() { + input = in.nextLine(); + return input; + } + + public void end() { + System.out.println(STMT_END); + } + + public void parseInput() { + parser.parseInput(input); + } + + public Boolean isExit() { + return isExit; + } + + public void processInput() { + String instruction = parser.getInstruction(); + String taskInfo = parser.getTaskInfo(); + String firstToken = parser.getFirstToken(); + + if (parser.isExit()) { + isExit = true; + return; + } + + if (parser.isList()) { + manager.listTasks(); + } else if (parser.isDone()) { + Task t = manager.markTaskDone(Integer.parseInt((firstToken))); + System.out.println(t == null ? "🤡 Oops this task doesn't exist, try \"list\" to see all your tasks." : STMT_DONE + "\n" + t); + } else if (parser.isDelete()) { + Task t = manager.deleteTask(Integer.parseInt((firstToken))); + System.out.println(t == null ? "🤡 Oops this task doesn't exist, try \"list\" to see all your tasks." : STMT_DELETE + "\n " + t); + } else if (parser.isFind()) { + ArrayList li = manager.findTask(firstToken); + if (li.size() == 0) { + System.out.println("🤡 No tasks with keyword \"" + firstToken + "\", try \"list\" to see all your tasks."); + } else { + manager.listTasks(li); + } + } else if (parser.isView()) { + ArrayList li = manager.viewTaskOn(parser.stringToDate(firstToken)); + if (li.size() == 0) { + System.out.println("🤡 No tasks on \"" + firstToken + "\", try \"list\" to see all your tasks."); + } else { + manager.listTasks(li); + } + } else if (parser.isAdd()) { + Task t = manager.createTask(taskInfo, instruction); + System.out.println("Got it! 👌 I've added this " + t.getType() + ": \n" + t.toString()); + } else { + System.out.println("🤡 Dukie did not understand the command, try again?"); + } + System.out.println("You have " + manager.getNumOfTasks() + " task(s) in the main list 😇."); + } +} diff --git a/src/test/java/TaskManagerTest.java b/src/test/java/TaskManagerTest.java new file mode 100644 index 00000000..8cecb2e8 --- /dev/null +++ b/src/test/java/TaskManagerTest.java @@ -0,0 +1,141 @@ +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; + +public class TaskManagerTest { + @Test + public void createTodoTest() { + String eventType = "todo"; + String eventInfo = "read books"; + + TaskManager tm = new TaskManager(); + Task t = tm.createTask(eventInfo, eventType); + Todo e = (Todo) t; + System.out.println(e.toString()); + assertEquals(e.getType(), eventType); + assertEquals(e.getDescription(), eventInfo); + } + + @Test + public void createEventTest() { + String eventType = "event"; + String eventDesc = "project meeting"; + String eventStartTime = "18:00"; + String eventEndTime = "21:00"; + String eventDate = "2019-12-01"; + String eventInfo = eventDesc + "/at" + eventDate + " " + eventStartTime + "-" + eventEndTime; + + TaskManager tm = new TaskManager(); + Task t = tm.createTask(eventInfo, eventType); + assertEquals(t.getType(), eventType); + Event e = (Event) t; + System.out.println(e.toString()); + assertEquals(e.getDescription(), eventDesc); + Assertions.assertEquals(e.getDate().toString(), eventDate); + } + + @Test + public void createDeadlineTest() { + String eventType = "deadline"; + String eventDesc = "submit report"; + String eventEndTime = "21:00"; + String eventDate = "2019-12-01"; + String eventInfo = eventDesc + "/by" + eventDate + " " + eventEndTime; + + TaskManager tm = new TaskManager(); + Task t = tm.createTask(eventInfo, eventType); + assertEquals(t.getType(), eventType); + Deadline e = (Deadline) t; + System.out.println(e.toString()); + assertEquals(e.getDescription(), eventDesc); + Assertions.assertEquals(e.getDate().toString(), eventDate); + } + + @Test + public void findTest() { + // Event 1 + String eventType = "deadline"; + String eventDesc = "submit report"; + String eventEndTime = "21:00"; + String eventDate = "2019-12-01"; + String eventInfo = eventDesc + "/by" + eventDate + " " + eventEndTime; + + TaskManager tm = new TaskManager(); + Task t = tm.createTask(eventInfo, eventType); + assertEquals(t.getType(), eventType); + Deadline e = (Deadline) t; + System.out.println(e.toString()); + assertEquals(e.getDescription(), eventDesc); + Assertions.assertEquals(e.getDate().toString(), eventDate); + + // Event 2 + eventType = "event"; + eventDesc = "project meeting"; + String eventStartTime = "18:00"; + eventEndTime = "21:00"; + eventDate = "2019-12-01"; + eventInfo = eventDesc + "/at" + eventDate + " " + eventStartTime + "-" + eventEndTime; + + t = tm.createTask(eventInfo, eventType); + assertEquals(t.getType(), eventType); + Event event = (Event) t; + System.out.println(event.toString()); + assertEquals(event.getDescription(), eventDesc); + Assertions.assertEquals(event.getDate().toString(), eventDate); + + ArrayList tasks = tm.findTask("project"); + assertEquals(tasks.toArray().length, 1, "too many returns"); + assertEquals(tasks.get(0).getId(), 1, "did not get expected id"); + } + + @Test + public void viewTest() { + TaskManager tm = new TaskManager(); + Parser p = new Parser(); + ArrayList expected = new ArrayList<>(); + // Event 1 + String eventType = "deadline"; + String eventDesc = "submit report"; + String eventEndTime = "21:00"; + String eventDate = "2019-12-01"; + String eventInfo = eventDesc + "/by" + eventDate + " " + eventEndTime; + Task t = tm.createTask(eventInfo, eventType); + expected.add(t); + assertEquals(t.getType(), eventType); + Deadline e = (Deadline) t; + System.out.println(e.toString()); + assertEquals(e.getDescription(), eventDesc); + Assertions.assertEquals(e.getDate().toString(), eventDate); + // Event 2 + eventType = "event"; + eventDesc = "project meeting"; + String eventStartTime = "18:00"; + eventEndTime = "21:00"; + eventDate = "2019-12-01"; + eventInfo = eventDesc + "/at" + eventDate + " " + eventStartTime + "-" + eventEndTime; + t = tm.createTask(eventInfo, eventType); + expected.add(t); + assertEquals(t.getType(), eventType); + Event event = (Event) t; + System.out.println(event.toString()); + assertEquals(event.getDescription(), eventDesc); + Assertions.assertEquals(event.getDate().toString(), eventDate); + // View + ArrayList tasks = tm.viewTaskOn(p.stringToDate(eventDate)); + assertEquals(2, tasks.toArray().length, "too many returns"); + expected.forEach(expect -> { + Task actual = tasks.stream().filter(task -> Objects.equals(task.getId(), expect.getId())).findFirst().orElse(null); + assertNotNull(actual); + Deadline ex = (Deadline) expect; + Deadline a = (Deadline) actual; + assertEquals(ex.getId(), a.getId(), "id mismatches"); + assertEquals(ex.getDescription(), a.getDescription(), "description mismatches"); + assertEquals(ex.getDate(), a.getDate(), "date mismatches"); + assertEquals(ex.getEndTime(), a.getEndTime(), "end_time mismatches"); + }); + } +} \ No newline at end of file