From 0601a25e26dc8542bf2ccbf365b41722fdf5153c Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Mon, 23 Dec 2024 17:12:50 +0900 Subject: [PATCH 1/9] =?UTF-8?q?1~8=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/org/example/Main.java | 132 ++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 src/main/java/org/example/Main.java diff --git a/src/main/java/org/example/Main.java b/src/main/java/org/example/Main.java new file mode 100644 index 0000000..dff67d6 --- /dev/null +++ b/src/main/java/org/example/Main.java @@ -0,0 +1,132 @@ +package org.example; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +public class Main { + public static void main(String[] args) throws IOException { + App app = new App(); + app.run(); + } +} + +class App { + private final List quotes = new ArrayList<>(); + + public void run() throws IOException { + System.out.println("== 명언 앱 =="); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int cnt = 0; + + while (true) { + System.out.print("명령) "); + String command = br.readLine(); + + if (command.equals("종료")) { + System.out.println("명언 앱을 종료합니다."); + break; + + } else if (command.equals("등록")) { + System.out.print("명언: "); + String content = br.readLine(); + System.out.print("작가: "); + String author = br.readLine(); + cnt++; + + quotes.add(new Quote(cnt, author, content)); + System.out.println(cnt + "번 명언이 등록되었습니다."); + + } else if (command.equals("목록")) { + printQuotes(); + + } else if (command.startsWith("삭제?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + deleteQuoteById(id); + + } else if (command.startsWith("수정?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + updateQuoteById(id, br); + } + } + } + + public void printQuotes() { + System.out.println("번호 / 작가 / 명언"); + System.out.println("----------------------"); + for (int i = quotes.size() - 1; i >= 0; i--) { // 최신 순으로 출력 + Quote quote = quotes.get(i); + System.out.printf("%d / %s / %s%n", quote.getId(), quote.getAuthor(), quote.getContent()); + } + } + + public void deleteQuoteById(int id) { + if (id == -1) return; + + for (int i = 0; i < quotes.size(); i++) { + if (quotes.get(i).getId() == id) { + quotes.remove(i); + System.out.println(id + "번 명언이 삭제되었습니다."); + return; + } + } + System.out.println(id + "번 명언은 존재하지 않습니다."); + } + + public void updateQuoteById(int id, BufferedReader br) throws IOException { + if (id == -1) return; + + for (Quote quote : quotes) { + if (quote.getId() == id) { + + System.out.println("명언(기존): " + quote.getContent()); + System.out.print("명언: "); + String newContent = br.readLine(); + + System.out.println("작가(기존): " + quote.getAuthor()); + System.out.print("작가: "); + String newAuthor = br.readLine(); + + quote.setContent(newContent); + quote.setAuthor(newAuthor); + + return; + } + } + System.out.println(id + "번 명언은 존재하지 않습니다."); + } +} + +class Quote { + private final int id; + private String author; + private String content; + + public Quote(int id, String author, String content) { + this.id = id; + this.author = author; + this.content = content; + } + + public int getId() { + return id; + } + + public String getAuthor() { + return author; + } + + public String getContent() { + return content; + } + + public void setAuthor(String author) { + this.author = author; + } + + public void setContent(String content) { + this.content = content; + } +} \ No newline at end of file From 591e26370f42ca72affa25e83bdf3076bb9e2970 Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Tue, 24 Dec 2024 09:46:28 +0900 Subject: [PATCH 2/9] =?UTF-8?q?9=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 3 + .idea/code-review.iml | 9 ++ .idea/misc.xml | 6 + .idea/modules.xml | 8 ++ .idea/vcs.xml | 6 + db/wiseSaying/1.json | 5 + db/wiseSaying/3.json | 5 + db/wiseSaying/lastId.txt | 1 + src/main/java/org/example/App.java | 162 +++++++++++++++++++++++++++ src/main/java/org/example/Main.java | 160 +++++++++++++++----------- src/main/java/org/example/Quote.java | 33 ++++++ 11 files changed, 333 insertions(+), 65 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/code-review.iml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 db/wiseSaying/1.json create mode 100644 db/wiseSaying/3.json create mode 100644 db/wiseSaying/lastId.txt create mode 100644 src/main/java/org/example/App.java create mode 100644 src/main/java/org/example/Quote.java diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/code-review.iml b/.idea/code-review.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/code-review.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b66d342 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..07225ff --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json new file mode 100644 index 0000000..cd057bf --- /dev/null +++ b/db/wiseSaying/1.json @@ -0,0 +1,5 @@ +{ +"id": 1, +"author": "작자미상", +"content": "현재와 자신을 사랑하라." +} \ No newline at end of file diff --git a/db/wiseSaying/3.json b/db/wiseSaying/3.json new file mode 100644 index 0000000..fc422b4 --- /dev/null +++ b/db/wiseSaying/3.json @@ -0,0 +1,5 @@ +{ +"id": 3, +"author": "작자미상", +"content": "현재를 사랑하라." +} \ No newline at end of file diff --git a/db/wiseSaying/lastId.txt b/db/wiseSaying/lastId.txt new file mode 100644 index 0000000..e440e5c --- /dev/null +++ b/db/wiseSaying/lastId.txt @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/src/main/java/org/example/App.java b/src/main/java/org/example/App.java new file mode 100644 index 0000000..3ebf648 --- /dev/null +++ b/src/main/java/org/example/App.java @@ -0,0 +1,162 @@ +package org.example; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class App { + private final List quotes = new ArrayList<>(); + private final String dbPath = "db/wiseSaying"; + private int lastId = 0; + + public void run() throws IOException { + System.out.println("== 명언 앱 =="); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + initDatabase(); + + while (true) { + System.out.print("명령) "); + String command = br.readLine(); + + if (command.equals("종료")) { + System.out.println("명언 앱을 종료합니다."); + break; + } else if (command.equals("등록")) { + createQuote(br); + } else if (command.equals("목록")) { + printQuotes(); + } else if (command.startsWith("삭제?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + deleteQuoteById(id); + } else if (command.startsWith("수정?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + updateQuoteById(id, br); + } + } + } + + /// 파일 영속성 + public void initDatabase() throws IOException { + Files.createDirectories(Paths.get(dbPath)); + + File lastIdFile = new File(dbPath, "lastId.txt"); + if (lastIdFile.exists()) { + lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); + } + + File[] files = new File(dbPath).listFiles(((dir, name) -> name.endsWith(".json"))); + if (files != null) { + for (File file : files) { + String q = Files.readString(file.toPath()); + Quote quote = parseQuote(q); + if (quote != null) { + quotes.add(quote); + } + } + } + } + + /// JSON -> Quote + public Quote parseQuote(String q) { + q = q.trim(); + String[] lines = q.split("\n"); + + int id = Integer.parseInt(lines[1].split(":")[1].trim().replace(",", "")); + String author = lines[2].split(":")[1].trim().replace("\"", "").replace(",", ""); + String content = lines[3].split(":")[1].trim().replace("\"", "").replace("}", ""); + + return new Quote(id, author, content); + } + + /// 명언 등록 + public void createQuote(BufferedReader br) throws IOException { + System.out.print("명언: "); + String content = br.readLine(); + System.out.print("작가: "); + String author = br.readLine(); + lastId++; + Quote quote = new Quote(lastId, author, content); + quotes.add(quote); + saveQuoteToFile(quote); + saveLastId(); + + System.out.println(lastId + "번 명언이 등록되었습니다."); + } + + /// Quote -> File + public void saveQuoteToFile(Quote quote) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append("\"id\": ").append(quote.getId()).append(",\n"); + sb.append("\"author\": \"").append(quote.getAuthor()).append("\",\n"); + sb.append("\"content\": \"").append(quote.getContent()).append("\"\n"); + sb.append("}"); + + File file = new File(dbPath, quote.getId() + ".json"); + Files.writeString(file.toPath(), sb.toString()); + } + + /// LastId -> File + public void saveLastId() throws IOException { + File lastIdFile = new File(dbPath, "lastId.txt"); + Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); + } + + /// 명언 조회 + public void printQuotes() { + System.out.println("번호 / 작가 / 명언"); + System.out.println("----------------------"); + for (int i = quotes.size() - 1; i >= 0; i--) { // 최신 순으로 출력 + Quote quote = quotes.get(i); + System.out.printf("%d / %s / %s%n", quote.getId(), quote.getAuthor(), quote.getContent()); + } + } + + /// 명언 수정 + public void updateQuoteById(int id, BufferedReader br) throws IOException { + if (id == -1) return; + + for (Quote quote : quotes) { + if (quote.getId() == id) { + System.out.println("명언(기존): " + quote.getContent()); + System.out.print("명언: "); + String newContent = br.readLine(); + System.out.println("작가(기존): " + quote.getAuthor()); + System.out.print("작가: "); + String newAuthor = br.readLine(); + + quote.setContent(newContent); + quote.setAuthor(newAuthor); + saveQuoteToFile(quote); + + System.out.println(id + "번 명언이 수정되었습니다."); + return; + } + } + System.out.println(id + "번 명언은 존재하지 않습니다."); + } + + /// 명언 삭제 + public void deleteQuoteById(int id) { + if (id == -1) return; + + for (int i = 0; i < quotes.size(); i++) { + if (quotes.get(i).getId() == id) { + quotes.remove(i); + File file = new File(dbPath, id + ".json"); + if (file.exists()) { + file.delete(); + } + + System.out.println(id + "번 명언이 삭제되었습니다."); + return; + } + } + System.out.println(id + "번 명언은 존재하지 않습니다."); + } +} diff --git a/src/main/java/org/example/Main.java b/src/main/java/org/example/Main.java index dff67d6..3ebf648 100644 --- a/src/main/java/org/example/Main.java +++ b/src/main/java/org/example/Main.java @@ -1,25 +1,23 @@ package org.example; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -public class Main { - public static void main(String[] args) throws IOException { - App app = new App(); - app.run(); - } -} - -class App { +public class App { private final List quotes = new ArrayList<>(); + private final String dbPath = "db/wiseSaying"; + private int lastId = 0; public void run() throws IOException { System.out.println("== 명언 앱 =="); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int cnt = 0; + initDatabase(); while (true) { System.out.print("명령) "); @@ -28,24 +26,13 @@ public void run() throws IOException { if (command.equals("종료")) { System.out.println("명언 앱을 종료합니다."); break; - } else if (command.equals("등록")) { - System.out.print("명언: "); - String content = br.readLine(); - System.out.print("작가: "); - String author = br.readLine(); - cnt++; - - quotes.add(new Quote(cnt, author, content)); - System.out.println(cnt + "번 명언이 등록되었습니다."); - + createQuote(br); } else if (command.equals("목록")) { printQuotes(); - } else if (command.startsWith("삭제?id=")) { int id = Integer.parseInt(command.split("=")[1]); deleteQuoteById(id); - } else if (command.startsWith("수정?id=")) { int id = Integer.parseInt(command.split("=")[1]); updateQuoteById(id, br); @@ -53,6 +40,74 @@ public void run() throws IOException { } } + /// 파일 영속성 + public void initDatabase() throws IOException { + Files.createDirectories(Paths.get(dbPath)); + + File lastIdFile = new File(dbPath, "lastId.txt"); + if (lastIdFile.exists()) { + lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); + } + + File[] files = new File(dbPath).listFiles(((dir, name) -> name.endsWith(".json"))); + if (files != null) { + for (File file : files) { + String q = Files.readString(file.toPath()); + Quote quote = parseQuote(q); + if (quote != null) { + quotes.add(quote); + } + } + } + } + + /// JSON -> Quote + public Quote parseQuote(String q) { + q = q.trim(); + String[] lines = q.split("\n"); + + int id = Integer.parseInt(lines[1].split(":")[1].trim().replace(",", "")); + String author = lines[2].split(":")[1].trim().replace("\"", "").replace(",", ""); + String content = lines[3].split(":")[1].trim().replace("\"", "").replace("}", ""); + + return new Quote(id, author, content); + } + + /// 명언 등록 + public void createQuote(BufferedReader br) throws IOException { + System.out.print("명언: "); + String content = br.readLine(); + System.out.print("작가: "); + String author = br.readLine(); + lastId++; + Quote quote = new Quote(lastId, author, content); + quotes.add(quote); + saveQuoteToFile(quote); + saveLastId(); + + System.out.println(lastId + "번 명언이 등록되었습니다."); + } + + /// Quote -> File + public void saveQuoteToFile(Quote quote) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append("\"id\": ").append(quote.getId()).append(",\n"); + sb.append("\"author\": \"").append(quote.getAuthor()).append("\",\n"); + sb.append("\"content\": \"").append(quote.getContent()).append("\"\n"); + sb.append("}"); + + File file = new File(dbPath, quote.getId() + ".json"); + Files.writeString(file.toPath(), sb.toString()); + } + + /// LastId -> File + public void saveLastId() throws IOException { + File lastIdFile = new File(dbPath, "lastId.txt"); + Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); + } + + /// 명언 조회 public void printQuotes() { System.out.println("번호 / 작가 / 명언"); System.out.println("----------------------"); @@ -62,71 +117,46 @@ public void printQuotes() { } } - public void deleteQuoteById(int id) { - if (id == -1) return; - - for (int i = 0; i < quotes.size(); i++) { - if (quotes.get(i).getId() == id) { - quotes.remove(i); - System.out.println(id + "번 명언이 삭제되었습니다."); - return; - } - } - System.out.println(id + "번 명언은 존재하지 않습니다."); - } - + /// 명언 수정 public void updateQuoteById(int id, BufferedReader br) throws IOException { if (id == -1) return; for (Quote quote : quotes) { if (quote.getId() == id) { - System.out.println("명언(기존): " + quote.getContent()); System.out.print("명언: "); String newContent = br.readLine(); - System.out.println("작가(기존): " + quote.getAuthor()); System.out.print("작가: "); String newAuthor = br.readLine(); quote.setContent(newContent); quote.setAuthor(newAuthor); + saveQuoteToFile(quote); + System.out.println(id + "번 명언이 수정되었습니다."); return; } } System.out.println(id + "번 명언은 존재하지 않습니다."); } -} - -class Quote { - private final int id; - private String author; - private String content; - - public Quote(int id, String author, String content) { - this.id = id; - this.author = author; - this.content = content; - } - - public int getId() { - return id; - } - public String getAuthor() { - return author; - } - - public String getContent() { - return content; - } + /// 명언 삭제 + public void deleteQuoteById(int id) { + if (id == -1) return; - public void setAuthor(String author) { - this.author = author; - } + for (int i = 0; i < quotes.size(); i++) { + if (quotes.get(i).getId() == id) { + quotes.remove(i); + File file = new File(dbPath, id + ".json"); + if (file.exists()) { + file.delete(); + } - public void setContent(String content) { - this.content = content; + System.out.println(id + "번 명언이 삭제되었습니다."); + return; + } + } + System.out.println(id + "번 명언은 존재하지 않습니다."); } -} \ No newline at end of file +} diff --git a/src/main/java/org/example/Quote.java b/src/main/java/org/example/Quote.java new file mode 100644 index 0000000..71ba68e --- /dev/null +++ b/src/main/java/org/example/Quote.java @@ -0,0 +1,33 @@ +package org.example; + +public class Quote { + private final int id; + private String author; + private String content; + + public Quote(int id, String author, String content) { + this.id = id; + this.author = author; + this.content = content; + } + + public int getId() { + return id; + } + + public String getAuthor() { + return author; + } + + public String getContent() { + return content; + } + + public void setAuthor(String author) { + this.author = author; + } + + public void setContent(String content) { + this.content = content; + } +} From f2b768c5f6d8d387f545f93b6fc9eb76bcbabf3b Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Tue, 24 Dec 2024 11:20:36 +0900 Subject: [PATCH 3/9] =?UTF-8?q?10=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/wiseSaying/1.json | 5 - db/wiseSaying/12.json | 1 + db/wiseSaying/13.json | 1 + db/wiseSaying/14.json | 1 + db/wiseSaying/3.json | 6 +- db/wiseSaying/4.json | 1 + db/wiseSaying/6.json | 1 + db/wiseSaying/8.json | 1 + db/wiseSaying/9.json | 1 + db/wiseSaying/data.json | 1 + db/wiseSaying/lastId.txt | 2 +- src/main/java/org/example/App.java | 114 ++++++++++++------- src/main/java/org/example/Main.java | 164 ++-------------------------- 13 files changed, 92 insertions(+), 207 deletions(-) delete mode 100644 db/wiseSaying/1.json create mode 100644 db/wiseSaying/12.json create mode 100644 db/wiseSaying/13.json create mode 100644 db/wiseSaying/14.json create mode 100644 db/wiseSaying/4.json create mode 100644 db/wiseSaying/6.json create mode 100644 db/wiseSaying/8.json create mode 100644 db/wiseSaying/9.json create mode 100644 db/wiseSaying/data.json diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json deleted file mode 100644 index cd057bf..0000000 --- a/db/wiseSaying/1.json +++ /dev/null @@ -1,5 +0,0 @@ -{ -"id": 1, -"author": "작자미상", -"content": "현재와 자신을 사랑하라." -} \ No newline at end of file diff --git a/db/wiseSaying/12.json b/db/wiseSaying/12.json new file mode 100644 index 0000000..2820049 --- /dev/null +++ b/db/wiseSaying/12.json @@ -0,0 +1 @@ +{"author":"홍길동","id":12,"content":"야야야"} \ No newline at end of file diff --git a/db/wiseSaying/13.json b/db/wiseSaying/13.json new file mode 100644 index 0000000..5da6d39 --- /dev/null +++ b/db/wiseSaying/13.json @@ -0,0 +1 @@ +{"author":"작가","id":13,"content":"명언"} \ No newline at end of file diff --git a/db/wiseSaying/14.json b/db/wiseSaying/14.json new file mode 100644 index 0000000..ab0a4d5 --- /dev/null +++ b/db/wiseSaying/14.json @@ -0,0 +1 @@ +{"author":"작가","id":14,"content":"명언"} \ No newline at end of file diff --git a/db/wiseSaying/3.json b/db/wiseSaying/3.json index fc422b4..02ed032 100644 --- a/db/wiseSaying/3.json +++ b/db/wiseSaying/3.json @@ -1,5 +1 @@ -{ -"id": 3, -"author": "작자미상", -"content": "현재를 사랑하라." -} \ No newline at end of file +{"author":"작자미상","id":3,"content":"현재를 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/4.json b/db/wiseSaying/4.json new file mode 100644 index 0000000..4938732 --- /dev/null +++ b/db/wiseSaying/4.json @@ -0,0 +1 @@ +{"author":"작자미상","id":4,"content":"과거에 집착하지 마라."} \ No newline at end of file diff --git a/db/wiseSaying/6.json b/db/wiseSaying/6.json new file mode 100644 index 0000000..03dd79b --- /dev/null +++ b/db/wiseSaying/6.json @@ -0,0 +1 @@ +{"author":"작자미상","id":6,"content":"현재와 자신을 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/8.json b/db/wiseSaying/8.json new file mode 100644 index 0000000..b580a5a --- /dev/null +++ b/db/wiseSaying/8.json @@ -0,0 +1 @@ +{"author":"홍길동","id":8,"content":"자신을 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/9.json b/db/wiseSaying/9.json new file mode 100644 index 0000000..44dd98c --- /dev/null +++ b/db/wiseSaying/9.json @@ -0,0 +1 @@ +{"author":"홍길동","id":9,"content":"아아아"} \ No newline at end of file diff --git a/db/wiseSaying/data.json b/db/wiseSaying/data.json new file mode 100644 index 0000000..bb83300 --- /dev/null +++ b/db/wiseSaying/data.json @@ -0,0 +1 @@ +[{"author":"작자미상","id":3,"content":"현재를 사랑하라."},{"author":"작자미상","id":4,"content":"과거에 집착하지 마라."},{"author":"작자미상","id":6,"content":"현재와 자신을 사랑하라."},{"author":"홍길동","id":8,"content":"자신을 사랑하라."},{"author":"홍길동","id":9,"content":"아아아"},{"author":"홍길동","id":12,"content":"야야야"},{"author":"작가","id":13,"content":"명언"},{"author":"작가","id":14,"content":"명언"}] \ No newline at end of file diff --git a/db/wiseSaying/lastId.txt b/db/wiseSaying/lastId.txt index e440e5c..da2d398 100644 --- a/db/wiseSaying/lastId.txt +++ b/db/wiseSaying/lastId.txt @@ -1 +1 @@ -3 \ No newline at end of file +14 \ No newline at end of file diff --git a/src/main/java/org/example/App.java b/src/main/java/org/example/App.java index 3ebf648..ecb52e8 100644 --- a/src/main/java/org/example/App.java +++ b/src/main/java/org/example/App.java @@ -1,5 +1,10 @@ package org.example; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -11,10 +16,11 @@ public class App { private final List quotes = new ArrayList<>(); - private final String dbPath = "db/wiseSaying"; + private final String DB_PATH = "db/wiseSaying"; + private final String LAST_ID_FILE = DB_PATH + "/lastId.txt"; private int lastId = 0; - public void run() throws IOException { + public void run() throws IOException, ParseException { System.out.println("== 명언 앱 =="); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); initDatabase(); @@ -26,34 +32,68 @@ public void run() throws IOException { if (command.equals("종료")) { System.out.println("명언 앱을 종료합니다."); break; - } else if (command.equals("등록")) { - createQuote(br); - } else if (command.equals("목록")) { - printQuotes(); - } else if (command.startsWith("삭제?id=")) { - int id = Integer.parseInt(command.split("=")[1]); - deleteQuoteById(id); - } else if (command.startsWith("수정?id=")) { - int id = Integer.parseInt(command.split("=")[1]); - updateQuoteById(id, br); } + + handleCommand(command, br); + } + } + + /// 명령어 핸들러 + public void handleCommand(String command, BufferedReader br) throws IOException { + if (command.equals("등록")) { + createQuote(br); + } else if (command.equals("목록")) { + printQuotes(); + } else if (command.startsWith("삭제?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + deleteQuoteById(id); + } else if (command.startsWith("수정?id=")) { + int id = Integer.parseInt(command.split("=")[1]); + updateQuoteById(id, br); + } else if (command.equals("빌드")) { + buildDataJson(); + } else { + System.out.println("알 수 없는 명령입니다."); + } + } + + /// 빌드 명령어 + public void buildDataJson() throws IOException { + System.out.println("빌드 전 " + quotes.size()); + JSONArray jsonArray = new JSONArray(); + + for (Quote quote : quotes) { + JSONObject json = new JSONObject(); + json.put("id", quote.getId()); + json.put("author", quote.getAuthor()); + json.put("content", quote.getContent()); + jsonArray.add(json); } + + File file = new File(DB_PATH, "data.json"); + Files.writeString(file.toPath(), jsonArray.toJSONString()); + + System.out.println("빌드 후 " + quotes.size()); } - /// 파일 영속성 - public void initDatabase() throws IOException { - Files.createDirectories(Paths.get(dbPath)); + /// 파일 영속성 초기화 + public void initDatabase() throws IOException, ParseException { + Files.createDirectories(Paths.get(DB_PATH)); - File lastIdFile = new File(dbPath, "lastId.txt"); + File lastIdFile = new File(LAST_ID_FILE); if (lastIdFile.exists()) { lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); } - File[] files = new File(dbPath).listFiles(((dir, name) -> name.endsWith(".json"))); - if (files != null) { - for (File file : files) { - String q = Files.readString(file.toPath()); - Quote quote = parseQuote(q); + File jsonFile = new File(DB_PATH, "data.json"); + if (jsonFile.exists()) { + String content = Files.readString(jsonFile.toPath()); + JSONParser jsonParser = new JSONParser(); + JSONArray jsonArray = (JSONArray) jsonParser.parse(content); + + for (Object obj : jsonArray) { + JSONObject json = (JSONObject) obj; + Quote quote = parseQuote(json); if (quote != null) { quotes.add(quote); } @@ -62,13 +102,10 @@ public void initDatabase() throws IOException { } /// JSON -> Quote - public Quote parseQuote(String q) { - q = q.trim(); - String[] lines = q.split("\n"); - - int id = Integer.parseInt(lines[1].split(":")[1].trim().replace(",", "")); - String author = lines[2].split(":")[1].trim().replace("\"", "").replace(",", ""); - String content = lines[3].split(":")[1].trim().replace("\"", "").replace("}", ""); + public Quote parseQuote(JSONObject json) { + int id = Integer.parseInt(json.get("id").toString()); + String author = json.get("author").toString(); + String content = json.get("content").toString(); return new Quote(id, author, content); } @@ -80,6 +117,7 @@ public void createQuote(BufferedReader br) throws IOException { System.out.print("작가: "); String author = br.readLine(); lastId++; + Quote quote = new Quote(lastId, author, content); quotes.add(quote); saveQuoteToFile(quote); @@ -90,20 +128,18 @@ public void createQuote(BufferedReader br) throws IOException { /// Quote -> File public void saveQuoteToFile(Quote quote) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append("{\n"); - sb.append("\"id\": ").append(quote.getId()).append(",\n"); - sb.append("\"author\": \"").append(quote.getAuthor()).append("\",\n"); - sb.append("\"content\": \"").append(quote.getContent()).append("\"\n"); - sb.append("}"); - - File file = new File(dbPath, quote.getId() + ".json"); - Files.writeString(file.toPath(), sb.toString()); + JSONObject json = new JSONObject(); + json.put("id", quote.getId()); + json.put("author", quote.getAuthor()); + json.put("content", quote.getContent()); + + File file = new File(DB_PATH, quote.getId() + ".json"); + Files.writeString(file.toPath(), json.toString()); } /// LastId -> File public void saveLastId() throws IOException { - File lastIdFile = new File(dbPath, "lastId.txt"); + File lastIdFile = new File(LAST_ID_FILE); Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); } @@ -148,7 +184,7 @@ public void deleteQuoteById(int id) { for (int i = 0; i < quotes.size(); i++) { if (quotes.get(i).getId() == id) { quotes.remove(i); - File file = new File(dbPath, id + ".json"); + File file = new File(DB_PATH, id + ".json"); if (file.exists()) { file.delete(); } diff --git a/src/main/java/org/example/Main.java b/src/main/java/org/example/Main.java index 3ebf648..da1b3ce 100644 --- a/src/main/java/org/example/Main.java +++ b/src/main/java/org/example/Main.java @@ -1,162 +1,12 @@ package org.example; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; - -public class App { - private final List quotes = new ArrayList<>(); - private final String dbPath = "db/wiseSaying"; - private int lastId = 0; - - public void run() throws IOException { - System.out.println("== 명언 앱 =="); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - initDatabase(); - - while (true) { - System.out.print("명령) "); - String command = br.readLine(); - - if (command.equals("종료")) { - System.out.println("명언 앱을 종료합니다."); - break; - } else if (command.equals("등록")) { - createQuote(br); - } else if (command.equals("목록")) { - printQuotes(); - } else if (command.startsWith("삭제?id=")) { - int id = Integer.parseInt(command.split("=")[1]); - deleteQuoteById(id); - } else if (command.startsWith("수정?id=")) { - int id = Integer.parseInt(command.split("=")[1]); - updateQuoteById(id, br); - } - } - } - - /// 파일 영속성 - public void initDatabase() throws IOException { - Files.createDirectories(Paths.get(dbPath)); - - File lastIdFile = new File(dbPath, "lastId.txt"); - if (lastIdFile.exists()) { - lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); - } +import org.json.simple.parser.ParseException; - File[] files = new File(dbPath).listFiles(((dir, name) -> name.endsWith(".json"))); - if (files != null) { - for (File file : files) { - String q = Files.readString(file.toPath()); - Quote quote = parseQuote(q); - if (quote != null) { - quotes.add(quote); - } - } - } - } - - /// JSON -> Quote - public Quote parseQuote(String q) { - q = q.trim(); - String[] lines = q.split("\n"); - - int id = Integer.parseInt(lines[1].split(":")[1].trim().replace(",", "")); - String author = lines[2].split(":")[1].trim().replace("\"", "").replace(",", ""); - String content = lines[3].split(":")[1].trim().replace("\"", "").replace("}", ""); - - return new Quote(id, author, content); - } - - /// 명언 등록 - public void createQuote(BufferedReader br) throws IOException { - System.out.print("명언: "); - String content = br.readLine(); - System.out.print("작가: "); - String author = br.readLine(); - lastId++; - Quote quote = new Quote(lastId, author, content); - quotes.add(quote); - saveQuoteToFile(quote); - saveLastId(); - - System.out.println(lastId + "번 명언이 등록되었습니다."); - } - - /// Quote -> File - public void saveQuoteToFile(Quote quote) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append("{\n"); - sb.append("\"id\": ").append(quote.getId()).append(",\n"); - sb.append("\"author\": \"").append(quote.getAuthor()).append("\",\n"); - sb.append("\"content\": \"").append(quote.getContent()).append("\"\n"); - sb.append("}"); - - File file = new File(dbPath, quote.getId() + ".json"); - Files.writeString(file.toPath(), sb.toString()); - } - - /// LastId -> File - public void saveLastId() throws IOException { - File lastIdFile = new File(dbPath, "lastId.txt"); - Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); - } - - /// 명언 조회 - public void printQuotes() { - System.out.println("번호 / 작가 / 명언"); - System.out.println("----------------------"); - for (int i = quotes.size() - 1; i >= 0; i--) { // 최신 순으로 출력 - Quote quote = quotes.get(i); - System.out.printf("%d / %s / %s%n", quote.getId(), quote.getAuthor(), quote.getContent()); - } - } - - /// 명언 수정 - public void updateQuoteById(int id, BufferedReader br) throws IOException { - if (id == -1) return; - - for (Quote quote : quotes) { - if (quote.getId() == id) { - System.out.println("명언(기존): " + quote.getContent()); - System.out.print("명언: "); - String newContent = br.readLine(); - System.out.println("작가(기존): " + quote.getAuthor()); - System.out.print("작가: "); - String newAuthor = br.readLine(); - - quote.setContent(newContent); - quote.setAuthor(newAuthor); - saveQuoteToFile(quote); - - System.out.println(id + "번 명언이 수정되었습니다."); - return; - } - } - System.out.println(id + "번 명언은 존재하지 않습니다."); - } - - /// 명언 삭제 - public void deleteQuoteById(int id) { - if (id == -1) return; - - for (int i = 0; i < quotes.size(); i++) { - if (quotes.get(i).getId() == id) { - quotes.remove(i); - File file = new File(dbPath, id + ".json"); - if (file.exists()) { - file.delete(); - } +import java.io.IOException; - System.out.println(id + "번 명언이 삭제되었습니다."); - return; - } - } - System.out.println(id + "번 명언은 존재하지 않습니다."); +public class Main { + public static void main(String[] args) throws IOException, ParseException { + App app = new App(); + app.run(); } -} +} \ No newline at end of file From 9e9b65a337121095050406e9e2e80d7fca102627 Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Thu, 2 Jan 2025 14:07:06 +0900 Subject: [PATCH 4/9] =?UTF-8?q?11=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/{Quote.java => WiseSaying.java} | 10 +- .../org/example/WiseSayingController.java | 97 +++++++++++++ .../org/example/WiseSayingRepository.java | 131 ++++++++++++++++++ .../java/org/example/WiseSayingService.java | 50 +++++++ 4 files changed, 285 insertions(+), 3 deletions(-) rename src/main/java/org/example/{Quote.java => WiseSaying.java} (77%) create mode 100644 src/main/java/org/example/WiseSayingController.java create mode 100644 src/main/java/org/example/WiseSayingRepository.java create mode 100644 src/main/java/org/example/WiseSayingService.java diff --git a/src/main/java/org/example/Quote.java b/src/main/java/org/example/WiseSaying.java similarity index 77% rename from src/main/java/org/example/Quote.java rename to src/main/java/org/example/WiseSaying.java index 71ba68e..cc66746 100644 --- a/src/main/java/org/example/Quote.java +++ b/src/main/java/org/example/WiseSaying.java @@ -1,11 +1,15 @@ -package org.example; +package org.example.wiseSaying; -public class Quote { +/** + * 명언 객체 + */ + +public class WiseSaying { private final int id; private String author; private String content; - public Quote(int id, String author, String content) { + public WiseSaying(int id, String author, String content) { this.id = id; this.author = author; this.content = content; diff --git a/src/main/java/org/example/WiseSayingController.java b/src/main/java/org/example/WiseSayingController.java new file mode 100644 index 0000000..45b3e36 --- /dev/null +++ b/src/main/java/org/example/WiseSayingController.java @@ -0,0 +1,97 @@ +package org.example.wiseSaying; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; + +/** + * 컨트롤러 + */ + +public class WiseSayingController { + private final WiseSayingService wiseSayingService; + private final String DB_PATH = "db/wiseSaying"; + private int lastId = 0; + + public WiseSayingController(WiseSayingService wiseSayingService) { + this.wiseSayingService = wiseSayingService; + } + + /// 빌드 명령어 + public void buildDataJson() throws IOException { + List wiseSayings = wiseSayingService.findAllWiseSayings(); + + JSONArray jsonArray = new JSONArray(); + + for (WiseSaying wiseSaying : wiseSayings) { + JSONObject json = new JSONObject(); + json.put("id", wiseSaying.getId()); + json.put("author", wiseSaying.getAuthor()); + json.put("content", wiseSaying.getContent()); + jsonArray.add(json); + } + + File file = new File(DB_PATH, "data.json"); + Files.writeString(file.toPath(), jsonArray.toJSONString()); + System.out.println("data.json 파일의 내용이 갱신되었습니다."); + } + + /// 명언 등록 + public void createWiseSaying(BufferedReader br) throws IOException { + System.out.print("명언: "); + String content = br.readLine(); + System.out.print("작가: "); + String author = br.readLine(); + lastId++; + + WiseSaying wiseSaying = new WiseSaying(lastId, author, content); + wiseSayingService.addWiseSaying(wiseSaying); + + System.out.println(lastId + "번 명언이 등록되었습니다."); + } + + + /// 명언 조회 + public void printWiseSayings() { + System.out.println("번호 / 작가 / 명언"); + System.out.println("----------------------"); + + wiseSayingService.printWiseSaying(); + } + + /// 명언 수정 + public void updateWiseSayingById(int id, BufferedReader br) throws IOException { + if (id == -1) return; + + WiseSaying wiseSaying = wiseSayingService.findWiseSayingById(id); + + if (wiseSaying == null) { + System.out.println(id + "번 명언은 존재하지 않습니다."); + } + + System.out.println("명언(기존): " + wiseSaying.getContent()); + System.out.print("명언: "); + String newContent = br.readLine(); + System.out.println("작가(기존): " + wiseSaying.getAuthor()); + System.out.print("작가: "); + String newAuthor = br.readLine(); + + wiseSayingService.updateWiseSaying(wiseSaying, newContent, newAuthor); + + System.out.println(id + "번 명언이 수정되었습니다."); + } + + /// 명언 삭제 + public void deleteWiseSayingById(int id) throws IOException { + if (wiseSayingService.deleteWiseSaying(id)) { + System.out.println(id + "번 명언이 삭제되었습니다."); + } else { + System.out.println(id + "번 명언은 존재하지 않습니다."); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/example/WiseSayingRepository.java b/src/main/java/org/example/WiseSayingRepository.java new file mode 100644 index 0000000..3ce04db --- /dev/null +++ b/src/main/java/org/example/WiseSayingRepository.java @@ -0,0 +1,131 @@ +package org.example.wiseSaying; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +/** + * 레포지토리 + */ + +public class WiseSayingRepository { + private final List wiseSayings = new ArrayList<>(); + private final String DB_PATH = "db/wiseSaying"; + private final String DATA_FILE = DB_PATH + "/data.json"; + private final String LAST_ID_FILE = DB_PATH + "/lastId.txt"; + private int lastId = 0; + + /// 파일 영속성 초기화 + public void initDatabase() throws IOException, ParseException { + Files.createDirectories(Paths.get(DB_PATH)); + + File lastIdFile = new File(LAST_ID_FILE); + if (lastIdFile.exists()) { + lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); + } + + File jsonFile = new File(DATA_FILE); + if (jsonFile.exists()) { + String content = Files.readString(jsonFile.toPath()); + JSONParser jsonParser = new JSONParser(); + JSONArray jsonArray = (JSONArray) jsonParser.parse(content); + + for (Object obj : jsonArray) { + JSONObject json = (JSONObject) obj; + WiseSaying wiseSaying = parseWiseSaying(json); + if (wiseSaying != null) { + wiseSayings.add(wiseSaying); + } + } + } + } + + /// JSON -> WiseSaying + public WiseSaying parseWiseSaying(JSONObject json) { + int id = Integer.parseInt(json.get("id").toString()); + String author = json.get("author").toString(); + String content = json.get("content").toString(); + + return new WiseSaying(id, author, content); + } + + /// WiseSaying -> File + public void saveWiseSayingToFile(WiseSaying wiseSaying) throws IOException { + JSONObject json = new JSONObject(); + json.put("id", wiseSaying.getId()); + json.put("author", wiseSaying.getAuthor()); + json.put("content", wiseSaying.getContent()); + + File file = new File(DB_PATH, wiseSaying.getId() + ".json"); + Files.createDirectories(file.getParentFile().toPath()); + Files.writeString(file.toPath(), json.toString()); + } + + /// LastId -> File + public void saveLastId() throws IOException { + File lastIdFile = new File(LAST_ID_FILE); + Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); + } + + /// 명언 저장 + public void saveWiseSaying(WiseSaying wiseSaying) throws IOException { + wiseSayings.add(wiseSaying); + + saveWiseSayingToFile(wiseSaying); + updateDataJsonFile(); + } + + /// 모든 명언 조회 + public List findAllWiseSayings() { + return new ArrayList<>(wiseSayings); + } + + /// id로 명언 조회 + public WiseSaying findWiseSayingById(int id) { + return wiseSayings.stream() + .filter(wiseSaying -> wiseSaying.getId() == id) + .findFirst() + .orElse(null); + } + + /// 명언 삭제 + public boolean deleteWiseSayingById(int id) throws IOException { + WiseSaying wiseSaying = findWiseSayingById(id); + + if (wiseSaying != null) { + wiseSayings.remove(wiseSaying); + + File file = new File(DB_PATH, wiseSaying.getId() + ".json"); + if (file.exists()) { + file.delete(); + } + + updateDataJsonFile(); + return true; + } + + return false; + } + + /// data.json 갱신 + private void updateDataJsonFile() throws IOException { + JSONArray jsonArray = new JSONArray(); + for (WiseSaying ws : wiseSayings) { + JSONObject json = new JSONObject(); + json.put("id", ws.getId()); + json.put("author", ws.getAuthor()); + json.put("content", ws.getContent()); + jsonArray.add(json); + } + + Files.writeString(Paths.get(DATA_FILE), jsonArray.toJSONString()); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/WiseSayingService.java b/src/main/java/org/example/WiseSayingService.java new file mode 100644 index 0000000..c30db30 --- /dev/null +++ b/src/main/java/org/example/WiseSayingService.java @@ -0,0 +1,50 @@ +package org.example.wiseSaying; + +import java.io.IOException; +import java.util.List; + +/** + * 서비스 + */ + +public class WiseSayingService { + private final WiseSayingRepository wiseSayingRepository; + + public WiseSayingService(WiseSayingRepository wiseSayingRepository) { + this.wiseSayingRepository = wiseSayingRepository; + } + + public void addWiseSaying(WiseSaying wiseSaying) throws IOException { + wiseSayingRepository.saveWiseSaying(wiseSaying); + wiseSayingRepository.saveWiseSayingToFile(wiseSaying); + wiseSayingRepository.saveLastId(); + } + + public List findAllWiseSayings() { + return wiseSayingRepository.findAllWiseSayings(); + } + + public WiseSaying findWiseSayingById(int id) { + return wiseSayingRepository.findWiseSayingById(id); + } + + public void printWiseSaying() { + List wiseSayings = findAllWiseSayings(); + + for (int i = wiseSayings.size() - 1; i >= 0; i--) { + WiseSaying wiseSaying = wiseSayings.get(i); + System.out.printf("%d / %s / %s%n", wiseSaying.getId(), wiseSaying.getAuthor(), wiseSaying.getContent()); + } + } + + public void updateWiseSaying(WiseSaying wiseSaying, String newContent, String newAuthor) throws IOException { + wiseSaying.setContent(newContent); + wiseSaying.setAuthor(newAuthor); + wiseSayingRepository.saveWiseSaying(wiseSaying); + wiseSayingRepository.saveWiseSayingToFile(wiseSaying); + } + + public boolean deleteWiseSaying(int id) throws IOException { + return wiseSayingRepository.deleteWiseSayingById(id); + } +} \ No newline at end of file From 83845c60a4932fb810f19ad4c621baf857855efa Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Fri, 3 Jan 2025 09:25:31 +0900 Subject: [PATCH 5/9] =?UTF-8?q?12=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/wiseSaying/1.json | 1 + db/wiseSaying/12.json | 1 - db/wiseSaying/13.json | 1 - db/wiseSaying/14.json | 1 - db/wiseSaying/3.json | 1 - db/wiseSaying/4.json | 1 - db/wiseSaying/6.json | 1 - db/wiseSaying/8.json | 1 - db/wiseSaying/9.json | 1 - db/wiseSaying/data.json | 2 +- db/wiseSaying/lastId.txt | 2 +- src/test/java/TestUtil.java | 24 +++ src/test/java/WiseSayingControllerTest.java | 173 ++++++++++++++++++++ 13 files changed, 200 insertions(+), 10 deletions(-) create mode 100644 db/wiseSaying/1.json delete mode 100644 db/wiseSaying/12.json delete mode 100644 db/wiseSaying/13.json delete mode 100644 db/wiseSaying/14.json delete mode 100644 db/wiseSaying/3.json delete mode 100644 db/wiseSaying/4.json delete mode 100644 db/wiseSaying/6.json delete mode 100644 db/wiseSaying/8.json delete mode 100644 db/wiseSaying/9.json create mode 100644 src/test/java/TestUtil.java create mode 100644 src/test/java/WiseSayingControllerTest.java diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json new file mode 100644 index 0000000..a23802f --- /dev/null +++ b/db/wiseSaying/1.json @@ -0,0 +1 @@ +{"author":"작자미상","id":1,"content":"현재를 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/12.json b/db/wiseSaying/12.json deleted file mode 100644 index 2820049..0000000 --- a/db/wiseSaying/12.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"홍길동","id":12,"content":"야야야"} \ No newline at end of file diff --git a/db/wiseSaying/13.json b/db/wiseSaying/13.json deleted file mode 100644 index 5da6d39..0000000 --- a/db/wiseSaying/13.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"작가","id":13,"content":"명언"} \ No newline at end of file diff --git a/db/wiseSaying/14.json b/db/wiseSaying/14.json deleted file mode 100644 index ab0a4d5..0000000 --- a/db/wiseSaying/14.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"작가","id":14,"content":"명언"} \ No newline at end of file diff --git a/db/wiseSaying/3.json b/db/wiseSaying/3.json deleted file mode 100644 index 02ed032..0000000 --- a/db/wiseSaying/3.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"작자미상","id":3,"content":"현재를 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/4.json b/db/wiseSaying/4.json deleted file mode 100644 index 4938732..0000000 --- a/db/wiseSaying/4.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"작자미상","id":4,"content":"과거에 집착하지 마라."} \ No newline at end of file diff --git a/db/wiseSaying/6.json b/db/wiseSaying/6.json deleted file mode 100644 index 03dd79b..0000000 --- a/db/wiseSaying/6.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"작자미상","id":6,"content":"현재와 자신을 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/8.json b/db/wiseSaying/8.json deleted file mode 100644 index b580a5a..0000000 --- a/db/wiseSaying/8.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"홍길동","id":8,"content":"자신을 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/9.json b/db/wiseSaying/9.json deleted file mode 100644 index 44dd98c..0000000 --- a/db/wiseSaying/9.json +++ /dev/null @@ -1 +0,0 @@ -{"author":"홍길동","id":9,"content":"아아아"} \ No newline at end of file diff --git a/db/wiseSaying/data.json b/db/wiseSaying/data.json index bb83300..d39f903 100644 --- a/db/wiseSaying/data.json +++ b/db/wiseSaying/data.json @@ -1 +1 @@ -[{"author":"작자미상","id":3,"content":"현재를 사랑하라."},{"author":"작자미상","id":4,"content":"과거에 집착하지 마라."},{"author":"작자미상","id":6,"content":"현재와 자신을 사랑하라."},{"author":"홍길동","id":8,"content":"자신을 사랑하라."},{"author":"홍길동","id":9,"content":"아아아"},{"author":"홍길동","id":12,"content":"야야야"},{"author":"작가","id":13,"content":"명언"},{"author":"작가","id":14,"content":"명언"}] \ No newline at end of file +[{"author":"작자미상","id":1,"content":"현재를 사랑하라."}] \ No newline at end of file diff --git a/db/wiseSaying/lastId.txt b/db/wiseSaying/lastId.txt index da2d398..c227083 100644 --- a/db/wiseSaying/lastId.txt +++ b/db/wiseSaying/lastId.txt @@ -1 +1 @@ -14 \ No newline at end of file +0 \ No newline at end of file diff --git a/src/test/java/TestUtil.java b/src/test/java/TestUtil.java new file mode 100644 index 0000000..c0a8c62 --- /dev/null +++ b/src/test/java/TestUtil.java @@ -0,0 +1,24 @@ +import java.io.*; + +public class TestUtil { + + public static ByteArrayInputStream getInputStream(String input) { + return new ByteArrayInputStream(input.getBytes()); + } + + public static ByteArrayOutputStream setOutToByteArray() { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + System.setOut(new PrintStream(output)); + + return output; + } + + public static void clearSetOutToByteArray(final ByteArrayOutputStream output) { + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + try { + output.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/src/test/java/WiseSayingControllerTest.java b/src/test/java/WiseSayingControllerTest.java new file mode 100644 index 0000000..3ab66d7 --- /dev/null +++ b/src/test/java/WiseSayingControllerTest.java @@ -0,0 +1,173 @@ +import org.example.wiseSaying.WiseSayingController; +import org.example.wiseSaying.WiseSayingRepository; +import org.example.wiseSaying.WiseSayingService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; + +public class WiseSayingControllerTest { + private WiseSayingRepository wiseSayingRepository; + private WiseSayingService wiseSayingService; + private WiseSayingController wiseSayingController; + + @BeforeEach + void beforeEach() { + wiseSayingRepository = new WiseSayingRepository(); + wiseSayingService = new WiseSayingService(wiseSayingRepository); + wiseSayingController = new WiseSayingController(wiseSayingService); + } + + @Test + @DisplayName("명언 등록") + void createWiseSaying() throws IOException { + final String input = (""" + 현재를 사랑하라. + 작자미상 + """); + ByteArrayInputStream inputStream = TestUtil.getInputStream(input); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); + ByteArrayOutputStream outputStream = TestUtil.setOutToByteArray(); + + Path dbPath = Path.of("db/wiseSaying"); + if (!Files.exists(dbPath)) { + Files.createDirectories(dbPath); + } + + wiseSayingController.createWiseSaying(br); + TestUtil.clearSetOutToByteArray(outputStream); + + Path filePath = Path.of(dbPath.toString(), "1.json"); + assertThat(Files.exists(filePath)).isTrue(); + + String content = Files.readString(filePath); + + assertThat(content) + .contains("현재를 사랑하라.", "작자미상"); + } + + @Test + @DisplayName("명언 조회") + void printWiseSaying() throws IOException { + String input = """ + 현재를 사랑하라. + 작자미상 + """; + ByteArrayInputStream inputStream = TestUtil.getInputStream(input); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); + ByteArrayOutputStream outputStream = TestUtil.setOutToByteArray(); + + wiseSayingController.createWiseSaying(br); + TestUtil.clearSetOutToByteArray(outputStream); + + outputStream = TestUtil.setOutToByteArray(); + wiseSayingController.printWiseSayings(); + TestUtil.clearSetOutToByteArray(outputStream); + + String output = outputStream.toString().trim(); + + assertThat(output).contains("번호 / 작가 / 명언") + .contains("----------------------") + .contains("1 / 작자미상 / 현재를 사랑하라."); + } + + @Test + @DisplayName("명언 수정") + void updateWiseSaying() throws IOException { + String input = """ + 현재를 사랑하라. + 작자미상 + 미래를 꿈꾸다. + 작자미상 + """; + ByteArrayInputStream inputStream = TestUtil.getInputStream(input); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); + ByteArrayOutputStream outputStream = TestUtil.setOutToByteArray(); + + wiseSayingController.createWiseSaying(br); + TestUtil.clearSetOutToByteArray(outputStream); + + Path dbPath = Path.of("db/wiseSaying"); + if (!Files.exists(dbPath)) { + Files.createDirectories(dbPath); + } + + Path filePath = Path.of(dbPath.toString(), "1.json"); + assertThat(Files.exists(filePath)).isTrue(); + + wiseSayingController.updateWiseSayingById(1, br); + TestUtil.clearSetOutToByteArray(outputStream); + + String fileContent = Files.readString(filePath); + + assertThat(fileContent) + .contains("미래를 꿈꾸다.") + .contains("작자미상"); + } + + @Test + @DisplayName("명언 삭제") + void deleteWiseSaying() throws IOException { + String input = """ + 현재를 사랑하라. + 작자미상 + """; + ByteArrayInputStream inputStream = TestUtil.getInputStream(input); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); + ByteArrayOutputStream outputStream = TestUtil.setOutToByteArray(); + + wiseSayingController.createWiseSaying(br); + TestUtil.clearSetOutToByteArray(outputStream); + + Path dbPath = Path.of("db/wiseSaying"); + if (!Files.exists(dbPath)) { + Files.createDirectories(dbPath); + } + + Path filePath = Path.of(dbPath.toString(), "1.json"); + assertThat(Files.exists(filePath)).isTrue(); + + TestUtil.clearSetOutToByteArray(outputStream); + wiseSayingController.deleteWiseSayingById(1); + + assertThat(filePath).doesNotExist(); + } + + @Test + @DisplayName("명언 빌드") + void buildWiseSaying() throws IOException { + String input = """ + 현재를 사랑하라. + 작자미상 + """; + ByteArrayInputStream inputStream = TestUtil.getInputStream(input); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); + ByteArrayOutputStream outputStream = TestUtil.setOutToByteArray(); + + wiseSayingController.createWiseSaying(br); + TestUtil.clearSetOutToByteArray(outputStream); + + Path dbPath = Path.of("db/wiseSaying"); + if (!Files.exists(dbPath)) { + Files.createDirectories(dbPath); + } + + Path filePath = Path.of(dbPath.toString(), "data.json"); + assertThat(Files.exists(filePath)).isTrue(); + + TestUtil.clearSetOutToByteArray(outputStream); + wiseSayingController.buildWiseSaying(); + + String fileContent = Files.readString(filePath); + + assertThat(filePath).exists(); + + assertThat(fileContent) + .contains("[{\"author\":\"작자미상\",\"id\":1,\"content\":\"현재를 사랑하라.\"}]"); + } +} From a0e6d02335d85bdf6587a23ec460c0d1ee211848 Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Fri, 3 Jan 2025 09:42:33 +0900 Subject: [PATCH 6/9] =?UTF-8?q?fix:=20lastId=20=EC=A0=80=EC=9E=A5=20?= =?UTF-8?q?=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/wiseSaying/1.json | 2 +- db/wiseSaying/2.json | 1 + db/wiseSaying/data.json | 2 +- db/wiseSaying/lastId.txt | 2 +- src/main/java/org/example/WiseSayingRepository.java | 5 +++-- src/main/java/org/example/WiseSayingService.java | 3 ++- 6 files changed, 9 insertions(+), 6 deletions(-) create mode 100644 db/wiseSaying/2.json diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json index a23802f..0c29805 100644 --- a/db/wiseSaying/1.json +++ b/db/wiseSaying/1.json @@ -1 +1 @@ -{"author":"작자미상","id":1,"content":"현재를 사랑하라."} \ No newline at end of file +{"author":"아아","id":1,"content":"음음"} \ No newline at end of file diff --git a/db/wiseSaying/2.json b/db/wiseSaying/2.json new file mode 100644 index 0000000..f6d564c --- /dev/null +++ b/db/wiseSaying/2.json @@ -0,0 +1 @@ +{"author":"작가","id":2,"content":"나는"} \ No newline at end of file diff --git a/db/wiseSaying/data.json b/db/wiseSaying/data.json index d39f903..b230181 100644 --- a/db/wiseSaying/data.json +++ b/db/wiseSaying/data.json @@ -1 +1 @@ -[{"author":"작자미상","id":1,"content":"현재를 사랑하라."}] \ No newline at end of file +[{"author":"아아","id":1,"content":"음음"},{"author":"작가","id":2,"content":"나는"}] \ No newline at end of file diff --git a/db/wiseSaying/lastId.txt b/db/wiseSaying/lastId.txt index c227083..d8263ee 100644 --- a/db/wiseSaying/lastId.txt +++ b/db/wiseSaying/lastId.txt @@ -1 +1 @@ -0 \ No newline at end of file +2 \ No newline at end of file diff --git a/src/main/java/org/example/WiseSayingRepository.java b/src/main/java/org/example/WiseSayingRepository.java index 3ce04db..df45689 100644 --- a/src/main/java/org/example/WiseSayingRepository.java +++ b/src/main/java/org/example/WiseSayingRepository.java @@ -70,9 +70,9 @@ public void saveWiseSayingToFile(WiseSaying wiseSaying) throws IOException { } /// LastId -> File - public void saveLastId() throws IOException { + public void saveLastId(WiseSaying wiseSaying) throws IOException { File lastIdFile = new File(LAST_ID_FILE); - Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); + Files.writeString(lastIdFile.toPath(), String.valueOf(wiseSaying.getId())); } /// 명언 저장 @@ -118,6 +118,7 @@ public boolean deleteWiseSayingById(int id) throws IOException { /// data.json 갱신 private void updateDataJsonFile() throws IOException { JSONArray jsonArray = new JSONArray(); + for (WiseSaying ws : wiseSayings) { JSONObject json = new JSONObject(); json.put("id", ws.getId()); diff --git a/src/main/java/org/example/WiseSayingService.java b/src/main/java/org/example/WiseSayingService.java index c30db30..bf1eb0b 100644 --- a/src/main/java/org/example/WiseSayingService.java +++ b/src/main/java/org/example/WiseSayingService.java @@ -17,7 +17,7 @@ public WiseSayingService(WiseSayingRepository wiseSayingRepository) { public void addWiseSaying(WiseSaying wiseSaying) throws IOException { wiseSayingRepository.saveWiseSaying(wiseSaying); wiseSayingRepository.saveWiseSayingToFile(wiseSaying); - wiseSayingRepository.saveLastId(); + wiseSayingRepository.saveLastId(wiseSaying); } public List findAllWiseSayings() { @@ -42,6 +42,7 @@ public void updateWiseSaying(WiseSaying wiseSaying, String newContent, String ne wiseSaying.setAuthor(newAuthor); wiseSayingRepository.saveWiseSaying(wiseSaying); wiseSayingRepository.saveWiseSayingToFile(wiseSaying); + wiseSayingRepository.saveLastId(wiseSaying); } public boolean deleteWiseSaying(int id) throws IOException { From c4811bf80b81d1e27c749fc8632aaf7e8bb255fd Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Fri, 3 Jan 2025 10:20:43 +0900 Subject: [PATCH 7/9] =?UTF-8?q?13=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/wiseSaying/1.json | 2 +- db/wiseSaying/2.json | 2 +- db/wiseSaying/data.json | 2 +- src/main/java/org/example/App.java | 176 ++---------------- .../org/example/WiseSayingController.java | 14 +- .../java/org/example/WiseSayingService.java | 38 ++++ 6 files changed, 70 insertions(+), 164 deletions(-) diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json index 0c29805..bffe3e3 100644 --- a/db/wiseSaying/1.json +++ b/db/wiseSaying/1.json @@ -1 +1 @@ -{"author":"아아","id":1,"content":"음음"} \ No newline at end of file +{"author":"작가","id":1,"content":"과거에 집착하지마라."} \ No newline at end of file diff --git a/db/wiseSaying/2.json b/db/wiseSaying/2.json index f6d564c..6819342 100644 --- a/db/wiseSaying/2.json +++ b/db/wiseSaying/2.json @@ -1 +1 @@ -{"author":"작가","id":2,"content":"나는"} \ No newline at end of file +{"author":"으믕ㅁ","id":2,"content":"아아"} \ No newline at end of file diff --git a/db/wiseSaying/data.json b/db/wiseSaying/data.json index b230181..d2ebc30 100644 --- a/db/wiseSaying/data.json +++ b/db/wiseSaying/data.json @@ -1 +1 @@ -[{"author":"아아","id":1,"content":"음음"},{"author":"작가","id":2,"content":"나는"}] \ No newline at end of file +[{"author":"작자미상","id":1,"content":"현재를 사랑하라."},{"author":"작가","id":1,"content":"과거에 집착하지마라."},{"author":"으믕ㅁ","id":2,"content":"아아"}] \ No newline at end of file diff --git a/src/main/java/org/example/App.java b/src/main/java/org/example/App.java index ecb52e8..c7ebee9 100644 --- a/src/main/java/org/example/App.java +++ b/src/main/java/org/example/App.java @@ -1,29 +1,20 @@ -package org.example; +package org.example.wiseSaying; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; public class App { - private final List quotes = new ArrayList<>(); - private final String DB_PATH = "db/wiseSaying"; - private final String LAST_ID_FILE = DB_PATH + "/lastId.txt"; - private int lastId = 0; + private final WiseSayingRepository wiseSayingRepository = new WiseSayingRepository(); + private final WiseSayingService wiseSayingService = new WiseSayingService(wiseSayingRepository); + private final WiseSayingController wiseSayingController = new WiseSayingController(wiseSayingService); public void run() throws IOException, ParseException { System.out.println("== 명언 앱 =="); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - initDatabase(); + wiseSayingRepository.initDatabase(); while (true) { System.out.print("명령) "); @@ -41,158 +32,23 @@ public void run() throws IOException, ParseException { /// 명령어 핸들러 public void handleCommand(String command, BufferedReader br) throws IOException { if (command.equals("등록")) { - createQuote(br); + wiseSayingController.createWiseSaying(br); } else if (command.equals("목록")) { - printQuotes(); + wiseSayingController.printWiseSayings(); } else if (command.startsWith("삭제?id=")) { int id = Integer.parseInt(command.split("=")[1]); - deleteQuoteById(id); + wiseSayingController.deleteWiseSayingById(id); } else if (command.startsWith("수정?id=")) { int id = Integer.parseInt(command.split("=")[1]); - updateQuoteById(id, br); + wiseSayingController.updateWiseSayingById(id, br); } else if (command.equals("빌드")) { - buildDataJson(); - } else { + wiseSayingController.buildWiseSaying(); + } else if (command.startsWith("목록?keywordType=")) { + String keywordType = command.split("=")[1].split("&")[0]; + String keyword = command.split("=")[2]; + wiseSayingController.searchWiseSaying(keywordType, keyword); + }else { System.out.println("알 수 없는 명령입니다."); } } - - /// 빌드 명령어 - public void buildDataJson() throws IOException { - System.out.println("빌드 전 " + quotes.size()); - JSONArray jsonArray = new JSONArray(); - - for (Quote quote : quotes) { - JSONObject json = new JSONObject(); - json.put("id", quote.getId()); - json.put("author", quote.getAuthor()); - json.put("content", quote.getContent()); - jsonArray.add(json); - } - - File file = new File(DB_PATH, "data.json"); - Files.writeString(file.toPath(), jsonArray.toJSONString()); - - System.out.println("빌드 후 " + quotes.size()); - } - - /// 파일 영속성 초기화 - public void initDatabase() throws IOException, ParseException { - Files.createDirectories(Paths.get(DB_PATH)); - - File lastIdFile = new File(LAST_ID_FILE); - if (lastIdFile.exists()) { - lastId = Integer.parseInt(Files.readString(lastIdFile.toPath()).trim()); - } - - File jsonFile = new File(DB_PATH, "data.json"); - if (jsonFile.exists()) { - String content = Files.readString(jsonFile.toPath()); - JSONParser jsonParser = new JSONParser(); - JSONArray jsonArray = (JSONArray) jsonParser.parse(content); - - for (Object obj : jsonArray) { - JSONObject json = (JSONObject) obj; - Quote quote = parseQuote(json); - if (quote != null) { - quotes.add(quote); - } - } - } - } - - /// JSON -> Quote - public Quote parseQuote(JSONObject json) { - int id = Integer.parseInt(json.get("id").toString()); - String author = json.get("author").toString(); - String content = json.get("content").toString(); - - return new Quote(id, author, content); - } - - /// 명언 등록 - public void createQuote(BufferedReader br) throws IOException { - System.out.print("명언: "); - String content = br.readLine(); - System.out.print("작가: "); - String author = br.readLine(); - lastId++; - - Quote quote = new Quote(lastId, author, content); - quotes.add(quote); - saveQuoteToFile(quote); - saveLastId(); - - System.out.println(lastId + "번 명언이 등록되었습니다."); - } - - /// Quote -> File - public void saveQuoteToFile(Quote quote) throws IOException { - JSONObject json = new JSONObject(); - json.put("id", quote.getId()); - json.put("author", quote.getAuthor()); - json.put("content", quote.getContent()); - - File file = new File(DB_PATH, quote.getId() + ".json"); - Files.writeString(file.toPath(), json.toString()); - } - - /// LastId -> File - public void saveLastId() throws IOException { - File lastIdFile = new File(LAST_ID_FILE); - Files.writeString(lastIdFile.toPath(), String.valueOf(lastId)); - } - - /// 명언 조회 - public void printQuotes() { - System.out.println("번호 / 작가 / 명언"); - System.out.println("----------------------"); - for (int i = quotes.size() - 1; i >= 0; i--) { // 최신 순으로 출력 - Quote quote = quotes.get(i); - System.out.printf("%d / %s / %s%n", quote.getId(), quote.getAuthor(), quote.getContent()); - } - } - - /// 명언 수정 - public void updateQuoteById(int id, BufferedReader br) throws IOException { - if (id == -1) return; - - for (Quote quote : quotes) { - if (quote.getId() == id) { - System.out.println("명언(기존): " + quote.getContent()); - System.out.print("명언: "); - String newContent = br.readLine(); - System.out.println("작가(기존): " + quote.getAuthor()); - System.out.print("작가: "); - String newAuthor = br.readLine(); - - quote.setContent(newContent); - quote.setAuthor(newAuthor); - saveQuoteToFile(quote); - - System.out.println(id + "번 명언이 수정되었습니다."); - return; - } - } - System.out.println(id + "번 명언은 존재하지 않습니다."); - } - - /// 명언 삭제 - public void deleteQuoteById(int id) { - if (id == -1) return; - - for (int i = 0; i < quotes.size(); i++) { - if (quotes.get(i).getId() == id) { - quotes.remove(i); - File file = new File(DB_PATH, id + ".json"); - if (file.exists()) { - file.delete(); - } - - System.out.println(id + "번 명언이 삭제되었습니다."); - return; - } - } - System.out.println(id + "번 명언은 존재하지 않습니다."); - } -} +} \ No newline at end of file diff --git a/src/main/java/org/example/WiseSayingController.java b/src/main/java/org/example/WiseSayingController.java index 45b3e36..03bb3ee 100644 --- a/src/main/java/org/example/WiseSayingController.java +++ b/src/main/java/org/example/WiseSayingController.java @@ -23,7 +23,7 @@ public WiseSayingController(WiseSayingService wiseSayingService) { } /// 빌드 명령어 - public void buildDataJson() throws IOException { + public void buildWiseSaying() throws IOException { List wiseSayings = wiseSayingService.findAllWiseSayings(); JSONArray jsonArray = new JSONArray(); @@ -94,4 +94,16 @@ public void deleteWiseSayingById(int id) throws IOException { System.out.println(id + "번 명언은 존재하지 않습니다."); } } + + /// 명언 검색 + public void searchWiseSaying(String keywordType, String keyword) throws IOException { + System.out.println("----------------------"); + System.out.println("검색타입 : " + keywordType); + System.out.println("검색어 : " + keyword); + System.out.println("----------------------"); + System.out.println("번호 / 작가 / 명언"); + System.out.println("----------------------"); + + wiseSayingService.printWiseSayingByKeyword(keywordType, keyword); + } } \ No newline at end of file diff --git a/src/main/java/org/example/WiseSayingService.java b/src/main/java/org/example/WiseSayingService.java index bf1eb0b..d221ffa 100644 --- a/src/main/java/org/example/WiseSayingService.java +++ b/src/main/java/org/example/WiseSayingService.java @@ -1,6 +1,7 @@ package org.example.wiseSaying; import java.io.IOException; +import java.util.ArrayList; import java.util.List; /** @@ -37,6 +38,43 @@ public void printWiseSaying() { } } + public void printWiseSayingByKeyword(String keywordType, String keyword) { + List wiseSayings = findAllWiseSayings(); + + List filteredWiseSayings = new ArrayList<>(); + for (WiseSaying wiseSaying: wiseSayings) { + switch (keywordType) { + case "id": + if (String.valueOf(wiseSaying.getId()).equals(keyword)) { + filteredWiseSayings.add(wiseSaying); + } + break; + case "content": + if (wiseSaying.getContent().contains(keyword)) { + filteredWiseSayings.add(wiseSaying); + } + break; + case "author": + if (wiseSaying.getAuthor().contains(keyword)) { + filteredWiseSayings.add(wiseSaying); + } + break; + default: + System.out.println("일치하는 키워드가 없습니다."); + return; + } + } + + if (filteredWiseSayings.isEmpty()) { + System.out.println("해당 명언을 찾을 수 없습니다."); + } else { + for (int i = filteredWiseSayings.size() - 1; i >= 0; i--) { + WiseSaying wiseSaying = filteredWiseSayings.get(i); + System.out.printf("%d / %s / %s%n", wiseSaying.getId(), wiseSaying.getAuthor(), wiseSaying.getContent()); + } + } + } + public void updateWiseSaying(WiseSaying wiseSaying, String newContent, String newAuthor) throws IOException { wiseSaying.setContent(newContent); wiseSaying.setAuthor(newAuthor); From 285f34216d0890621e1cf89eb14e1b7e3d3c605e Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Fri, 3 Jan 2025 11:17:25 +0900 Subject: [PATCH 8/9] =?UTF-8?q?14=EB=8B=A8=EA=B3=84=20=EA=B5=AC=ED=98=84?= =?UTF-8?q?=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/wiseSaying/1.json | 2 +- db/wiseSaying/10.json | 1 + db/wiseSaying/11.json | 1 + db/wiseSaying/2.json | 2 +- db/wiseSaying/3.json | 1 + db/wiseSaying/4.json | 1 + db/wiseSaying/5.json | 1 + db/wiseSaying/6.json | 1 + db/wiseSaying/7.json | 1 + db/wiseSaying/8.json | 1 + db/wiseSaying/9.json | 1 + db/wiseSaying/data.json | 2 +- db/wiseSaying/lastId.txt | 2 +- src/main/java/org/example/App.java | 4 +- .../org/example/WiseSayingController.java | 4 +- .../java/org/example/WiseSayingService.java | 40 ++++++++++++++++++- src/test/java/WiseSayingControllerTest.java | 6 +-- 17 files changed, 58 insertions(+), 13 deletions(-) create mode 100644 db/wiseSaying/10.json create mode 100644 db/wiseSaying/11.json create mode 100644 db/wiseSaying/3.json create mode 100644 db/wiseSaying/4.json create mode 100644 db/wiseSaying/5.json create mode 100644 db/wiseSaying/6.json create mode 100644 db/wiseSaying/7.json create mode 100644 db/wiseSaying/8.json create mode 100644 db/wiseSaying/9.json diff --git a/db/wiseSaying/1.json b/db/wiseSaying/1.json index bffe3e3..a23802f 100644 --- a/db/wiseSaying/1.json +++ b/db/wiseSaying/1.json @@ -1 +1 @@ -{"author":"작가","id":1,"content":"과거에 집착하지마라."} \ No newline at end of file +{"author":"작자미상","id":1,"content":"현재를 사랑하라."} \ No newline at end of file diff --git a/db/wiseSaying/10.json b/db/wiseSaying/10.json new file mode 100644 index 0000000..d48fd4c --- /dev/null +++ b/db/wiseSaying/10.json @@ -0,0 +1 @@ +{"author":"작자미상 10","id":10,"content":"명언 10"} \ No newline at end of file diff --git a/db/wiseSaying/11.json b/db/wiseSaying/11.json new file mode 100644 index 0000000..a5f1a44 --- /dev/null +++ b/db/wiseSaying/11.json @@ -0,0 +1 @@ +{"author":"작자미상 11","id":11,"content":"명언 11"} \ No newline at end of file diff --git a/db/wiseSaying/2.json b/db/wiseSaying/2.json index 6819342..1e1ccbe 100644 --- a/db/wiseSaying/2.json +++ b/db/wiseSaying/2.json @@ -1 +1 @@ -{"author":"으믕ㅁ","id":2,"content":"아아"} \ No newline at end of file +{"author":"작자미상 2","id":2,"content":"명언 2"} \ No newline at end of file diff --git a/db/wiseSaying/3.json b/db/wiseSaying/3.json new file mode 100644 index 0000000..4593a60 --- /dev/null +++ b/db/wiseSaying/3.json @@ -0,0 +1 @@ +{"author":"작자미상 3","id":3,"content":"명언 3"} \ No newline at end of file diff --git a/db/wiseSaying/4.json b/db/wiseSaying/4.json new file mode 100644 index 0000000..75d791c --- /dev/null +++ b/db/wiseSaying/4.json @@ -0,0 +1 @@ +{"author":"작자미상 4","id":4,"content":"명언 4"} \ No newline at end of file diff --git a/db/wiseSaying/5.json b/db/wiseSaying/5.json new file mode 100644 index 0000000..5f7bb0c --- /dev/null +++ b/db/wiseSaying/5.json @@ -0,0 +1 @@ +{"author":"작자미상 5","id":5,"content":"명언 5"} \ No newline at end of file diff --git a/db/wiseSaying/6.json b/db/wiseSaying/6.json new file mode 100644 index 0000000..538798e --- /dev/null +++ b/db/wiseSaying/6.json @@ -0,0 +1 @@ +{"author":"작자미상 6","id":6,"content":"명언 6"} \ No newline at end of file diff --git a/db/wiseSaying/7.json b/db/wiseSaying/7.json new file mode 100644 index 0000000..c629120 --- /dev/null +++ b/db/wiseSaying/7.json @@ -0,0 +1 @@ +{"author":"작자미상 7","id":7,"content":"명언 ㅕ7"} \ No newline at end of file diff --git a/db/wiseSaying/8.json b/db/wiseSaying/8.json new file mode 100644 index 0000000..abe1677 --- /dev/null +++ b/db/wiseSaying/8.json @@ -0,0 +1 @@ +{"author":"작자미상 8","id":8,"content":"명언 8"} \ No newline at end of file diff --git a/db/wiseSaying/9.json b/db/wiseSaying/9.json new file mode 100644 index 0000000..478169f --- /dev/null +++ b/db/wiseSaying/9.json @@ -0,0 +1 @@ +{"author":"작자미상 9","id":9,"content":"명언 9"} \ No newline at end of file diff --git a/db/wiseSaying/data.json b/db/wiseSaying/data.json index d2ebc30..e365e26 100644 --- a/db/wiseSaying/data.json +++ b/db/wiseSaying/data.json @@ -1 +1 @@ -[{"author":"작자미상","id":1,"content":"현재를 사랑하라."},{"author":"작가","id":1,"content":"과거에 집착하지마라."},{"author":"으믕ㅁ","id":2,"content":"아아"}] \ No newline at end of file +[{"author":"작자미상 1","id":1,"content":"명언 1"},{"author":"작자미상 2","id":2,"content":"명언 2"},{"author":"작자미상 3","id":3,"content":"명언 3"},{"author":"작자미상 4","id":4,"content":"명언 4"},{"author":"작자미상 5","id":5,"content":"명언 5"},{"author":"작자미상 6","id":6,"content":"명언 6"},{"author":"작자미상 7","id":7,"content":"명언 ㅕ7"},{"author":"작자미상 8","id":8,"content":"명언 8"},{"author":"작자미상 9","id":9,"content":"명언 9"},{"author":"작자미상 10","id":10,"content":"명언 10"},{"author":"작자미상 11","id":11,"content":"명언 11"}] \ No newline at end of file diff --git a/db/wiseSaying/lastId.txt b/db/wiseSaying/lastId.txt index d8263ee..9d60796 100644 --- a/db/wiseSaying/lastId.txt +++ b/db/wiseSaying/lastId.txt @@ -1 +1 @@ -2 \ No newline at end of file +11 \ No newline at end of file diff --git a/src/main/java/org/example/App.java b/src/main/java/org/example/App.java index c7ebee9..545d867 100644 --- a/src/main/java/org/example/App.java +++ b/src/main/java/org/example/App.java @@ -33,8 +33,8 @@ public void run() throws IOException, ParseException { public void handleCommand(String command, BufferedReader br) throws IOException { if (command.equals("등록")) { wiseSayingController.createWiseSaying(br); - } else if (command.equals("목록")) { - wiseSayingController.printWiseSayings(); + } else if (command.startsWith("목록")) { + wiseSayingController.printWiseSayings(command); } else if (command.startsWith("삭제?id=")) { int id = Integer.parseInt(command.split("=")[1]); wiseSayingController.deleteWiseSayingById(id); diff --git a/src/main/java/org/example/WiseSayingController.java b/src/main/java/org/example/WiseSayingController.java index 03bb3ee..29dc818 100644 --- a/src/main/java/org/example/WiseSayingController.java +++ b/src/main/java/org/example/WiseSayingController.java @@ -57,11 +57,11 @@ public void createWiseSaying(BufferedReader br) throws IOException { /// 명언 조회 - public void printWiseSayings() { + public void printWiseSayings(String command) { System.out.println("번호 / 작가 / 명언"); System.out.println("----------------------"); - wiseSayingService.printWiseSaying(); + wiseSayingService.printWiseSaying(command); } /// 명언 수정 diff --git a/src/main/java/org/example/WiseSayingService.java b/src/main/java/org/example/WiseSayingService.java index d221ffa..5f4a172 100644 --- a/src/main/java/org/example/WiseSayingService.java +++ b/src/main/java/org/example/WiseSayingService.java @@ -29,13 +29,49 @@ public WiseSaying findWiseSayingById(int id) { return wiseSayingRepository.findWiseSayingById(id); } - public void printWiseSaying() { + public void printWiseSaying(String command) { + int page = 1; + int itemsPerPage = 5; + + if (command.contains("?page=")) { + try { + page = Integer.parseInt(command.split("=")[1]); + } catch (NumberFormatException e) { + System.out.println("잘못된 페이지 번호입니다."); + return; + } + } + List wiseSayings = findAllWiseSayings(); - for (int i = wiseSayings.size() - 1; i >= 0; i--) { + wiseSayings.sort((ws1, ws2) -> Integer.compare(ws2.getId(), ws1.getId())); + + int totalItems = wiseSayings.size(); + int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage); + + if (page > totalPages) { + System.out.println("잘못된 페이지 번호입니다."); + return; + } + + int startIndex = (page - 1) * itemsPerPage; + int endIndex = Math.min(startIndex + itemsPerPage, totalItems); + + for (int i = startIndex; i < endIndex; i++) { WiseSaying wiseSaying = wiseSayings.get(i); System.out.printf("%d / %s / %s%n", wiseSaying.getId(), wiseSaying.getAuthor(), wiseSaying.getContent()); } + + System.out.println("----------------------"); + System.out.print("페이지 : "); + for (int i = 1; i <= totalPages; i++) { + if (i == page) { + System.out.print("[" + i + "]"); + } else { + System.out.print(" / " + i); + } + } + System.out.println(); } public void printWiseSayingByKeyword(String keywordType, String keyword) { diff --git a/src/test/java/WiseSayingControllerTest.java b/src/test/java/WiseSayingControllerTest.java index 3ab66d7..1b60e04 100644 --- a/src/test/java/WiseSayingControllerTest.java +++ b/src/test/java/WiseSayingControllerTest.java @@ -66,14 +66,14 @@ void printWiseSaying() throws IOException { TestUtil.clearSetOutToByteArray(outputStream); outputStream = TestUtil.setOutToByteArray(); - wiseSayingController.printWiseSayings(); + wiseSayingController.printWiseSayings("목록?page=1"); TestUtil.clearSetOutToByteArray(outputStream); String output = outputStream.toString().trim(); assertThat(output).contains("번호 / 작가 / 명언") - .contains("----------------------") - .contains("1 / 작자미상 / 현재를 사랑하라."); + .contains("----------------------") + .contains("1 / 작자미상 / 현재를 사랑하라."); } @Test From c6bce8c96defb75706d4e097735415a3a6fa0531 Mon Sep 17 00:00:00 2001 From: ohnoesganj Date: Fri, 3 Jan 2025 12:22:15 +0900 Subject: [PATCH 9/9] =?UTF-8?q?fix:=20=EB=AA=A9=EB=A1=9D=20=EB=AA=85?= =?UTF-8?q?=EB=A0=B9=EC=96=B4=20=EC=A4=91=EB=B3=B5=20=EB=B2=84=EA=B7=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/org/example/App.java | 2 +- src/main/java/org/example/WiseSayingController.java | 2 +- src/main/java/org/example/WiseSayingService.java | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/example/App.java b/src/main/java/org/example/App.java index 545d867..1741150 100644 --- a/src/main/java/org/example/App.java +++ b/src/main/java/org/example/App.java @@ -33,7 +33,7 @@ public void run() throws IOException, ParseException { public void handleCommand(String command, BufferedReader br) throws IOException { if (command.equals("등록")) { wiseSayingController.createWiseSaying(br); - } else if (command.startsWith("목록")) { + } else if (command.startsWith("목록?page=") || command.equals("목록")) { wiseSayingController.printWiseSayings(command); } else if (command.startsWith("삭제?id=")) { int id = Integer.parseInt(command.split("=")[1]); diff --git a/src/main/java/org/example/WiseSayingController.java b/src/main/java/org/example/WiseSayingController.java index 29dc818..bbd3d0e 100644 --- a/src/main/java/org/example/WiseSayingController.java +++ b/src/main/java/org/example/WiseSayingController.java @@ -96,7 +96,7 @@ public void deleteWiseSayingById(int id) throws IOException { } /// 명언 검색 - public void searchWiseSaying(String keywordType, String keyword) throws IOException { + public void searchWiseSaying(String keywordType, String keyword) { System.out.println("----------------------"); System.out.println("검색타입 : " + keywordType); System.out.println("검색어 : " + keyword); diff --git a/src/main/java/org/example/WiseSayingService.java b/src/main/java/org/example/WiseSayingService.java index 5f4a172..a350dd5 100644 --- a/src/main/java/org/example/WiseSayingService.java +++ b/src/main/java/org/example/WiseSayingService.java @@ -68,7 +68,10 @@ public void printWiseSaying(String command) { if (i == page) { System.out.print("[" + i + "]"); } else { - System.out.print(" / " + i); + System.out.print(i + " "); + } + if (i != totalPages) { + System.out.print(" / "); } } System.out.println();