diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a195c7b --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store +/db/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..0b135ed --- /dev/null +++ b/build.gradle @@ -0,0 +1,47 @@ +plugins { + id 'java' + id 'application' +} + +group 'com.example' +version '1.0' + +repositories { + mavenCentral() +} + +dependencies { + // jackson + implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' + + // test + testImplementation 'org.junit.jupiter:junit-jupiter:5.11.3' + testImplementation 'org.assertj:assertj-core:3.26.3' + testImplementation 'org.mockito:mockito-core:4.11.0' +} + +application { + mainClass = 'Main' +} + +sourceSets { + main { + java { + srcDirs = ['src/main/java'] + } + } + test { + java { + srcDirs = ['src/test/java'] + } + } +} + +tasks.test { + useJUnitPlatform() + testLogging { + events "passed", "skipped", "failed" + exceptionFormat "full" + showStandardStreams = true + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 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 0000000..1af9e09 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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/HEAD/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/com/ll/wisesaying/App.java b/src/main/java/com/ll/wisesaying/App.java new file mode 100644 index 0000000..09a5983 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/App.java @@ -0,0 +1,36 @@ +package com.ll.wisesaying; + +import static com.ll.wisesaying.util.InputUtil.*; +import static com.ll.wisesaying.util.OutputUtil.*; +import static com.ll.wisesaying.util.Validator.*; + +import java.io.IOException; + +import com.ll.wisesaying.controller.WiseSayingController; +import com.ll.wisesaying.exception.WiseSayingException; + +public class App { + private final WiseSayingController wiseSayingController; + + public App(WiseSayingController wiseSayingController) { + this.wiseSayingController = wiseSayingController; + } + + public void run() throws IOException { + printlnMessage(HEADER); + + while (true) { + String cmd = inputMessage(); + + if (cmd.equals(END)) + return; + + try { + validateInput(cmd); + wiseSayingController.process(cmd); + } catch (WiseSayingException e) { + printError(e.getMessage()); + } + } + } +} diff --git a/src/main/java/com/ll/wisesaying/Main.java b/src/main/java/com/ll/wisesaying/Main.java new file mode 100644 index 0000000..52728e2 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/Main.java @@ -0,0 +1,16 @@ +package com.ll.wisesaying; + +import java.io.IOException; + +import com.ll.wisesaying.controller.WiseSayingController; +import com.ll.wisesaying.repository.WiseSayingRepository; +import com.ll.wisesaying.service.WiseSayingService; + +public class Main { + + public static void main(String[] args) throws IOException { + new App( + new WiseSayingController(new WiseSayingService(new WiseSayingRepository())) + ).run(); + } +} diff --git a/src/main/java/com/ll/wisesaying/constant/Constant.java b/src/main/java/com/ll/wisesaying/constant/Constant.java new file mode 100644 index 0000000..49f30f5 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/constant/Constant.java @@ -0,0 +1,31 @@ +package com.ll.wisesaying.constant; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class Constant { + + public static final ObjectMapper objectMapper = new ObjectMapper(); + public static final String initIdx = "0"; + public static final String SEPARATOR = " / "; + public static final String LEFT_BRACKET = "["; + public static final String RIGHT_BRACKET = "]"; + public static final String TXT = ".txt"; + public static final String JSON = ".json"; + public static final String DB_FOLDER = "db/wiseSaying/"; + public static final String LAST_ID_FILE = "lastId" + TXT; + public static final String ALL_FILE = "data" + JSON; + public static final int PAGE_SIZE = 5; + public static final int PAGE_NUM = 2; + + public static Path getPath(int idx) { + String path = DB_FOLDER + idx + JSON; + return Paths.get(path); + } + + public static Path getPath(String path) { + return Paths.get(path); + } +} diff --git a/src/main/java/com/ll/wisesaying/controller/WiseSayingController.java b/src/main/java/com/ll/wisesaying/controller/WiseSayingController.java new file mode 100644 index 0000000..da9b09d --- /dev/null +++ b/src/main/java/com/ll/wisesaying/controller/WiseSayingController.java @@ -0,0 +1,120 @@ +package com.ll.wisesaying.controller; + +import static com.ll.wisesaying.constant.Constant.*; +import static com.ll.wisesaying.util.InputUtil.*; +import static com.ll.wisesaying.util.OutputUtil.*; + +import java.io.IOException; +import java.util.List; + +import com.ll.wisesaying.domain.Search; +import com.ll.wisesaying.domain.WiseSaying; +import com.ll.wisesaying.service.WiseSayingService; + +public class WiseSayingController { + + private final WiseSayingService wiseSayingService; + + public WiseSayingController(WiseSayingService wiseSayingService) { + this.wiseSayingService = wiseSayingService; + } + + public void process(String cmd) throws IOException { + if (cmd.equals(ENROLL)) { + register(); + return; + } + + if (cmd.equals(LIST)) { + list(); + return; + } + + if (cmd.startsWith(DELETE)) { + delete(cmd); + return; + } + + if (cmd.startsWith(EDIT)) { + edit(cmd); + return; + } + + if (cmd.equals(BUILD)) { + build(); + return; + } + + if (!cmd.equals(LIST) && cmd.startsWith(LIST)) { + search(cmd); + return; + } + } + + public void register() throws IOException { + printMessage(WISESAYING); + String content = inputMessage(); + + printMessage(AUTHOR); + String author = inputMessage(); + + WiseSaying wiseSaying = wiseSayingService.inputWiseSaying(content, author); + wiseSayingService.saveFile(wiseSaying); + + printlnMessage(wiseSaying.getId() + ENROLLED); + } + + public void list() { + printlnMessage(FORM); + printlnMessage(TABLE_SEPARATOR); + + printWiseSayings(wiseSayingService.getWiseSayings()); + + printPage(1L); + } + + public void delete(String cmd) throws IOException { + int idx = wiseSayingService.deleteWiseSaying(cmd); + wiseSayingService.deleteFile(idx); + + printlnMessage(idx + DELETED); + } + + public void edit(String cmd) throws IOException { + WiseSaying wiseSaying = wiseSayingService.getWiseSaying(cmd); + + printlnMessage(EXISTING_WISESAYING + wiseSaying.getContent()); + printMessage(WISESAYING); + String content = inputMessage(); + + printlnMessage(EXISTING_AUTHOR + wiseSaying.getAuthor()); + printMessage(AUTHOR); + String author = inputMessage(); + + WiseSaying newWiseSaying = wiseSayingService.editWiseSaying(wiseSaying.getId(), content, author); + printlnMessage(WISESAYING + newWiseSaying.getContent()); + printlnMessage(AUTHOR + newWiseSaying.getAuthor()); + + wiseSayingService.saveFile(newWiseSaying); + } + + public void build() throws IOException { + wiseSayingService.buildPhrase(); + printlnMessage(ALL_FILE + BUILDED); + } + + public void search(String cmd) { + Search search = getSearch(cmd); + + printListHeader(search); + + List wiseSayings = wiseSayingService.getWiseSayings(search); + + printlnMessage(FORM); + printlnMessage(TABLE_SEPARATOR); + + printWiseSayings(wiseSayings); + + printPage(search.page()); + } +} diff --git a/src/main/java/com/ll/wisesaying/domain/Search.java b/src/main/java/com/ll/wisesaying/domain/Search.java new file mode 100644 index 0000000..8429a67 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/domain/Search.java @@ -0,0 +1,23 @@ +package com.ll.wisesaying.domain; + +public record Search( + String keywordType, + String keyword, + long page +) { + public static Search of(String keyWordType, String keyword, long page) { + return new Search(keyWordType, keyword, page); + } + + public static Search of(String keyWordType, String keyword) { + return new Search(keyWordType, keyword, 1L); + } + + public static Search of(long page) { + return new Search(null, null, page); + } + + public static Search of() { + return new Search(null, null, 1L); + } +} diff --git a/src/main/java/com/ll/wisesaying/domain/WiseSaying.java b/src/main/java/com/ll/wisesaying/domain/WiseSaying.java new file mode 100644 index 0000000..4568352 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/domain/WiseSaying.java @@ -0,0 +1,45 @@ +package com.ll.wisesaying.domain; + +public class WiseSaying implements Comparable { + private int id; + private String content; + private String author; + + public WiseSaying() { + } + + public WiseSaying(int id, String content, String author) { + this.id = id; + this.content = content; + this.author = author; + } + + @Override + public int compareTo(WiseSaying o) { + return Integer.compare(o.id, this.id); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} diff --git a/src/main/java/com/ll/wisesaying/exception/IndexException.java b/src/main/java/com/ll/wisesaying/exception/IndexException.java new file mode 100644 index 0000000..fa17930 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/exception/IndexException.java @@ -0,0 +1,7 @@ +package com.ll.wisesaying.exception; + +public class IndexException extends WiseSayingException { + public IndexException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ll/wisesaying/exception/InputException.java b/src/main/java/com/ll/wisesaying/exception/InputException.java new file mode 100644 index 0000000..3081c2f --- /dev/null +++ b/src/main/java/com/ll/wisesaying/exception/InputException.java @@ -0,0 +1,7 @@ +package com.ll.wisesaying.exception; + +public class InputException extends WiseSayingException { + public InputException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ll/wisesaying/exception/NotFoundException.java b/src/main/java/com/ll/wisesaying/exception/NotFoundException.java new file mode 100644 index 0000000..1671a99 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/exception/NotFoundException.java @@ -0,0 +1,7 @@ +package com.ll.wisesaying.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ll/wisesaying/exception/WiseSayingException.java b/src/main/java/com/ll/wisesaying/exception/WiseSayingException.java new file mode 100644 index 0000000..91936a5 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/exception/WiseSayingException.java @@ -0,0 +1,7 @@ +package com.ll.wisesaying.exception; + +public class WiseSayingException extends RuntimeException { + public WiseSayingException(String message) { + super(message); + } +} diff --git a/src/main/java/com/ll/wisesaying/repository/WiseSayingRepository.java b/src/main/java/com/ll/wisesaying/repository/WiseSayingRepository.java new file mode 100644 index 0000000..4870104 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/repository/WiseSayingRepository.java @@ -0,0 +1,134 @@ +package com.ll.wisesaying.repository; + +import static com.ll.wisesaying.constant.Constant.*; +import static com.ll.wisesaying.util.InputUtil.*; +import static com.ll.wisesaying.util.OutputUtil.*; +import static java.util.stream.Collectors.*; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import com.ll.wisesaying.domain.Search; +import com.ll.wisesaying.domain.WiseSaying; +import com.ll.wisesaying.exception.IndexException; +import com.ll.wisesaying.exception.InputException; + +public class WiseSayingRepository { + + public final Map db = new TreeMap<>(Comparator.reverseOrder()); + private int idx; + + public WiseSayingRepository() throws IOException { + init(); + } + + public void init() throws IOException { + checkFileState(); + idx = getLastIdx(); + + for (int i = 1; i <= idx; i++) { + db.put(i, getWiseSaying(i)); + } + } + + private void checkFileState() throws IOException { + Path path = getPath(DB_FOLDER); + if (!Files.exists(path)) { + Files.createDirectories(path); + } + + Path lastPath = getPath(DB_FOLDER + LAST_ID_FILE); + if (!Files.exists(lastPath)) { + Files.writeString(lastPath, initIdx); + } + } + + public void saveAllWiseSayings(List wiseSayings) throws IOException { + String content = objectMapper.writeValueAsString(wiseSayings); + Files.writeString(getPath(DB_FOLDER + ALL_FILE), content); + } + + public void saveWiseSaying(WiseSaying wiseSaying) throws IOException { + String content = objectMapper.writeValueAsString(wiseSaying); + Files.writeString(getPath(wiseSaying.getId()), content); + } + + public WiseSaying getWiseSaying(int idx) throws IOException { + if (!Files.exists(getPath(idx))) { + throw new FileNotFoundException(); + } + + String json = Files.readString(getPath(idx)); + return objectMapper.readValue(json, WiseSaying.class); + } + + public int getLastIdx() throws IOException { + String lastId = Files.readString(getPath(DB_FOLDER + LAST_ID_FILE)).trim(); + return lastId.isEmpty() ? 0 : Integer.parseInt(lastId); + } + + public void saveLastIdx(int lastId) throws IOException { + Files.writeString(Paths.get(DB_FOLDER + LAST_ID_FILE), String.valueOf(lastId)); + } + + public int getNextIdx() { + return ++idx; + } + + public int getIdx() { + return idx; + } + + public Map getDB() { + return db; + } + + public void containsWiseSaying(int idx) { + if (!db.containsKey(idx)) { + throw new IndexException(idx + IDX_NOT_EXIST); + } + } + + public List findWiseSayings(Search search) { + List wiseSayings = null; + + if(search.keywordType() == null && search.keyword() == null) { + wiseSayings = new ArrayList<>(db.values()); + + return getSubWiseSayings(wiseSayings, search.page()); + } + + if (search.keywordType().equals(ENG_CONTENT)) { + wiseSayings = db.values().stream() + .filter(wiseSaying -> wiseSaying.getContent().contains(search.keyword())) + .collect(toList()); + } + + if (search.keywordType().equals(ENG_AUTHOR)) { + wiseSayings = db.values().stream() + .filter(wiseSaying -> wiseSaying.getAuthor().contains(search.keyword())) + .collect(toList()); + } + + if (wiseSayings == null || wiseSayings.isEmpty()) { + throw new InputException(NOT_EXIST); + } + + return getSubWiseSayings(wiseSayings, search.page()); + } + + public List getSubWiseSayings(List wiseSayings, long page) { + int start = (int) ((page - 1) * PAGE_SIZE); + int end = Math.min(start + PAGE_SIZE - 1, db.size() - 1); + + return new ArrayList<>(wiseSayings).subList(start, end + 1); + } +} diff --git a/src/main/java/com/ll/wisesaying/service/WiseSayingService.java b/src/main/java/com/ll/wisesaying/service/WiseSayingService.java new file mode 100644 index 0000000..7ae14e4 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/service/WiseSayingService.java @@ -0,0 +1,76 @@ +package com.ll.wisesaying.service; + +import static com.ll.wisesaying.constant.Constant.*; +import static com.ll.wisesaying.util.InputUtil.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import com.ll.wisesaying.domain.Search; +import com.ll.wisesaying.domain.WiseSaying; +import com.ll.wisesaying.repository.WiseSayingRepository; + +public class WiseSayingService { + + private final WiseSayingRepository wiseSayingRepository; + + public WiseSayingService(WiseSayingRepository wiseSayingRepository) { + this.wiseSayingRepository = wiseSayingRepository; + } + + public WiseSaying inputWiseSaying(String content, String author) { + int idx = wiseSayingRepository.getNextIdx(); + + WiseSaying wiseSaying = new WiseSaying(idx, content, author); + wiseSayingRepository.getDB().put(idx, wiseSaying); + + return wiseSaying; + } + + public List getWiseSayings() { + return wiseSayingRepository.getSubWiseSayings(new ArrayList<>(wiseSayingRepository.getDB().values()), 1L); + } + + public List getWiseSayings(Search search) { + return wiseSayingRepository.findWiseSayings(search); + } + + public Integer deleteWiseSaying(String cmd) { + int idx = getCmdIdx(cmd); + wiseSayingRepository.containsWiseSaying(idx); + + wiseSayingRepository.getDB().remove(idx); + + return idx; + } + + public WiseSaying editWiseSaying(int idx, String content, String author) { + WiseSaying newWiseSaying = new WiseSaying(idx, content, author); + wiseSayingRepository.getDB().put(idx, newWiseSaying); + + return newWiseSaying; + } + + public WiseSaying getWiseSaying(String cmd) { + int idx = getCmdIdx(cmd); + wiseSayingRepository.containsWiseSaying(idx); + + return wiseSayingRepository.getDB().get(idx); + } + + public void buildPhrase() throws IOException { + wiseSayingRepository.saveAllWiseSayings(new ArrayList<>(wiseSayingRepository.getDB().values())); + } + + public void saveFile(WiseSaying wiseSaying) throws IOException { + wiseSayingRepository.saveWiseSaying(wiseSaying); + wiseSayingRepository.saveLastIdx(wiseSaying.getId()); + } + + public void deleteFile(int idx) throws IOException { + Files.delete(getPath(idx)); + wiseSayingRepository.saveLastIdx(--idx); + } +} diff --git a/src/main/java/com/ll/wisesaying/util/InputUtil.java b/src/main/java/com/ll/wisesaying/util/InputUtil.java new file mode 100644 index 0000000..43b4345 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/util/InputUtil.java @@ -0,0 +1,73 @@ +package com.ll.wisesaying.util; + +import static com.ll.wisesaying.util.OutputUtil.*; +import static com.ll.wisesaying.util.Validator.*; +import static java.lang.Long.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +import com.ll.wisesaying.domain.Search; +import com.ll.wisesaying.exception.InputException; + +public class InputUtil { + public static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + public static final String END = "종료"; + public static final String ENROLL = "등록"; + public static final String LIST = "목록"; + public static final String DELETE = "삭제"; + public static final String EDIT = "수정"; + public static final String BUILD = "빌드"; + public static final String ENG_CONTENT = "content"; + public static final String ENG_AUTHOR = "author"; + public static final String CMD_SEPARATOR = "\\?|id|="; + public static final String SEARCH_SEPARATOR = "\\?|keywordType|&|keyword|page|="; + + public static void resetBufferedReader() { + bf = new BufferedReader(new InputStreamReader(System.in)); + } + + public static String inputMessage() throws IOException { + return bf.readLine(); + } + + public static int getCmdIdx(String cmd) { + String[] tokens = getTokens(cmd, CMD_SEPARATOR); + + validateCmd(tokens); + + int idx = Integer.valueOf(tokens[tokens.length - 1]); + return idx; + } + + public static Search getSearch(String cmd) { + String[] tokens = getTokens(cmd, SEARCH_SEPARATOR); + + validateCmd(tokens); + validatePage(tokens); + + if (tokens.length == 2) { + return Search.of(valueOf(tokens[1])); + } + + if (tokens.length == 3) { + return Search.of(tokens[1], tokens[2]); + } + + if (tokens.length == 4) { + return Search.of(tokens[1], tokens[2], valueOf(tokens[3])); + } + + throw new InputException(ILLEGAL_CMD); + } + + private static String[] getTokens(String cmd, String cmdSeparator) { + String[] tokens = cmd.split(cmdSeparator); + tokens = Arrays.stream(tokens) + .filter(token -> !token.isEmpty()) + .toArray(String[]::new); + return tokens; + } +} diff --git a/src/main/java/com/ll/wisesaying/util/OutputUtil.java b/src/main/java/com/ll/wisesaying/util/OutputUtil.java new file mode 100644 index 0000000..cbfa983 --- /dev/null +++ b/src/main/java/com/ll/wisesaying/util/OutputUtil.java @@ -0,0 +1,77 @@ +package com.ll.wisesaying.util; + +import static com.ll.wisesaying.constant.Constant.*; + +import java.util.List; + +import com.ll.wisesaying.domain.Search; +import com.ll.wisesaying.domain.WiseSaying; + +public class OutputUtil { + + public static final String HEADER = "== 명언 앱 =="; + public static final String FORM = "번호 / 작가 / 명언"; + public static final String TABLE_SEPARATOR = "----------------------"; + public static final String WISESAYING = "명언 : "; + public static final String EXISTING_WISESAYING = "명언(기존) : "; + public static final String AUTHOR = "작가 : "; + public static final String EXISTING_AUTHOR = "작가(기존) : "; + public static final String KEYWORD_TYPE = "검색타입 : "; + public static final String KEYWORD = "검색어 : "; + public static final String PAGE = "페이지 : "; + public static final String ENROLLED = "번 명언이 등록되었습니다."; + public static final String DELETED = "번 명언이 삭제되었습니다."; + public static final String BUILDED = "파일의 내용이 갱신되었습니다."; + public static final String IDX_NOT_EXIST = "번 명언은 존재하지 않습니다."; + public static final String NOT_EXIST = "해당 명언은 존재하지 않습니다."; + public static final String ILLEGAL_INPUT = "등록, 목록, 삭제, 수정, 빌드 중에 입력해주세요."; + public static final String ILLEGAL_CMD = "명령어 형식이 올바르지 않습니다."; + + public static void printError(String message) { + System.out.println(message); + } + + public static void printMessage(String message) { + System.out.print(message); + } + + public static void printlnMessage(String message) { + System.out.println(message); + } + + public static void printWiseSayings(List wiseSayings) { + wiseSayings.forEach((wiseSaying) -> { + System.out.println(wiseSaying.getId() + + SEPARATOR + wiseSaying.getContent() + + SEPARATOR + wiseSaying.getAuthor()); + }); + } + + public static void printPage(long page) { + long previous = page % PAGE_NUM == 0 ? page - 1 : page; + long next = page % PAGE_NUM == 0 ? page : page + 1; + + StringBuilder output = new StringBuilder(); + + if (page == previous) { + output.append(LEFT_BRACKET).append(previous).append(RIGHT_BRACKET).append(SEPARATOR).append(next); + } else { + output.append(previous).append(SEPARATOR).append(LEFT_BRACKET).append(next).append(RIGHT_BRACKET); + } + + printlnMessage(PAGE + output); + } + + public static void printListHeader(Search search) { + if (search.keywordType() == null && search.keyword() == null) + return; + + printlnMessage(TABLE_SEPARATOR); + printMessage(KEYWORD_TYPE); + printlnMessage(search.keywordType()); + + printMessage(KEYWORD); + printlnMessage(search.keyword()); + printlnMessage(TABLE_SEPARATOR); + } +} diff --git a/src/main/java/com/ll/wisesaying/util/Validator.java b/src/main/java/com/ll/wisesaying/util/Validator.java new file mode 100644 index 0000000..5425f4f --- /dev/null +++ b/src/main/java/com/ll/wisesaying/util/Validator.java @@ -0,0 +1,34 @@ +package com.ll.wisesaying.util; + +import static com.ll.wisesaying.util.InputUtil.*; +import static com.ll.wisesaying.util.OutputUtil.*; + +import com.ll.wisesaying.exception.InputException; + +public class Validator { + public static void validateInput(String cmd) { + if (!(cmd.contains(ENROLL) + || cmd.contains(LIST) + || cmd.contains(DELETE) + || cmd.contains(EDIT) + || cmd.contains(BUILD))) { + throw new InputException(ILLEGAL_INPUT); + } + } + + public static void validateCmd(String[] tokens) { + if (tokens.length <= 1) { + throw new InputException(ILLEGAL_CMD); + } + } + + public static void validatePage(String[] tokens) { + if (tokens.length == 2 || tokens.length == 4) { + String lastToken = tokens[tokens.length - 1]; + if (lastToken.chars().anyMatch(c -> !Character.isDigit(c))) { + throw new InputException(ILLEGAL_CMD); + } + } + } + +} diff --git a/src/test/java/com/ll/wisesaying/controller/WiseSayingControllerTest.java b/src/test/java/com/ll/wisesaying/controller/WiseSayingControllerTest.java new file mode 100644 index 0000000..d3679bd --- /dev/null +++ b/src/test/java/com/ll/wisesaying/controller/WiseSayingControllerTest.java @@ -0,0 +1,138 @@ +package com.ll.wisesaying.controller; + +import com.ll.wisesaying.service.WiseSayingService; +import com.ll.wisesaying.repository.WiseSayingRepository; +import com.ll.wisesaying.util.InputUtil; +import com.ll.wisesaying.util.TestUtil; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import static com.ll.wisesaying.constant.Constant.*; +import static com.ll.wisesaying.util.OutputUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class WiseSayingControllerTest { + + private WiseSayingRepository wiseSayingRepository; + private WiseSayingService wiseSayingService; + private WiseSayingController controller; + private ByteArrayOutputStream output; + private final Path path = Paths.get(DB_FOLDER); + + @BeforeEach + void setup() throws IOException { + wiseSayingRepository = new WiseSayingRepository(); + wiseSayingService = new WiseSayingService(wiseSayingRepository); + controller = new WiseSayingController(wiseSayingService); + + output = TestUtil.setOutToByteArray(); + } + + @AfterEach + void cleanup() throws IOException { + Files.walk(path) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(file -> { + if (!file.delete()) { + System.err.println("파일 삭제 실패"); + } + }); + Files.deleteIfExists(path.getParent()); + + System.setIn(System.in); + TestUtil.clearSetOutToByteArray(output); + } + + @Test + void registerTest() throws IOException { + // Given + String input = """ + 현재를 사랑하라. + 작자미상 + """; + System.setIn(TestUtil.getInputStream(input)); + InputUtil.resetBufferedReader(); + + // When + controller.register(); + + // Then + Path savedFilePath = Path.of("db/wiseSaying/1.json"); + assertThat(Files.exists(savedFilePath)).isTrue(); + + String savedContent = Files.readString(savedFilePath); + assertThat(savedContent).contains("현재를 사랑하라.", "작자미상"); + } + + @Test + void deleteTest() throws IOException { + // Given + controller.register(); + + // When + controller.delete("삭제?id=1"); + + // Then + Path savedFilePath = Path.of("db/wiseSaying/1.json"); + assertThat(Files.exists(savedFilePath)).isFalse(); + } + + @Test + void editTest() throws IOException { + // Given + String input = """ + 현재를 사랑하라. + 작자미상 + 수정된 명언 + 수정된 작가 + """; + System.setIn(TestUtil.getInputStream(input)); + InputUtil.resetBufferedReader(); + + controller.register(); + + // When + controller.edit("수정?id=1"); + + // Then + Path savedFilePath = Path.of("db/wiseSaying/1.json"); + assertThat(Files.exists(savedFilePath)).isTrue(); + + String savedContent = Files.readString(savedFilePath); + assertThat(savedContent).contains("수정된 명언", "수정된 작가"); + } + + @Test + void buildTest() throws IOException { + // Given + String input = """ + 현재를 사랑하라. + 작자미상 + """; + System.setIn(TestUtil.getInputStream(input)); + InputUtil.resetBufferedReader(); + + controller.register(); + + // When + controller.build(); + + // Then + Path allFilePath = Path.of("db/wiseSaying/data.json"); + assertThat(Files.exists(allFilePath)).isTrue(); + + String allContent = Files.readString(allFilePath); + assertThat(allContent).contains("현재를 사랑하라.", "작자미상"); + } +} diff --git a/src/test/java/com/ll/wisesaying/util/TestUtil.java b/src/test/java/com/ll/wisesaying/util/TestUtil.java new file mode 100644 index 0000000..d0427b2 --- /dev/null +++ b/src/test/java/com/ll/wisesaying/util/TestUtil.java @@ -0,0 +1,25 @@ +package com.ll.wisesaying.util; + +import java.io.*; + +public class TestUtil { + + public static ByteArrayInputStream getInputStream(String input) { + return new ByteArrayInputStream(input.getBytes()); + } + + public static ByteArrayOutputStream setOutToByteArray() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + return output; + } + + public static void clearSetOutToByteArray(ByteArrayOutputStream output) { + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + try { + output.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +}