code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,39 @@
+package christmas.domain;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum MenuType {
+ APPETIZER("์ ํผํ์ด์ ", Arrays.asList(Menu.MUSHROOM_SOUP, Menu.TAPAS, Menu.CAESAR_SALAD)),
+ MAIN("๋ฉ์ธ", Arrays.asList(Menu.T_BONE_STAKE, Menu.BARBECUE_LIP, Menu.SEAFOOD_PASTA, Menu.CHRISTMAS_PASTA)),
+ DESSERT("๋์ ํธ", Arrays.asList(Menu.CHOCOLATE_CAKE, Menu.ICE_CREAM)),
+ BEVERAGE("์๋ฃ", Arrays.asList(Menu.ZERO_COKE, Menu.RED_WINE, Menu.CHAMPAGNE));
+
+ private final String name;
+ private final List<Menu> menus;
+
+ MenuType(String name, List<Menu> menus) {
+ this.name = name;
+ this.menus = menus;
+ }
+
+ public static MenuType decideMenuType(Menu menu) {
+ MenuType[] menuTypes = values();
+
+ for (MenuType menuType : menuTypes) {
+ if (menuType.getMenus().contains(menu)) {
+ return menuType;
+ }
+ }
+
+ return null;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<Menu> getMenus() {
+ return menus;
+ }
+}
\ No newline at end of file | Java | ๋ง์์ ๋ค์ ๋ฌผ์ด๋ณด์
จ์ด์ ๋๊ธ์ ์ ๋ณด๋ฅผ ์ป์ ๋งํฌ ๋จ๊ฒจ๋๋ ธ์๋๋ฐ์ ๋ชป ๋ณด์ ๊ฒ ๊ฐ์ ๋ค์ ๋จ๊ฒจ๋๋ ค์..!!
https://techblog.woowahan.com/2527/
@Uniaut |
@@ -0,0 +1,21 @@
+package christmas.domain;
+
+public enum OrderResultType {
+ ORDER_MENU("<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ TOTAL_ORDER_PRICE("<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ GIFT_MENU("<์ฆ์ ๋ฉ๋ด>"),
+ BENEFIT_STATISTICS("<ํํ ๋ด์ญ>"),
+ TOTAL_BENEFIT_AMOUNT("<์ดํํ ๊ธ์ก>"),
+ ESTIMATED_PAYMENT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ EVENT_BADGE("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>");
+
+ private final String name;
+
+ OrderResultType(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๋ ์ข์ ๋ฐฉ๋ฒ์ธ๊ฒ ๊ฐ๋ค์!! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,45 @@
+package christmas.domain;
+
+public class OrderedMenu {
+ public static final String ORDER_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final int AMOUNT_MINIMUM_QUANTITY = 1;
+
+ private final String menuName;
+ private final int quantity;
+
+ public OrderedMenu(String menuName, int quantity) {
+ validateOrderNameExistInMenu(menuName);
+ validateOrderAmountQuantity(quantity);
+
+ this.menuName = menuName;
+ this.quantity = quantity;
+ }
+
+ private void validateOrderNameExistInMenu(String name) {
+ if (Menu.decideMenu(name) == Menu.NONE) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateOrderAmountQuantity(int amount) {
+ if (amount < AMOUNT_MINIMUM_QUANTITY) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isBeverage() {
+ return MenuType.decideMenuType(Menu.decideMenu(menuName)) == MenuType.BEVERAGE;
+ }
+
+ public int calculatePrice() {
+ return Menu.decideMenu(menuName).getPrice() * quantity;
+ }
+
+ public String getMenuName() {
+ return menuName;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+}
\ No newline at end of file | Java | ๋ง๋ค์..! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค!! Menu์ด๊ฑฐ์์ ๋ฉ๋ด์ ์ํ์ง ์๋ ์
๋ ฅ์ ์ฒ๋ฆฌํ๊ธฐ ์ํด "์์"์ ๋ง๋ค์์๋๋ฐ, ๋ง์ฝ null๋ก ์ฒ๋ฆฌํ์๋ค๋ฉด Menu์ ์ํ๋ ๊ฒ์ผ๋ก ์์ง ๊ฒ์ฆ์ด ์๋์๋ ๊ฑฐ๋๊น ์ง๊ธ์ฒ๋ผ String์ผ๋ก ํ๋ ๊ฒ์ด ๋ง์๊น์? ์ ๊ฐ ์ดํดํ ๊ฒ์ด ๋ง๋์ง ๊ถ๊ธํด์ @Uniaut |
@@ -0,0 +1,58 @@
+package christmas.domain;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+
+public class Date {
+ public static final String DATE_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final LocalDate CHRISTMAS_DAY = LocalDate.of(2023, 12, 25);
+ private static final int YEAR = 2023;
+ private static final int MONTH = 12;
+ private static final int DATE_MIN_NUMBER = 1;
+ private static final int DATE_MAX_NUMBER = 31;
+
+ private final int dayNumber;
+
+ public Date(int dayNumber) {
+ validateRange(dayNumber);
+ this.dayNumber = dayNumber;
+ }
+
+ private void validateRange(int dayNumber) {
+ if ((dayNumber < DATE_MIN_NUMBER) || (dayNumber > DATE_MAX_NUMBER)) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isDDayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+
+ return localDate.isBefore(CHRISTMAS_DAY.plusDays(1));
+ }
+
+ public boolean isWeekdayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.MONDAY) || day.equals(DayOfWeek.TUESDAY) || day.equals(DayOfWeek.WEDNESDAY)
+ || day.equals(DayOfWeek.THURSDAY) || day.equals(DayOfWeek.SUNDAY));
+ }
+
+ public boolean isWeekendDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.FRIDAY) || day.equals(DayOfWeek.SATURDAY));
+ }
+
+ public boolean isSpecialDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.SUNDAY) || localDate.equals(CHRISTMAS_DAY));
+ }
+
+ public int getDayNumber() {
+ return dayNumber;
+ }
+}
\ No newline at end of file | Java | @JaeHongDev
์ ๋ ์๋กญ๊ฒ ๋ฐฐ์๊ฐ๋๋ค..! |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ๋ง์์!! ์ ๋ ๊ฐ์ธ์ ์ผ๋ก ์ด ๋ฉ์๋์ ๋ก์ง์ ๋ง๋ค์๋ ๋ฐฉ์์ด ์์ฌ์ ๋๋ฐ์ ,, ๋ง์ํด ์ฃผ์ ๋ฐฉ๋ฒ์ด ํจ์ฌ ๊น๋ํ ๊ฒ ๊ฐ์์ ๋์
if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
return SANTA_BADGE;
}
if (totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) {
return TREE_BADGE;
}
if (totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) {
return STAR_BADGE;
}
return NON_BADGE;
์ด๋ฐ์์ผ๋ก ์ฐํ ๋ฐฐ์ง๊ฐ ์ ์ผ ์๋ก ๊ฐ์ผ 30000์์ผ ๋ ๋ณ ๋ฐฐ์ง๋ฅผ ๋ฆฌํดํ์ง ์๊ณ ์ฐํ ๋ฐฐ์ง๋ฅผ ๋ฆฌํด ํ ๊ฒ ๊ฐ์์
์ ๊ฐ ์ดํดํ๊ฒ ๋ง๋์ง ๊ถ๊ธํฉ๋๋ค @Uniaut
Maximum์ด๋ผ๋ ํํ์ ํด๋น ๊ฐ์ ํฌํจํ๋ ํํ์ด๋ ๊ฒ์ ๋์ณค๋ ๊ฒ ๊ฐ๋ค์!! ๋ ์นด๋ก์ด ์ง์ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | if๋ฌธ ์ ๊น์ง๊ฐ calculateTotalBenefitAmount๋ ๊ฐ์์ ๊ฐ์ ์ฝ๋๋ฅผ ์ ์ ํ์์์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํด๋ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ์ด if๋ฌธ์ ์กฐ๊ฑด๋ isReceivedGiftBenefit ๋ฉ์๋๋ฅผ ์ฌ์ฉํด๋ ๋๊ฒ ๋ค์! |
@@ -0,0 +1,76 @@
+package christmas.domain;
+
+import static christmas.domain.OrderedMenu.ORDER_RE_READ_REQUEST_MESSAGE;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class Order {
+ private static final int MAXIMUM_MENU_QUANTITY = 20;
+
+ private final List<OrderedMenu> order;
+
+ public Order(List<OrderedMenu> order) {
+ validateOrderedMenuNamesNotAllBeverage(order);
+ validateOrderedMenuNamesNotDuplicate(order);
+ validateTotalOrderedMenuQuantity(order);
+
+ this.order = order;
+ }
+
+ private void validateOrderedMenuNamesNotAllBeverage(List<OrderedMenu> order) {
+ List<Boolean> beverageChecker = new ArrayList<>();
+
+ for (OrderedMenu orderedMenu : order) {
+ if (orderedMenu.isBeverage()) {
+ beverageChecker.add(true);
+ }
+ if (!orderedMenu.isBeverage()) {
+ beverageChecker.add(false);
+ }
+ }
+
+ if (!beverageChecker.contains(false)) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateOrderedMenuNamesNotDuplicate(List<OrderedMenu> order) {
+ Set<String> duplicateChecker = new HashSet<>();
+
+ for (OrderedMenu orderedMenu : order) {
+ duplicateChecker.add(orderedMenu.getMenuName());
+ }
+ if (duplicateChecker.size() != order.size()) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateTotalOrderedMenuQuantity(List<OrderedMenu> order) {
+ int totalQuantity = 0;
+
+ for (OrderedMenu orderedMenu : order) {
+ totalQuantity += orderedMenu.getQuantity();
+ }
+ if (totalQuantity > MAXIMUM_MENU_QUANTITY) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public int calculateTotalOrderPrice() {
+ int totalOrderPrice = 0;
+
+ for (OrderedMenu orderedMenu : order) {
+ totalOrderPrice += orderedMenu.calculatePrice();
+ }
+
+ return totalOrderPrice;
+ }
+
+ public List<OrderedMenu> getOrder() {
+ return Collections.unmodifiableList(order);
+ }
+}
\ No newline at end of file | Java | ๋ฉ์๋๋ช
์ด ๊ธธ์ด๋ ํ์คํ ์ด๋ฆ๋ง ๋ณด๊ณ ๋ ์ด๋ค ์ญํ ์ ํ๋์ง ๋ฐ๋ก ์ ์ ์์ด์ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,152 @@
+package nextstep.subway.acceptance;
+
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_๊ถํ์ด_์์;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ;
+import static nextstep.subway.acceptance.LineSteps.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.MemberSteps.๋ก๊ทธ์ธ_๋์ด_์์;
+import static nextstep.subway.acceptance.MemberSteps.ํ์_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.StationSteps.์งํ์ฒ ์ญ_์์ฑ_์์ฒญ;
+
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+@DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ๊ธฐ๋ฅ")
+public class FavoritesAcceptanceTest extends AcceptanceTest {
+
+ public static final String EMAIL = "email@email.com";
+ public static final String PASSWORD = "password";
+ public static final int AGE = 20;
+
+ private Long ๊ต๋์ญ;
+ private Long ๊ฐ๋จ์ญ;
+ private Long ์์ฌ์ญ;
+ private Long ๋จ๋ถํฐ๋ฏธ๋์ญ;
+ private Long ์ดํธ์ ;
+ private Long ์ ๋ถ๋น์ ;
+ private Long ์ผํธ์ ;
+ private String ๋ก๊ทธ์ธํ ํฐ;
+
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ | | *3ํธ์ * *์ ๋ถ๋น์ * |
+ * | ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ต๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ต๋์ญ").jsonPath().getLong("id");
+ ๊ฐ๋จ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ฐ๋จ์ญ").jsonPath().getLong("id");
+ ์์ฌ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("์์ฌ์ญ").jsonPath().getLong("id");
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๋จ๋ถํฐ๋ฏธ๋์ญ").jsonPath().getLong("id");
+
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("2ํธ์ ", "green", ๊ต๋์ญ, ๊ฐ๋จ์ญ, 10);
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("์ ๋ถ๋น์ ", "red", ๊ฐ๋จ์ญ, ์์ฌ์ญ, 10);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("3ํธ์ ", "orange", ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 2);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ(์ผํธ์ , createSectionCreateParams(๋จ๋ถํฐ๋ฏธ๋์ญ, ์์ฌ์ญ, 3));
+
+ ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ ๋ก๊ทธ์ธํ ํฐ = ๋ก๊ทธ์ธ_๋์ด_์์(EMAIL, PASSWORD);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ถ๊ฐ ํ๊ธฐ")
+ @Test
+ public void addFavorite() {
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์กฐํ ํ๊ธฐ")
+ @Test
+ public void getFavorites() {
+ // given
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ์์ฌ์ญ, ๊ต๋์ญ);
+
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ(response, new Long[]{๊ฐ๋จ์ญ, ์์ฌ์ญ}, new Long[]{์์ฌ์ญ, ๊ต๋์ญ});
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ํ๊ธฐ")
+ @Test
+ public void deleteFavorites() {
+ // given
+ ExtractableResponse<Response> createResponse = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ(๋ก๊ทธ์ธํ ํฐ, createResponse);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ถ๊ฐ ํ๊ธฐ - ์ ํจํ์ง ์์ ํ ํฐ ์ผ ๊ฒฝ์ฐ")
+ @Test
+ public void addFavoriteWithInvalidToken() {
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ("invalid_token", ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_๊ถํ์ด_์์(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก์ ๊ด๋ฆฌํ๋ค.")
+ @Test
+ public void manageFavorites() {
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ์ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต);
+
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก ์กฐํ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก ์กฐํ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์๋ต, new Long[]{ ๊ฐ๋จ์ญ }, new Long[]{ ์์ฌ์ญ });
+
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์๋ต);
+ }
+
+
+ private Long ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(String name, String color, Long upStation, Long downStation,
+ int distance) {
+ Map<String, String> lineCreateParams;
+ lineCreateParams = new HashMap<>();
+ lineCreateParams.put("name", name);
+ lineCreateParams.put("color", color);
+ lineCreateParams.put("upStationId", upStation + "");
+ lineCreateParams.put("downStationId", downStation + "");
+ lineCreateParams.put("distance", distance + "");
+
+ return LineSteps.์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(lineCreateParams).jsonPath().getLong("id");
+ }
+
+ private Map<String, String> createSectionCreateParams(Long upStationId, Long downStationId,
+ int distance) {
+ Map<String, String> params = new HashMap<>();
+ params.put("upStationId", upStationId + "");
+ params.put("downStationId", downStationId + "");
+ params.put("distance", distance + "");
+ return params;
+ }
+
+} | Java | `์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก์ ๊ด๋ฆฌํ๋ค` ์์ ์๋๋ฆฌ์ค ํ์์ผ๋ก ์ ์์ฑํด์ฃผ์
์
ํด๋น ํ
์คํธ๋ค์ ์์ฑํด์ฃผ์ง ์์๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์์ ๐ |
@@ -0,0 +1,50 @@
+package nextstep.subway.applicaion;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import nextstep.member.application.MemberService;
+import nextstep.member.domain.LoginMember;
+import nextstep.member.domain.MemberRepository;
+import nextstep.subway.applicaion.dto.FavoriteRequest;
+import nextstep.subway.applicaion.dto.FavoriteResponse;
+import nextstep.subway.domain.Favorite;
+import nextstep.subway.domain.FavoriteRepository;
+import nextstep.subway.domain.Station;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class FavoriteService {
+ private final StationService stationService;
+ private final PathService pathService;
+ private final MemberRepository memberRepository;
+ private final FavoriteRepository favoriteRepository;
+
+ public FavoriteService(StationService stationService, PathService pathService,
+ MemberRepository memberRepository, FavoriteRepository favoriteRepository) {
+ this.stationService = stationService;
+ this.pathService = pathService;
+ this.memberRepository = memberRepository;
+ this.favoriteRepository = favoriteRepository;
+ }
+
+ public FavoriteResponse createFavorite(FavoriteRequest favoriteRequest, Long memberId) {
+ Station source = stationService.findById(favoriteRequest.getSource());
+ Station target = stationService.findById(favoriteRequest.getTarget());
+ pathService.findPath(source, target);
+ Favorite favorite = favoriteRepository.save(Favorite.of(memberId, source, target));
+ return FavoriteResponse.from(favorite);
+ }
+
+ @Transactional(readOnly = true)
+ public List<FavoriteResponse> findFavorites(Long memberId) {
+ List<Favorite> favorites = favoriteRepository.findAllByMemberId(memberId);
+ return favorites.stream().map(FavoriteResponse::from).collect(Collectors.toList());
+ }
+
+ public void deleteFavorite(Long favoriteId, Long memberId) {
+ Favorite favorite = favoriteRepository.getById(favoriteId);
+ favorite.hasPermission(memberId);
+ favoriteRepository.delete(favorite);
+ }
+} | Java | memberRepository ๋ฅผ ์ฌ์ฉํ๊ณ ์์ง ์๋๋ฐ์,
์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ, ์กฐํ, ์ญ์ ์ ์ ์ํ memberId ์ธ์ง ํ์ธํ์ง ์์๋ ๋ ๊น์? ๐ |
@@ -22,10 +22,14 @@ public PathService(LineService lineService, StationService stationService) {
public PathResponse findPath(Long source, Long target) {
Station upStation = stationService.findById(source);
Station downStation = stationService.findById(target);
- List<Line> lines = lineService.findLines();
- SubwayMap subwayMap = new SubwayMap(lines);
- Path path = subwayMap.findPath(upStation, downStation);
+ Path path = findPath(upStation, downStation);
return PathResponse.of(path);
}
+
+ Path findPath(Station upStation, Station downStation) {
+ List<Line> lines = lineService.findLines();
+ SubwayMap subwayMap = new SubwayMap(lines);
+ return subwayMap.findPath(upStation, downStation);
+ }
} | Java | ์ ๊ทผ์ ์ด์๋ฅผ ์๋ตํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์? ๐ |
@@ -0,0 +1,39 @@
+package nextstep.subway.applicaion.dto;
+
+import nextstep.subway.domain.Favorite;
+
+public class FavoriteResponse {
+ private Long id;
+ private Long memberId;
+ private StationResponse source;
+ private StationResponse target;
+
+ private FavoriteResponse(Long id, Long memberId,
+ StationResponse source, StationResponse target) {
+ this.id = id;
+ this.memberId = memberId;
+ this.source = source;
+ this.target = target;
+ }
+
+ public static FavoriteResponse from(Favorite favorite) {
+ return new FavoriteResponse(favorite.getId(), favorite.getMemberId(),
+ StationResponse.of(favorite.getSource()), StationResponse.of(favorite.getTarget()));
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getMemberId() {
+ return memberId;
+ }
+
+ public StationResponse getSource() {
+ return source;
+ }
+
+ public StationResponse getTarget() {
+ return target;
+ }
+} | Java | ์๊ตฌ์ฌํญ์ memberId ๋ ์๋ค์!
์๊ตฌ์ฌํญ์ ํ์ธํด์ฃผ์ธ์ ๐ |
@@ -0,0 +1,49 @@
+package nextstep.subway.ui;
+
+import java.net.URI;
+import java.util.List;
+import nextstep.auth.authorization.AuthenticationPrincipal;
+import nextstep.member.domain.LoginMember;
+import nextstep.subway.applicaion.FavoriteService;
+import nextstep.subway.applicaion.dto.FavoriteRequest;
+import nextstep.subway.applicaion.dto.FavoriteResponse;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/favorites")
+public class FavoriteController {
+
+ private final FavoriteService favoriteService;
+
+ public FavoriteController(FavoriteService favoriteService) {
+ this.favoriteService = favoriteService;
+ }
+
+ @PostMapping
+ public ResponseEntity<FavoriteResponse> createFavorite(
+ @AuthenticationPrincipal LoginMember loginMember,
+ @RequestBody FavoriteRequest favoriteRequest) {
+ FavoriteResponse favoriteResponse = favoriteService.createFavorite(favoriteRequest, loginMember.getId());
+ return ResponseEntity.created(URI.create("/favorites/" + favoriteResponse.getId())).body(favoriteResponse);
+ }
+
+ @GetMapping
+ public ResponseEntity<List<FavoriteResponse>> getFavorites(@AuthenticationPrincipal LoginMember loginMember) {
+ List<FavoriteResponse> favoriteResponses = favoriteService.findFavorites(loginMember.getId());
+ return ResponseEntity.ok(favoriteResponses);
+ }
+
+ @DeleteMapping("/{favoriteId}")
+ public ResponseEntity<Void> deleteFavorite(@AuthenticationPrincipal LoginMember loginMember, @PathVariable Long favoriteId) {
+ favoriteService.deleteFavorite(favoriteId, loginMember.getId());
+ return ResponseEntity.noContent().build();
+ }
+
+} | Java | ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ ํ ๋ฐํ๊ฐ์ ๋ํ ์๊ตฌ์ฌํญ์ ํ์ธํด์ฃผ์ธ์! ๐
 |
@@ -1,5 +1,6 @@
package nextstep.subway.domain;
+import java.util.Optional;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
@@ -22,6 +23,11 @@ public Path findPath(Station source, Station target) {
DijkstraShortestPath<Station, SectionEdge> dijkstraShortestPath = new DijkstraShortestPath<>(graph);
GraphPath<Station, SectionEdge> result = dijkstraShortestPath.getPath(source, target);
+ Optional.ofNullable(result)
+ .orElseThrow(() -> {
+ throw new IllegalArgumentException("์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ๋์ด ์์ง ์์ต๋๋ค.");
+ });
+
List<Section> sections = result.getEdgeList().stream()
.map(it -> it.getSection())
.collect(Collectors.toList()); | Java | Optional ์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์?
์ด๋ ํ ์ด์ ์ด ์๋์? ๐
```suggestion
if (Objects.isNull(result)) {
throw new IllegalArgumentException("์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ๋์ด ์์ง ์์ต๋๋ค.");
}
``` |
@@ -0,0 +1,21 @@
+package nextstep.subway;
+
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class ControllerExceptionHandler {
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity handleIllegalArgumentException(IllegalArgumentException illegalArgumentException){
+ String message = illegalArgumentException.getMessage();
+ return ResponseEntity.badRequest().body(message);
+ }
+} | Java | @RestControllerAdvice ๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ ์๋ฌ๋ฅผ ํ๊ตฐ๋ฐ์ ์ฒ๋ฆฌํด์ค ์ ์๊ฒํด์ค ๋ถ๋ถ ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,21 @@
+package nextstep.subway;
+
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class ControllerExceptionHandler {
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity handleIllegalArgumentException(IllegalArgumentException illegalArgumentException){
+ String message = illegalArgumentException.getMessage();
+ return ResponseEntity.badRequest().body(message);
+ }
+} | Java | ์ด ๋ถ๋ถ์ ์กฐ๊ธ ๊ถ๊ธํ์ฌ ์ฌ์ญค๋ด
๋๋ค! DataIntegrityViolationException ๋ ํ์ฌ ์ดํ๋ฆฌ์ผ์ด์
๋ด์์ ์ธ์ , ์ด๋ค ์ผ์ด์ค์์ ๋ฐ์ํ๊ฒ ๋๋์...? |
@@ -0,0 +1,38 @@
+package nextstep.subway.line.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import nextstep.subway.station.domain.Station;
+import org.jgrapht.GraphPath;
+import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
+
+public class Lines {
+
+ List<Line> lines = new ArrayList<>();
+
+ public Lines(List<Line> lines) {
+ this.lines = lines;
+ }
+
+ public GraphPath minPath(Station sourceStation, Station targetStation) {
+
+ validatePath(sourceStation, targetStation);
+ WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(DefaultWeightedEdge.class);
+
+ for (Line line : lines) {
+ line.addPathInfo(graph);
+ }
+
+ DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(graph);
+
+ return dijkstraShortestPath.getPath(sourceStation, targetStation);
+ }
+
+ private void validatePath(Station sourceStation, Station targetStation){
+ if(sourceStation.equals(targetStation)){
+ throw new IllegalArgumentException("๊ฒฝ๋ก ์์์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ผ์นํฉ๋๋ค.");
+ }
+ }
+} | Java | ์ ๊ทผ์ ํ์๊ฐ ์๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,38 @@
+package nextstep.subway.line.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import nextstep.subway.station.domain.Station;
+import org.jgrapht.GraphPath;
+import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
+
+public class Lines {
+
+ List<Line> lines = new ArrayList<>();
+
+ public Lines(List<Line> lines) {
+ this.lines = lines;
+ }
+
+ public GraphPath minPath(Station sourceStation, Station targetStation) {
+
+ validatePath(sourceStation, targetStation);
+ WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(DefaultWeightedEdge.class);
+
+ for (Line line : lines) {
+ line.addPathInfo(graph);
+ }
+
+ DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(graph);
+
+ return dijkstraShortestPath.getPath(sourceStation, targetStation);
+ }
+
+ private void validatePath(Station sourceStation, Station targetStation){
+ if(sourceStation.equals(targetStation)){
+ throw new IllegalArgumentException("๊ฒฝ๋ก ์์์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ผ์นํฉ๋๋ค.");
+ }
+ }
+} | Java | ๋์ฌ๊ตฌ๋ก ๋ฉ์๋๋ฅผ ํํํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์...? ๊ทธ๋ฆฌ๊ณ ํน์ ์ ๋๋ฆญ์ ์์ฐ์๋ ์ด์ ๊ฐ ์์ผ์ค๊น์...? |
@@ -6,9 +6,11 @@
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
-import nextstep.subway.SectionsNotAddedException;
-import nextstep.subway.SectionsNotRemovedException;
+import nextstep.subway.line.exception.SectionsNotAddedException;
+import nextstep.subway.line.exception.SectionsNotRemovedException;
import nextstep.subway.station.domain.Station;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
@Embeddable
public class Sections {
@@ -34,41 +36,36 @@ public void requestAddSection(Section section) {
sections.add(section);
return;
}
- checkExistsStation(section, section.getUpStation(), section.getDownStation());
+ checkExistsStation(section);
}
- private void checkExistsStation(Section section, Station upStation, Station downStation) {
- boolean upMatchesLineUp = stationExistsInUp(upStation);
- boolean downMatchsLineDown = stationExistsInDown(downStation);
- boolean matchesAtFront = stationExistsInUp(downStation);
- boolean matchesAtBack = stationExistsInDown(upStation);
- if (!upMatchesLineUp && !matchesAtFront && !matchesAtBack && !downMatchsLineDown) {
+ private void checkExistsStation(Section section) {
+ boolean upMatchesLineUp = stationExistsInUp(section.getUpStation());
+ boolean downMatchesLineDown = stationExistsInDown(section.getDownStation());
+ boolean matchesAtEnd = stationExistsAtEnd(section);
+
+ if (!upMatchesLineUp && !downMatchesLineDown && !matchesAtEnd) {
throw new SectionsNotAddedException("๊ตฌ๊ฐ ์ค ์ด๋ ํ ์ญ๋ ํ์ฌ ๊ตฌ๊ฐ์ ์์ต๋๋ค.");
}
- if (upMatchesLineUp && downMatchsLineDown) {
+ if (upMatchesLineUp && downMatchesLineDown) {
throw new SectionsNotAddedException("์ด๋ฏธ ๋ฑ๋ก๋ ๊ตฌ๊ฐ ์
๋๋ค.");
}
- addSectionToMatchStation(section, upStation, downStation, upMatchesLineUp, downMatchsLineDown, matchesAtFront,
- matchesAtBack);
-
+ addSectionToMatchStation(section, upMatchesLineUp, downMatchesLineDown);
}
- private void addSectionToMatchStation(Section section, Station upStation, Station downStation,
- boolean upMatchesLineUp, boolean downMatchsLineDown, boolean matchesAtFront,
- boolean matchesAtBack) {
+ private void addSectionToMatchStation(Section section, boolean upMatchesLineUp, boolean downMatchsLineDown) {
+ Station upStation = section.getUpStation();
+ Station downStation = section.getDownStation();
if (upMatchesLineUp) {
- addUpStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateUpStationMatch(section, upStation, downStation, section.getDistance());
}
if (downMatchsLineDown) {
- addDownStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateDownStatioMatch(section, upStation, downStation, section.getDistance());
}
- if (matchesAtFront || matchesAtBack) {
- sections.add(section);
- }
+ //์์ชฝ ๋์ ๋ํด์ง ๊ฒฝ์ฐ
+ sections.add(section);
}
private boolean stationExistsInUp(Station station) {
@@ -79,33 +76,40 @@ private boolean stationExistsInDown(Station station) {
return sections.stream().anyMatch(section -> section.getDownStation().equals(station));
}
+ private boolean stationExistsAtEnd(Section section) {
+ return sections.stream().anyMatch(
+ sectionIterate -> sectionIterate.getDownStation().equals(section.getUpStation())
+ || sectionIterate.getUpStation().equals(section.getDownStation()));
+ }
- private void addUpStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateUpStationMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> upStation.equals(sectionIterate.getUpStation())).findFirst()
.ifPresent(sectionIterate -> sectionIterate.updateUpStation(downStation, distance));
- sections.add(section);
}
- private void addDownStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateDownStatioMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> downStation.equals(sectionIterate.getDownStation())).findFirst()
.ifPresent(it -> it.updateDownStation(upStation, distance));
- sections.add(section);
}
+
public void removeLineStation(Station station, Line line) {
if (sections.size() <= ONE) {
throw new SectionsNotRemovedException("ํ์ฌ ๊ตฌ๊ฐ์ด ํ๋๋ฐ์ ์์ต๋๋ค.");
}
- Optional<Section> upLineStation = sections.stream().filter(it -> it.getUpStation() == station).findFirst();
- Optional<Section> downLineStation = sections.stream().filter(it -> it.getDownStation() == station).findFirst();
+ Optional<Section> upLineStation = sections.stream().filter(section -> section.getUpStation().equals(station))
+ .findFirst();
+ Optional<Section> downLineStation = sections.stream()
+ .filter(section -> section.getDownStation().equals(station)).findFirst();
connectFrontBackSection(line, upLineStation, downLineStation);
- upLineStation.ifPresent(it -> sections.remove(it));
- downLineStation.ifPresent(it -> sections.remove(it));
+ upLineStation.ifPresent(section -> sections.remove(section));
+ downLineStation.ifPresent(section -> sections.remove(section));
}
- private void connectFrontBackSection(Line line, Optional<Section> upLineStation, Optional<Section> downLineStation) {
+ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
+ Optional<Section> downLineStation) {
if (upLineStation.isPresent() && downLineStation.isPresent()) {
Station newUpStation = downLineStation.get().getUpStation();
Station newDownStation = upLineStation.get().getDownStation();
@@ -114,4 +118,11 @@ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
sections.add(new Section(line, newUpStation, newDownStation, newDistance));
}
}
+
+ public void addGraphEdge(WeightedMultigraph<Station, DefaultWeightedEdge> graph) {
+ for (Section section : sections) {
+ section.addGraphEdge(graph);
+ }
+ }
+
}
\ No newline at end of file | Java | ์ด๋ถ๋ถ๋ Section์ ๋ฉ์์ง๋ฅผ ๋์ ธ์ ํ์ธํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -6,9 +6,11 @@
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
-import nextstep.subway.SectionsNotAddedException;
-import nextstep.subway.SectionsNotRemovedException;
+import nextstep.subway.line.exception.SectionsNotAddedException;
+import nextstep.subway.line.exception.SectionsNotRemovedException;
import nextstep.subway.station.domain.Station;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
@Embeddable
public class Sections {
@@ -34,41 +36,36 @@ public void requestAddSection(Section section) {
sections.add(section);
return;
}
- checkExistsStation(section, section.getUpStation(), section.getDownStation());
+ checkExistsStation(section);
}
- private void checkExistsStation(Section section, Station upStation, Station downStation) {
- boolean upMatchesLineUp = stationExistsInUp(upStation);
- boolean downMatchsLineDown = stationExistsInDown(downStation);
- boolean matchesAtFront = stationExistsInUp(downStation);
- boolean matchesAtBack = stationExistsInDown(upStation);
- if (!upMatchesLineUp && !matchesAtFront && !matchesAtBack && !downMatchsLineDown) {
+ private void checkExistsStation(Section section) {
+ boolean upMatchesLineUp = stationExistsInUp(section.getUpStation());
+ boolean downMatchesLineDown = stationExistsInDown(section.getDownStation());
+ boolean matchesAtEnd = stationExistsAtEnd(section);
+
+ if (!upMatchesLineUp && !downMatchesLineDown && !matchesAtEnd) {
throw new SectionsNotAddedException("๊ตฌ๊ฐ ์ค ์ด๋ ํ ์ญ๋ ํ์ฌ ๊ตฌ๊ฐ์ ์์ต๋๋ค.");
}
- if (upMatchesLineUp && downMatchsLineDown) {
+ if (upMatchesLineUp && downMatchesLineDown) {
throw new SectionsNotAddedException("์ด๋ฏธ ๋ฑ๋ก๋ ๊ตฌ๊ฐ ์
๋๋ค.");
}
- addSectionToMatchStation(section, upStation, downStation, upMatchesLineUp, downMatchsLineDown, matchesAtFront,
- matchesAtBack);
-
+ addSectionToMatchStation(section, upMatchesLineUp, downMatchesLineDown);
}
- private void addSectionToMatchStation(Section section, Station upStation, Station downStation,
- boolean upMatchesLineUp, boolean downMatchsLineDown, boolean matchesAtFront,
- boolean matchesAtBack) {
+ private void addSectionToMatchStation(Section section, boolean upMatchesLineUp, boolean downMatchsLineDown) {
+ Station upStation = section.getUpStation();
+ Station downStation = section.getDownStation();
if (upMatchesLineUp) {
- addUpStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateUpStationMatch(section, upStation, downStation, section.getDistance());
}
if (downMatchsLineDown) {
- addDownStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateDownStatioMatch(section, upStation, downStation, section.getDistance());
}
- if (matchesAtFront || matchesAtBack) {
- sections.add(section);
- }
+ //์์ชฝ ๋์ ๋ํด์ง ๊ฒฝ์ฐ
+ sections.add(section);
}
private boolean stationExistsInUp(Station station) {
@@ -79,33 +76,40 @@ private boolean stationExistsInDown(Station station) {
return sections.stream().anyMatch(section -> section.getDownStation().equals(station));
}
+ private boolean stationExistsAtEnd(Section section) {
+ return sections.stream().anyMatch(
+ sectionIterate -> sectionIterate.getDownStation().equals(section.getUpStation())
+ || sectionIterate.getUpStation().equals(section.getDownStation()));
+ }
- private void addUpStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateUpStationMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> upStation.equals(sectionIterate.getUpStation())).findFirst()
.ifPresent(sectionIterate -> sectionIterate.updateUpStation(downStation, distance));
- sections.add(section);
}
- private void addDownStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateDownStatioMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> downStation.equals(sectionIterate.getDownStation())).findFirst()
.ifPresent(it -> it.updateDownStation(upStation, distance));
- sections.add(section);
}
+
public void removeLineStation(Station station, Line line) {
if (sections.size() <= ONE) {
throw new SectionsNotRemovedException("ํ์ฌ ๊ตฌ๊ฐ์ด ํ๋๋ฐ์ ์์ต๋๋ค.");
}
- Optional<Section> upLineStation = sections.stream().filter(it -> it.getUpStation() == station).findFirst();
- Optional<Section> downLineStation = sections.stream().filter(it -> it.getDownStation() == station).findFirst();
+ Optional<Section> upLineStation = sections.stream().filter(section -> section.getUpStation().equals(station))
+ .findFirst();
+ Optional<Section> downLineStation = sections.stream()
+ .filter(section -> section.getDownStation().equals(station)).findFirst();
connectFrontBackSection(line, upLineStation, downLineStation);
- upLineStation.ifPresent(it -> sections.remove(it));
- downLineStation.ifPresent(it -> sections.remove(it));
+ upLineStation.ifPresent(section -> sections.remove(section));
+ downLineStation.ifPresent(section -> sections.remove(section));
}
- private void connectFrontBackSection(Line line, Optional<Section> upLineStation, Optional<Section> downLineStation) {
+ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
+ Optional<Section> downLineStation) {
if (upLineStation.isPresent() && downLineStation.isPresent()) {
Station newUpStation = downLineStation.get().getUpStation();
Station newDownStation = upLineStation.get().getDownStation();
@@ -114,4 +118,11 @@ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
sections.add(new Section(line, newUpStation, newDownStation, newDistance));
}
}
+
+ public void addGraphEdge(WeightedMultigraph<Station, DefaultWeightedEdge> graph) {
+ for (Section section : sections) {
+ section.addGraphEdge(graph);
+ }
+ }
+
}
\ No newline at end of file | Java | ์ฌ๊ธฐ๊น์ง ํผ๋๋ฐฑ ๋ฐ์ ์ข๋ค์ ใ
ใ
๐ |
@@ -0,0 +1,38 @@
+package nextstep.subway.path.application;
+
+import nextstep.subway.station.exception.StationNotFoundException;
+import nextstep.subway.line.domain.LineRepository;
+import nextstep.subway.line.domain.Lines;
+import nextstep.subway.path.dto.PathResponse;
+import nextstep.subway.station.domain.Station;
+import nextstep.subway.station.domain.StationRepository;
+import org.jgrapht.GraphPath;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PathService {
+
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public PathService(StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public PathResponse minPath(Long sourceStationId, Long targetStationId) {
+ System.out.println("PathService.minPath");
+
+ Station sourceStation = stationRepository.findById(sourceStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ์์์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+ Station targetStation = stationRepository.findById(targetStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ๋์ฐฉ์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+
+ Lines lines = new Lines(lineRepository.findAll());
+ GraphPath graphPath = lines.minPath(sourceStation, targetStation);
+
+ PathResponse pathResponse = new PathResponse(graphPath.getVertexList(), (int) graphPath.getWeight());
+
+ return pathResponse;
+ }
+} | Java | ์ฌ๊ธฐ์ ํน์ System ํจ์๋ฅผ ์ฐ์ ์ด์ ๊ฐ ์์๊น์...? Sysytem ํจ์๋ ๋ฆฌ์์ค๋ฅผ ๋ง์ด ๋จน์ด์ ์ต๋ํ ์ฌ์ฉํ์ง ์๋ ๊ฒ์ด ์ข์ต๋๋ค. |
@@ -0,0 +1,38 @@
+package nextstep.subway.path.application;
+
+import nextstep.subway.station.exception.StationNotFoundException;
+import nextstep.subway.line.domain.LineRepository;
+import nextstep.subway.line.domain.Lines;
+import nextstep.subway.path.dto.PathResponse;
+import nextstep.subway.station.domain.Station;
+import nextstep.subway.station.domain.StationRepository;
+import org.jgrapht.GraphPath;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PathService {
+
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public PathService(StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public PathResponse minPath(Long sourceStationId, Long targetStationId) {
+ System.out.println("PathService.minPath");
+
+ Station sourceStation = stationRepository.findById(sourceStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ์์์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+ Station targetStation = stationRepository.findById(targetStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ๋์ฐฉ์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+
+ Lines lines = new Lines(lineRepository.findAll());
+ GraphPath graphPath = lines.minPath(sourceStation, targetStation);
+
+ PathResponse pathResponse = new PathResponse(graphPath.getVertexList(), (int) graphPath.getWeight());
+
+ return pathResponse;
+ }
+} | Java | Repository ์กฐํํ๋ ๋ถ๋ถ์ด ์๋๋ฐ readOnly ์ต์
์ ์ฃผ๋ ๊ฒ์ ์ด๋จ๊น์....? |
@@ -1,9 +1,111 @@
package nextstep.subway.path;
+import static nextstep.subway.line.acceptance.LineAcceptanceTest.์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
import nextstep.subway.AcceptanceTest;
+import nextstep.subway.line.acceptance.LineSectionAcceptanceTest;
+import nextstep.subway.line.dto.LineRequest;
+import nextstep.subway.line.dto.LineResponse;
+import nextstep.subway.station.StationAcceptanceTest;
+import nextstep.subway.station.dto.StationResponse;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
@DisplayName("์งํ์ฒ ๊ฒฝ๋ก ์กฐํ")
public class PathAcceptanceTest extends AcceptanceTest {
+
+ private LineResponse ์ ๋ถ๋น์ ;
+ private LineResponse ์ดํธ์ ;
+ private LineResponse ์ผํธ์ ;
+ private StationResponse ๊ฐ๋จ์ญ;
+ private StationResponse ์์ฌ์ญ;
+ private StationResponse ๊ต๋์ญ;
+ private StationResponse ๋จ๋ถํฐ๋ฏธ๋์ญ;
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ
+ * | |
+ * *3ํธ์ * *์ ๋ถ๋น์ *
+ * | |
+ * ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ฐ๋จ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ฐ๋จ์ญ").as(StationResponse.class);
+ ์์ฌ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("์์ฌ์ญ").as(StationResponse.class);
+ ๊ต๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ต๋์ญ").as(StationResponse.class);
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๋จ๋ถํฐ๋ฏธ๋์ญ").as(StationResponse.class);
+
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ ๋ถ๋น์ ", "bg-red-600", ๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId(), 10)).as(
+ LineResponse.class);
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ดํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ๊ฐ๋จ์ญ.getId(), 10)).as(LineResponse.class);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ผํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ์์ฌ์ญ.getId(), 5)).as(LineResponse.class);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(์ผํธ์ , ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 3);
+ }
+
+ private ExtractableResponse<Response> ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(LineResponse lineResponse, StationResponse upStation,
+ StationResponse downStation,
+ int distance) {
+ return LineSectionAcceptanceTest.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก_์์ฒญ(lineResponse,
+ upStation, downStation, distance);
+ }
+
+ @Test
+ @DisplayName("๊ต๋์ญ-์์ฌ์ญ ์ต๋จ๊ฒฝ๋ก ์กฐํํ๊ธฐ (๊ต๋์ญ-๋จ๋ถํฐ๋ฏธ๋์ญ-์์ฌ์ญ)")
+ public void findMinPath() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ์์ฌ์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ, 5, "๊ต๋์ญ","๋จ๋ถํฐ๋ฏธ๋์ญ", "์์ฌ์ญ");
+ }
+
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์์์ญ ๋์ฐฉ์ญ ์ผ์น ์กฐํ ์๋ฌ ํ์ธ")
+ public void findMinPathSourceTargetSame() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ๊ต๋์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์กฐํ์ ๋ฏธ์กด์ฌ ์ญ ์๋ฌ ํ์ธ")
+ public void findMinPathNotExsistStation() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(new StationResponse(), new StationResponse());
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(ExtractableResponse<Response> response) {
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(ExtractableResponse<Response> response,int distance, String... stationNames) {
+ assertThat(response.jsonPath().getInt("distance")).isEqualTo(distance);
+ assertThat(response.jsonPath().getList("stations.name")).containsExactly(stationNames);
+ }
+
+ private ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(StationResponse source, StationResponse target) {
+ Map<String, Long> param = new HashMap<>();
+ param.put("source", source.getId());
+ param.put("target", target.getId());
+
+ return RestAssured
+ .given().log().all()
+ .queryParams(param)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .when().get("/paths")
+ .then().log().all()
+ .extract();
+ }
+
} | Java | ์ธ์ํ
์คํธ ์ข์ต๋๋ค ๐ ๋ค๋ง ์ด๋ฒ์ ์๋ก๋ง๋์ Lines์ ๋ํ ๋จ์ ํ
์คํธ, PathService์ ๋ํ ๋จ์ํ
์คํธ๋ ์ถ๊ฐ๋๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
Lines์ ๊ฒฝ์ฐ ์ค์ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฏ๋ก ํด๋น ์ค์ ๊ฐ์ฒด๋ฅผ ์ด์ฉํ์ฌ ํ
์คํธ๋ฅผ ์์ฑํ๊ณ , PathService์ ๊ฒฝ์ฐ๋ ์ธ๋ถ ์์กด์ฑ์ Mocking ํ ๋จ์ ํ
์คํธ๋ฅผ ์์ฑํด๋ณด๋ ๊ฒ๋ ์ข์ ๊ณต๋ถ๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -1,9 +1,111 @@
package nextstep.subway.path;
+import static nextstep.subway.line.acceptance.LineAcceptanceTest.์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
import nextstep.subway.AcceptanceTest;
+import nextstep.subway.line.acceptance.LineSectionAcceptanceTest;
+import nextstep.subway.line.dto.LineRequest;
+import nextstep.subway.line.dto.LineResponse;
+import nextstep.subway.station.StationAcceptanceTest;
+import nextstep.subway.station.dto.StationResponse;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
@DisplayName("์งํ์ฒ ๊ฒฝ๋ก ์กฐํ")
public class PathAcceptanceTest extends AcceptanceTest {
+
+ private LineResponse ์ ๋ถ๋น์ ;
+ private LineResponse ์ดํธ์ ;
+ private LineResponse ์ผํธ์ ;
+ private StationResponse ๊ฐ๋จ์ญ;
+ private StationResponse ์์ฌ์ญ;
+ private StationResponse ๊ต๋์ญ;
+ private StationResponse ๋จ๋ถํฐ๋ฏธ๋์ญ;
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ
+ * | |
+ * *3ํธ์ * *์ ๋ถ๋น์ *
+ * | |
+ * ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ฐ๋จ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ฐ๋จ์ญ").as(StationResponse.class);
+ ์์ฌ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("์์ฌ์ญ").as(StationResponse.class);
+ ๊ต๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ต๋์ญ").as(StationResponse.class);
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๋จ๋ถํฐ๋ฏธ๋์ญ").as(StationResponse.class);
+
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ ๋ถ๋น์ ", "bg-red-600", ๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId(), 10)).as(
+ LineResponse.class);
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ดํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ๊ฐ๋จ์ญ.getId(), 10)).as(LineResponse.class);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ผํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ์์ฌ์ญ.getId(), 5)).as(LineResponse.class);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(์ผํธ์ , ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 3);
+ }
+
+ private ExtractableResponse<Response> ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(LineResponse lineResponse, StationResponse upStation,
+ StationResponse downStation,
+ int distance) {
+ return LineSectionAcceptanceTest.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก_์์ฒญ(lineResponse,
+ upStation, downStation, distance);
+ }
+
+ @Test
+ @DisplayName("๊ต๋์ญ-์์ฌ์ญ ์ต๋จ๊ฒฝ๋ก ์กฐํํ๊ธฐ (๊ต๋์ญ-๋จ๋ถํฐ๋ฏธ๋์ญ-์์ฌ์ญ)")
+ public void findMinPath() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ์์ฌ์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ, 5, "๊ต๋์ญ","๋จ๋ถํฐ๋ฏธ๋์ญ", "์์ฌ์ญ");
+ }
+
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์์์ญ ๋์ฐฉ์ญ ์ผ์น ์กฐํ ์๋ฌ ํ์ธ")
+ public void findMinPathSourceTargetSame() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ๊ต๋์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์กฐํ์ ๋ฏธ์กด์ฌ ์ญ ์๋ฌ ํ์ธ")
+ public void findMinPathNotExsistStation() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(new StationResponse(), new StationResponse());
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(ExtractableResponse<Response> response) {
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(ExtractableResponse<Response> response,int distance, String... stationNames) {
+ assertThat(response.jsonPath().getInt("distance")).isEqualTo(distance);
+ assertThat(response.jsonPath().getList("stations.name")).containsExactly(stationNames);
+ }
+
+ private ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(StationResponse source, StationResponse target) {
+ Map<String, Long> param = new HashMap<>();
+ param.put("source", source.getId());
+ param.put("target", target.getId());
+
+ return RestAssured
+ .given().log().all()
+ .queryParams(param)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .when().get("/paths")
+ .then().log().all()
+ .extract();
+ }
+
} | Java | ์ฐ๊ฒฐ๋์ด ์์ง ์์ ์ญ์ ๋ํ ์ต๋จ๊ฑฐ๋ฆฌ ์กฐํ์ ๊ฒฝ์ฐ์๋ ํ
์คํธ๋ฅผ ์ถ๊ฐํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์...? |
@@ -0,0 +1,22 @@
+package codesquad.dto.question;
+
+import lombok.*;
+
+@AllArgsConstructor
+@Getter
+@Setter
+@Builder
+public class QuestionRequestDto {
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionDto{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | ๊ธฐ๋ณธ ์์ฑ์๋ฅผ ์์ฑํด์ฃผ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ปจํธ๋กค๋ฌ๋ @Controller ์ด๋
ธํ
์ด์
์ ์ด์ฉํด ๋น์ ๋ฑ๋กํ๊ณ ๊ณ์๋๋ฐ, Service์ Repository๋ Config ํ์ผ์์ ๋น์ ๋ฐ๋ก ๋ฑ๋กํด์ฃผ๊ณ ๊ณ์๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | update()๋ dto๋ฅผ ๋๊ฒจ์ฃผ๊ณ ์๋๋ฐ, register()๋ ์ํฐํฐ๋ฅผ ๋๊ฒจ์ฃผ๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | Entity, Model, Dto, VO์ ์ฐจ์ด์ ๋ํด ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | applicationcontext๋ก๋ถํฐ ์ง์ ๋น์ ๊ฐ์ ธ์ค์
์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -1,18 +1,17 @@
package codesquad.controller;
import codesquad.AppConfig;
-import codesquad.dto.UserDto;
+import codesquad.dto.user.UserDto;
+import codesquad.dto.user.UserUpdateRequestDto;
import codesquad.entity.UserEntity;
+import codesquad.mapper.UserMapper;
import codesquad.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -39,7 +38,6 @@ public String registerUser(UserDto userDto) {
@GetMapping()
public String getUserList(Model model) {
- System.out.println("userService.findUsers().get(0) = " + userService.findUsers().get(0));
List<UserDto> users = userService.findUsers().stream()
.map(userEntity -> modelMapper.map(userEntity, UserDto.class)).collect(Collectors.toList());
model.addAttribute("users", users);
@@ -57,4 +55,15 @@ public String getUserProfile(@PathVariable String userId, Model model) {
return "user/profile";
}
+
+ @GetMapping("/{userId}/form")
+ public String getProfileEditForm() {
+ return "user/update_form";
+ }
+
+ @PutMapping("/{userId}/update")
+ public String updateUserProfile(@PathVariable("userId") String userId, UserUpdateRequestDto requestDto) {
+ userService.updateUser(userId, UserMapper.dtoToEntity(requestDto));
+ return "redirect:/users";
+ }
} | Java | ์
๋ฐ์ดํธ์๋ ๋ณดํต PUT๊ณผ PATCH๊ฐ ์ฌ์ฉ๋ฉ๋๋ค. ์ด ๋์ ์ฐจ์ด๋ ๋ฌด์์ผ๊น์? |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ฐ์ ์์กด์ฑ์ ์ฃผ์
ํ์ฌ ์ฝ๋/๊ฐ์ฒด ๊ฐ์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ธฐ ์ํด Service์ Repository๋ ์๋ฐ ์ฝ๋๋ก ์ง์ ์คํ๋ง ๋น์ ๋ฑ๋กํ์์ต๋๋ค. ์ด๋ ๊ฐ๋ฐ์ ์งํํ๋ค Repository๋ฅผ ๋ณ๊ฒฝํด์ผํ๋ ์ํฉ์ผ ๋, Config์ ๋ฑ๋ก๋ Repository Bean๋ง ์์ ํ๋ฉด ๋๊ธฐ ๋๋ฌธ์
๋๋ค.
๊ทธ๋ผ Controller์ ์ญํ ์ ์๊ฐํด๋ณด๊ฒ ์ต๋๋ค.
์ปจํธ๋กค๋ฌ๋ View์ Service๋ฅผ ์ด์ด์ฃผ๋ ์ญํ ๋ง ํ๊ณ ๋น์ฆ๋์ค ๋ก์ง์ ๊ฐ์ง๊ณ ์์ง ์์ต๋๋ค. ๋ฐ๋ผ์ Repository๊ฐ ๋ณ๊ฒฝ๋๊ฑฐ๋ ๋น์ฆ๋์ค ๋ก์ง์ด ๋ณ๊ฒฝ๋์ด๋ Controller๋ ๋ณ๊ฒฝ๋์ง ์์ผ๋ฏ๋ก Config์์ ๋ฑ๋กํ์ง ์์์ต๋๋ค.
ref: https://inf.run/SZEa -> ๋ง ๋ค๋ฌ๋๋ฐ ๋์ ๋ฐ์์ต๋๋ค:) |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | AppConfig์์ @ComponentScan ๊ฐ์ Spring Bean์ ์๋์ผ๋ก ๊ฐ์ ธ์ค๊ธฐ ์ํ ์ด๋
ธํ
์ด์
์ ์ฌ์ฉํ์ง ์์๊ธฐ์ ์ง์ ๋น์ ๊ฐ์ ธ์์ต๋๋ค!
(์ฌ์ค ์ง๋ฌธ ์๋๋ฅผ ์ ๋๋ก ์ดํดํ์ง ๋ชปํ์ต๋๋ค. ๋ถ์ฐ ์ค๋ช
ํด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค!) |
@@ -1,18 +1,17 @@
package codesquad.controller;
import codesquad.AppConfig;
-import codesquad.dto.UserDto;
+import codesquad.dto.user.UserDto;
+import codesquad.dto.user.UserUpdateRequestDto;
import codesquad.entity.UserEntity;
+import codesquad.mapper.UserMapper;
import codesquad.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -39,7 +38,6 @@ public String registerUser(UserDto userDto) {
@GetMapping()
public String getUserList(Model model) {
- System.out.println("userService.findUsers().get(0) = " + userService.findUsers().get(0));
List<UserDto> users = userService.findUsers().stream()
.map(userEntity -> modelMapper.map(userEntity, UserDto.class)).collect(Collectors.toList());
model.addAttribute("users", users);
@@ -57,4 +55,15 @@ public String getUserProfile(@PathVariable String userId, Model model) {
return "user/profile";
}
+
+ @GetMapping("/{userId}/form")
+ public String getProfileEditForm() {
+ return "user/update_form";
+ }
+
+ @PutMapping("/{userId}/update")
+ public String updateUserProfile(@PathVariable("userId") String userId, UserUpdateRequestDto requestDto) {
+ userService.updateUser(userId, UserMapper.dtoToEntity(requestDto));
+ return "redirect:/users";
+ }
} | Java | `PUT`์ ์์ ์ ์ฒด๋ฅผ ๊ต์ฒดํ์ฌ, ์์์ ๋ชจ๋ ํ๋๊ฐ ํ์ํ๊ณ
`PATCH`๋ ์์์ ๋ถ๋ถ๋ง ๊ต์ฒดํ์ฌ, ์์์ ์ผ๋ถ ํ๋๋ง ์์ด๋ ๋ฉ๋๋ค.
GOOD
```
PUT /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
```
BAD
```
PUT /userId/1
{
"userId" : "mywnajsldkf",
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : null
}
```
GOOD
```
PATCH /userId/1
{
"userId" : "mywnajsldkf",
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
``` |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | dto <-> entity ์ฌ์ด์ ๋งตํ์ ์ด๋์ ํด์ผํ ์ง ๊ณ ๋ฏผ์ ํ๋๋ฐ์.
DTO๋ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด์ ์ข
์๋์ด์ผ ํ๋ค๊ณ ์๊ฐํด ๋งตํ์ ๊ด๋ จ๋ ๊ฒ์ ๋ชจ๋ ์ปจํธ๋กค๋ฌ์์ ๋๋ ค๊ณ ํ์์ต๋๋ค.
update()์ ๋ํ ๋ถ๋ถ์ ํผ๋๋ฐฑ์ ๋ณด๊ณ ๋ค์ ๋ณด๋, ์๋ก์ด userEntity๋ฅผ ์์ฑํ๋ register์ ๋ค๋ฅด๊ฒ ๊ธฐ์กด์ ์๋ userEntity๋ฅผ ์์ ํ๋ ๊ฒ์ด๋ค๋ณด๋ ๊ฐ์ updateํ๋ ๋ฐฉํฅ์ ์ง์คํ์ต๋๋ค. ๊ทธ๋ฌ๋ค๋ณด๋ DTO -> Entity๋ ์๋กญ๊ฒ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค๋ ์๊ฐ์ ๊ฑฐ์น์ง ์์๋ค์.๐
๋ค์๋ณด๋ register() ์ฒ๋ผ controller์์ entity๋ก ๋ฐ๊ฟ์ ๋๊ฒจ์ง๊ณ entity์ ์๋ ๊ฐ๋ค์ repository์์ ๊บผ๋ด์ด ์
๋ฐ์ดํธํ๋ ๋ฐฉ์์ผ๋ก ์์ ํ๊ณ ์ถ์๋ฐ @saint6839 ๋์ ์๊ฐ์ ์ด๋ ์ธ์?
+)
dto <-> entity๋ ์ด๋์์ ๊ดํ ๋ถ๋ถ์...
์ด์ ๋ฆฌ๋ทฐ์์๋ ์ง๋ฌธ๋๋ฆฌ๊ธฐ๋ ํ๊ณ , ๋ค์ํ [ํ ๋ก ๊ธ 1](https://okky.kr/articles/708060), [ํ ๋ก ๊ธ 2](https://tecoble.techcourse.co.kr/post/2021-04-25-dto-layer-scope/) ๋ฑ์ ์ฐพ์๋ณด๊ธฐ๋ ํ๋๋ฐ์~
์ค์ค๋ก ๋ด๋ฆฐ ์์
๋ฐฉํฅ์ฑ์ **repository๊น์ง ๋ค์ด๊ฐ์ง ๋ง ๊ฒ, ํ๋ก์ ํธ ๋ด์ ์ผ๊ด์ฑ์ ์ ์งํ ๊ฒ, (๋ฌด์๋ณด๋ค) ๊ฐ์ด ํ๋ ์ฌ๋์ด๋ ๋ง์ถ ๊ฒ** ์
๋๋ค.๐
์ด ๋ถ๋ถ์ ๋ํด ์์ฝ๋์ ์๊ฐ๋ ๋ค์ด๋ณด๊ณ ์ถ๋ค์~ |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
๋ค! ํ๋ฒ ๊ณ ๋ฏผํด๋ณด๊ฒ ์ต๋๋ค~ ํน์ ์์ฝ๋์ด ๋ง์ํ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ถ๋ถ์ view(controller)์ ์ฃผ๊ณ ๋ฐ๋๋ค๋ ๋ง์์ด์ค๊น์? |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > Entity, Model, Dto, VO์ ์ฐจ์ด์ ๋ํด ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์กฐ์ธ ๊ฐ์ฌํฉ๋๋ค~
๊ณต๋ถํ๋ฉด์ ๊ถ๊ธํ ์ ์ด ์์ต๋๋ค.
์์ง VO๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๊ฐ ์๋ฟ์ง ์๋๋ฐ์~
DTO์ฒ๋ผ ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๋ ์ํฉ์๋ง ์ด๋ค๋ ๊ฒ์ด ์๋,
VO์ ์ ์ฝ์ฌํญ(๋ถ๋ณ์ฑ, ๋๋ฑ์ฑ, ์๊ฐ ์ ํจ์ฑ)์ด ์๊ธฐ์
๊ฐ์ฒด ์์ฑ ์ VO ๊ทธ ์์ฒด๊ฐ ์ ์ฝ์ฌํญ์ด ๋๊ฑฐ๋ ์ธ์คํด์ค๊ฐ ์ ํด์ ธ ์๋ ๊ฒฝ์ฐ ๋ฏธ๋ฆฌ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ ๋ฑ
VO์ ํน์ง์ผ๋ก ์ป์ ์ ์๋ ์ด์ ์ด ์๊ธฐ์ ์ฌ์ฉํ๋ค๊ณ ์ดํดํด๋ ๋ ๊น์?
์๋๋ถํฐ๋ ์ ๋ฆฌํ ๋ด์ฉ์
๋๋ค.
# Entity
- DB์ ํ
์ด๋ธ๊ณผ ๋งคํ๋๋ ๊ฐ์ฒด๋ก, `id`๋ฅผ ํตํด ๊ฐ๊ฐ์ Entity๋ฅผ ๊ตฌ๋ถํฉ๋๋ค.
- ๋ก์ง์ ๊ฐ์ง ์ ์์ต๋๋ค.
```java
public class User {
private Long id;
private String name;
private String email;
@Builder
public User(String name, String email) {
this.name = name;
this.email = email;
}
public User update(String name, String email) {
this.name = name;
this.email = email;
return this;
}
}
```
# DTO
- Data Transfer Object, ๋ง ๊ทธ๋๋ก ๊ณ์ธต(Layer: Service, Controller, Repository)๊ฐ ๋ฐ์ดํฐ ๊ตํ์ ์ํด ์ฌ์ฉํ๋ ๊ฐ์ฒด์
๋๋ค.
- ๋ก์ง์ ๊ฐ์ง ์๊ณ , getter/setter ๋ฉ์๋๋ง ๊ฐ์ต๋๋ค.
```java
class UserDto {
private int name;
private int email;
public UserDto(int name, int email){
this.name = name;
this.email = email;
}
public int getName() {
return name;
}
public int setName(int name) {
this.name = name;
}
...
}
```
# VO
Value Object์ ์ฝ์๋ก ๊ฐ ๊ทธ ์์ฒด์
๋๋ค.
์ฌ์ฉ ์, ์ผ๋ํด์ผํ ๋ถ๋ถ์ **1. equals & hash code ๋ฉ์๋๋ฅผ ์ฌ์ ์ํด์ผ ํ๋ค. 2. ์์ ์(setter)๊ฐ ์๋ ๋ถ๋ณ ๊ฐ์ฒด์ฌ์ผ ํ๋ค.** ์
๋๋ค.
1๋ฒ์ ๋ํด ์ข ๋ ์ด์ผ๊ธฐํ์๋ฉด ๋๋ฑ์ฑ์ ๊ฐ๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๊ฐ ์ค์ ๋ค๋ฅธ ๊ฐ์ฒด์ด๋๋ผ๋, ๋
ผ๋ฆฌ์ ์ผ๋ก ๊ฐ์ด ๊ฐ๋ค๋ฉด(๋์ ์์ดํฐ 13๋ฏธ๋, ๋์ ํด๋ํฐ 13๋ฏธ๋ ์๋ก ๋ค๋ฅด์ง๋ง ๊ฐ์) ๊ฐ๋ค๊ณ ๋งํฉ๋๋ค.
2๋ฒ์ setter๊ฐ ์์ด์ ๊ฐ ๋ณ๊ฒฝ ๊ฑฑ์ ์ด ์์ด DB์์ ๊ฐ์ ๊ฐ์ ธ์ ๋ฐ์ดํฐ๋ฅผ VO์ ๋ด์ผ๋ฉด ํญ์ VO์ ๊ฐ์ ์๋ณธ์ผ๋ก ์ ๋ขฐํ ์ ์์ต๋๋ค.
+) ์ ์ ๋ฆฌ๋ ๊ธ๋ ์ฒจ๋ถํฉ๋๋ค.
* https://tecoble.techcourse.co.kr/post/2020-06-11-value-object/
* https://hudi.blog/value-object/
# Model
Model์ ๋น์ฆ๋์ค ๋ก์ง์์ ๋ฐ์ํ๋ ๊ฐ์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค.
DB์ ๊ฐ์ ๋ฃ๊ฑฐ๋ ๊ฐ์ ธ์ค๋ ๊ฒ์ด ์๋ ์ค๊ฐ์ ์ฐ์ฐ์ด ์ด๋ฃจ์ด์ง ๋ ํ๋๋ค์ ๋ชจ๋ธ์ ๋ด์ ๊ด๋ฆฌํ๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์์กด์ฑ ์ฃผ์
์ ์คํ๋ง์ด ์์์ ํด์ฃผ๋ ๋ถ๋ถ์
๋๋ค ~
์คํ๋ง ๋ถํธ์ DI ๋ฐฉ์์ ๋ํด ์์๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | ์คํ๋ง๋ถํธ์์ ์์ฑ์ ์ฃผ์
์ ํ๋ ๋ฐฉ๋ฒ์ ๋ํด ๊ฒ์ํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,45 @@
+package codesquad.mapper;
+
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class QuestionMapper {
+
+ public static QuestionEntity dtoToEntity(QuestionRequestDto questionRequestDto) {
+ if (questionRequestDto == null){
+ return null;
+ }
+
+ QuestionEntity.QuestionEntityBuilder questionEntity = QuestionEntity.builder();
+
+ questionEntity.writer(questionRequestDto.getWriter());
+ questionEntity.title(questionRequestDto.getTitle());
+ questionEntity.contents(questionRequestDto.getContents());
+
+ return questionEntity.build();
+ }
+
+ public static QuestionResponseDto entityToDto(QuestionEntity questionEntity) {
+ if (questionEntity == null) {
+ return null;
+ }
+
+ QuestionResponseDto.QuestionResponseDtoBuilder questionResponseDto = QuestionResponseDto.builder();
+
+ questionResponseDto.writer(questionEntity.getWriter());
+ questionResponseDto.title(questionEntity.getTitle());
+ questionResponseDto.contents(questionEntity.getContents());
+ questionResponseDto.date(localTimeToString(questionEntity.getCreatedDate()));
+
+ return questionResponseDto.build();
+ }
+
+ public static String localTimeToString(LocalDateTime localDateTime) {
+ String stringLocalTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
+ return stringLocalTime;
+ }
+} | Java | ๋ณ์๋ private ์ผ๋ก ์ ์ธํ๊ณ setter ๋ฅผ ์ฌ์ฉํด์ ์ ๊ทผํ๋๊ฒ ์๋ฐ์ ์ผ๋ฐ์ ์ธ ์์น์
๋๋ค ~ |
@@ -0,0 +1,24 @@
+package codesquad.entity;
+
+import lombok.*;
+
+@Setter
+@Getter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class QuestionEntity extends BaseTimeEntity {
+
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionEntity{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | Entity ๋ผ๋ postfix ๋ฅผ ๋ถ์ด์ง ์์๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค ~ |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ ์ด์ ์ญ์ (IoC)๊ฐ ๋ฌด์์ธ์ง๋ ํ ๋ฒ ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > > ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
>
> ๋ค! ํ๋ฒ ๊ณ ๋ฏผํด๋ณด๊ฒ ์ต๋๋ค~ ํน์ ์์ฝ๋์ด ๋ง์ํ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ถ๋ถ์ view(controller)์ ์ฃผ๊ณ ๋ฐ๋๋ค๋ ๋ง์์ด์ค๊น์?
์ปจํธ๋กค๋ฌ ๋ฟ ์๋๋ผ ๋ ์ด์ด๋ ์ํคํ
์ณ์์ ๊ฐ ๊ณ์ธต๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค! |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | > dto <-> entity ์ฌ์ด์ ๋งตํ์ ์ด๋์ ํด์ผํ ์ง ๊ณ ๋ฏผ์ ํ๋๋ฐ์. DTO๋ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด์ ์ข
์๋์ด์ผ ํ๋ค๊ณ ์๊ฐํด ๋งตํ์ ๊ด๋ จ๋ ๊ฒ์ ๋ชจ๋ ์ปจํธ๋กค๋ฌ์์ ๋๋ ค๊ณ ํ์์ต๋๋ค.
>
> update()์ ๋ํ ๋ถ๋ถ์ ํผ๋๋ฐฑ์ ๋ณด๊ณ ๋ค์ ๋ณด๋, ์๋ก์ด userEntity๋ฅผ ์์ฑํ๋ register์ ๋ค๋ฅด๊ฒ ๊ธฐ์กด์ ์๋ userEntity๋ฅผ ์์ ํ๋ ๊ฒ์ด๋ค๋ณด๋ ๊ฐ์ updateํ๋ ๋ฐฉํฅ์ ์ง์คํ์ต๋๋ค. ๊ทธ๋ฌ๋ค๋ณด๋ DTO -> Entity๋ ์๋กญ๊ฒ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค๋ ์๊ฐ์ ๊ฑฐ์น์ง ์์๋ค์.๐
>
> ๋ค์๋ณด๋ register() ์ฒ๋ผ controller์์ entity๋ก ๋ฐ๊ฟ์ ๋๊ฒจ์ง๊ณ entity์ ์๋ ๊ฐ๋ค์ repository์์ ๊บผ๋ด์ด ์
๋ฐ์ดํธํ๋ ๋ฐฉ์์ผ๋ก ์์ ํ๊ณ ์ถ์๋ฐ @saint6839 ๋์ ์๊ฐ์ ์ด๋ ์ธ์?
>
> +) dto <-> entity๋ ์ด๋์์ ๊ดํ ๋ถ๋ถ์... ์ด์ ๋ฆฌ๋ทฐ์์๋ ์ง๋ฌธ๋๋ฆฌ๊ธฐ๋ ํ๊ณ , ๋ค์ํ [ํ ๋ก ๊ธ 1](https://okky.kr/articles/708060), [ํ ๋ก ๊ธ 2](https://tecoble.techcourse.co.kr/post/2021-04-25-dto-layer-scope/) ๋ฑ์ ์ฐพ์๋ณด๊ธฐ๋ ํ๋๋ฐ์~ ์ค์ค๋ก ๋ด๋ฆฐ ์์
๋ฐฉํฅ์ฑ์ **repository๊น์ง ๋ค์ด๊ฐ์ง ๋ง ๊ฒ, ํ๋ก์ ํธ ๋ด์ ์ผ๊ด์ฑ์ ์ ์งํ ๊ฒ, (๋ฌด์๋ณด๋ค) ๊ฐ์ด ํ๋ ์ฌ๋์ด๋ ๋ง์ถ ๊ฒ** ์
๋๋ค.๐ ์ด ๋ถ๋ถ์ ๋ํด ์์ฝ๋์ ์๊ฐ๋ ๋ค์ด๋ณด๊ณ ์ถ๋ค์~
๊ฐ์ธ์ ์ผ๋ก๋ Entity <-> Dto ๋ณํ ์ฑ
์์ ์๋น์ค ๊ณ์ธต์ ๋ถ์ฌํ๋๊ฒ์ ์ ํธํ๋ ํธ์
๋๋ค. ์ปจํธ๋กค๋ฌ ๊ณ์ธต์ ๋ฉ์๋ ๋ค์ด๋ฐ์ ๋น์ฆ๋์ค ์ฉ์ด๋ฅผ, ์๋น์ค ๊ณ์ธต์ ๋ฉ์๋ ๋ค์ด๋ฐ์ ๊ฐ๋ฐ ์ฉ์ด๋ฅผ ์ฌ์ฉํ๋ค๋ ์์์ ๋ณธ ์ ์ด ์์ต๋๋ค(์๋ง๋ ๊น์ํ๋).
๊ทธ๋งํผ ์ปจํธ๋กค๋ฌ ๊ณ์ธต์ ๊ฐ๋ฐ์ ์ธ ์์๋ณด๋ค๋ ์ฌ์ฉ์๋ก๋ถํฐ ๋ค์ด์จ ์์ฒญ์ ์ฒ๋ฆฌํ๋๋ฐ ์ฑ
์์ด ์ง์ค๋์ด์ผ ํ๋ ๊ณ์ธต์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค. ์ด๋ฌํ ์ด์ ๋๋ฌธ์ ์ ๋ ์๋น์ค ๊ณ์ธต์์ Entity์ Dto ๋ณํ์ ๋ค๋ฃจ๋ ๊ฒ์ ์ ํธํ๋ ํธ์
๋๋ค.
์ ๋ต์ ์๋ ๊ฒ ๊ฐ์ง๋ง ๋ณธ์ธ์ด ์ ํธํ๋ ๋ฐฉ๋ฒ์ด ์๋ค๋ฉด, ๊ทธ ๊ทผ๊ฑฐ์ ๋ํด์ ์๊ฐํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์(๋จ์ํ ๋๋ถ๋ถ ์ฌ๋๋ค์ด ๊ทธ๋ ๋ค๊ณ ํด์๊ฐ ์๋..) |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | @saint6839
์ ๋ service(application or usecase), domain ์ ์ธ๋ถ์ ๊ฒ์ผ๋ก๋ถํฐ ๋
๋ฆฝ์ ์ด๊ณ ์ต๋ํ ์์ํ ์๋ต์ ๋ณด๋ด์ผ ์ฌ์ฉ์ฑ์ด ์ข์์ง๋ค๊ณ ์๊ฐํฉ๋๋ค.
๋ฐ๋ผ์ service ๋ ์ด์ด์์๋ ์ธ๋ถ ์๊ตฌ์ฌํญ์ ํด๋นํ๋ ๋ฐ์ดํฐ ๊ตฌ์กฐ์ธ dto ๋ณํ์ ์ง์ํ๋๋ก ๊ฐ๋ฐํ๋ ํธ์
๋๋ค. ์ค์ ์๋น์ค์์ ๊ฐ๋ฐํ๋ค๋ณด๋ฉด 1controller - 1service ๊ฐ ์๋๋ผ n๊ฐ์ controller ์ผ์ด์ค์์ ์๋ก ๋ค๋ฅธ ๋ชฉ์ ์ผ๋ก 1service ๋ฅผ ํธ์ถํ๋ ์ผ์ด์ค๋ ์์ผ๋ ๊ฐ์๊ฐ ํ์ํ ๋ฐ์ดํฐ๊ฐ ๋ค๋ฅผ ๊ฒฝ์ฐ, dto ๊ฐ ๊ณตํต์ผ๋ก ์ฌ์ฉ๋์ด์ ๋ฑ๋ฑํด์ง๊ณ ๋ฌด์์ด ์ด๋ค ์ผ์ด์ค์ ๊ผญ ํ์ํ ๋ฐ์ดํฐ์ธ์ง ๊ตฌ๋ถํ๊ธฐ๋ ์ด๋ ค์์ง๋๋ค. ๊ทธ๋ฆฌ๊ณ ์๋ก์ ๋ณ๊ฒฝ์ ์ํฅ๋ ๋ง์ด ๋ฐ๊ตฌ์.
๊ทธ๋ ๋ค๊ณ entity ๋ฅผ ์์ํ๊ฒ ๊ทธ๋๋ก ๋ฐํํ๊ฒ ๋๋ฉด OSIV ๊ณ ๋ฏผ์ ๋น ์ง๊ฒ ๋ฉ๋๋ค. ๊ทธ๋์ ์ข ๋ณต์กํ ์ฝ๋์์๋ Service layer DTO ๋ฅผ ๋ฐ๋ก ์ ์ํด์ ๊ทธ๊ฒ์ผ๋ก ๋ณํํ์ฌ ๊ณตํต์ ์ผ๋ก ๋ฐํํด์ฃผ๊ณ , controller ์์๋ service dto ๋ฅผ ๋ฐ์์ ํ์ํ ๋ถ๋ถ๋ค์ ๋ค์ controller layer dto ๋ก ๋ณํํด์ ์ฌ์ฉํ๊ธฐ๋ ํฉ๋๋ค. ๋๋ฌด ํด๋์ค๊ฐ ๋ง์์ง๊ณ ์คํ๋ ค ๋ณต์กํด์ง๋ค๋ ๊ฒฝํฅ์ด ์์ด์ ์ด๋ฐ ํ ์ดํ์ ์์๋ ์ถ์ฒํ์ง ์์ง๋ง ์ด๋ฐ ๋ถ๋ถ๋ ์๊ตฌ๋ ํ๊ณ ๋๊ธฐ์
๋ ์ข์ ๊ฒ ๊ฐ์์ ๊ณต์ ๋๋ฆฝ๋๋ค ~
์ด ์ผ์ด์ค์์๋ ์์ ๊ท๋ชจ์ด๋ ๊ทธ๋ฅ service layer ์์ dto ๋ณํ์ ํ๋ ๊ฒ์ ์ถ์ฒํฉ๋๋ค ~ |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | ์์ง 1๋จ๊ณ๋ผ์ ์ด๋ฐ ๋ถ๋ถ์ ๋ํ ์ฝ๋ฉํธ๋ ์ข ๋ ์น์ ํ ์ค๋ช
ํด์ฃผ์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,24 @@
+package codesquad.entity;
+
+import lombok.*;
+
+@Setter
+@Getter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class QuestionEntity extends BaseTimeEntity {
+
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionEntity{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | @hyukjin-lee class๋ช
๋ง์ํ์ค๊น์?? |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | > applicationcontext๋ก๋ถํฐ ์ง์ ๋น์ ๊ฐ์ ธ์ค์
์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค!
questionService๋ ๋ค์๊ณผ ๊ฐ์ด ์์ฑ์๋ฅผ ํตํด ์ฃผ์
๋์์ต๋๋ค.
**AppConfig**
```java
@Bean
public QuestionService questionService() {
return new QuestionServiceImpl(questionRepository());
}
@Bean
public QuestionRepository questionRepository() {
return new QuestionRepositoryImpl();
}
```
QuestionServiceImpl
```java
public QuestionServiceImpl(QuestionRepository questionRepository) {
this.questionRepository = questionRepository;
}
```
์์ฑ์ ์ฃผ์
์ ํ ๊ฒฝ์ฐ, `getBean()`์ ํตํด ๊ฐ์ฒด๋ฅผ ์ป์ด์์ ์ฌ์ฉํด์ผ ํฉ๋๋ค. |
@@ -0,0 +1,45 @@
+package codesquad.mapper;
+
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class QuestionMapper {
+
+ public static QuestionEntity dtoToEntity(QuestionRequestDto questionRequestDto) {
+ if (questionRequestDto == null){
+ return null;
+ }
+
+ QuestionEntity.QuestionEntityBuilder questionEntity = QuestionEntity.builder();
+
+ questionEntity.writer(questionRequestDto.getWriter());
+ questionEntity.title(questionRequestDto.getTitle());
+ questionEntity.contents(questionRequestDto.getContents());
+
+ return questionEntity.build();
+ }
+
+ public static QuestionResponseDto entityToDto(QuestionEntity questionEntity) {
+ if (questionEntity == null) {
+ return null;
+ }
+
+ QuestionResponseDto.QuestionResponseDtoBuilder questionResponseDto = QuestionResponseDto.builder();
+
+ questionResponseDto.writer(questionEntity.getWriter());
+ questionResponseDto.title(questionEntity.getTitle());
+ questionResponseDto.contents(questionEntity.getContents());
+ questionResponseDto.date(localTimeToString(questionEntity.getCreatedDate()));
+
+ return questionResponseDto.build();
+ }
+
+ public static String localTimeToString(LocalDateTime localDateTime) {
+ String stringLocalTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
+ return stringLocalTime;
+ }
+} | Java | @hyukjin-lee ๋ต!!! ๊ธฐ์ตํ๊ฒ ์ต๋๋ค. ์ด๋ฒ์๋ ๋ณ๊ฒฝ ๊ฐ๋ฅ์ฑ์ ์ด์ด๋๋ setter ์ฌ์ฉ์ ์ง์ํ๊ณ , ํ์ํ ๋ฐ์ดํฐ๋ง ์ค์ ํ๊ณ ์ถ์ด Builder ํจํด์ ์ฌ์ฉํด๋ณด์์ต๋๋ค~ |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | Question์ ๋ํ Exception์ customizing ํ ์ด์ ์
๋๋ค
QuestionEditException์ ํด๋น ์ง๋ฌธ์๊ฐ ์๋๊ธฐ ๋๋ฌธ์ ์ญ์ ํ ์ ์๋ ๊ฒฝ์ฐ,
QuestionDeleteException์ ๋ค๋ฅธ User์ ๋ต๊ธ์ด ์กด์ฌํ์ฌ ์ญ์ ํ ์ ์๋ ๊ฒฝ์ฐ์
๋๋ค
์ฒ์์๋ boolean์ผ๋ก ์ฒ๋ฆฌํ๋ ค๋ค๊ฐ ๋ ๊ฐ์ง ๊ฒฝ์ฐ๊ฐ ์๊ฒ ๋์ด(=๋ ๊ฐ์ง view)
exception์ ๋ง๋ค์์ต๋๋ค |
@@ -1,10 +1,15 @@
package codesquad.user;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
import javax.persistence.*;
import java.util.Objects;
@Entity
+@NoArgsConstructor
+@Getter
public class User {
@Id
@@ -20,43 +25,14 @@ public class User {
private String email;
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getPassword() {
- return password;
+ User(SignUpUserDto signUpUserDto) {
+ userId = signUpUserDto.getUserId();
+ password = signUpUserDto.getPassword();
+ name = signUpUserDto.getName();
+ email = signUpUserDto.getEmail();
}
- public void setPassword(String password) {
- this.password = password;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public Long getId() {
- return id;
- }
-
- public void update(User user) {
+ public void update(SignUpUserDto user) {
if (equalsPassword(user.getPassword())) {
name = user.getName();
email = user.getEmail();
@@ -67,6 +43,10 @@ public boolean equalsPassword(String password) {
return this.password.equals(password);
}
+ public boolean equalsPassword(LoginUserDto loginUserDto) {
+ return password.equals(loginUserDto.getPassword());
+ }
+
public boolean equalsId(Long id) {
return this.id.equals(id);
}
@@ -76,15 +56,11 @@ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
- return Objects.equals(getId(), user.getId()) &&
- Objects.equals(getUserId(), user.getUserId()) &&
- Objects.equals(getPassword(), user.getPassword()) &&
- Objects.equals(getName(), user.getName()) &&
- Objects.equals(getEmail(), user.getEmail());
+ return Objects.equals(getId(), user.getId());
}
@Override
public int hashCode() {
- return Objects.hash(getId(), getUserId(), getPassword(), getName(), getEmail());
+ return Objects.hash(getId());
}
} | Java | ์ ๋ฒ์ ๋ง์ํด์ฃผ์ equals์ ๋ํ ๋ฆฌ๋ทฐ ์๊ฐํด๋ดค์ต๋๋ค
๋ง์๋๋ก ๊ด๊ณํ DB์์๋ "์๋ณ์(id)" ๊ฐ ๊ณ ์ ํ ๊ฐ์ผ๋ก, ํด๋น ์๋ณ์๊ฐ ๋์ผํ๋ค๋ฉด ๊ฐ์ ๋ฐ์ดํฐ๋ผ๊ณ ์ธ์ํ๋๋ฐ equals๋ฅผ overridingํ๋ค๋ฉด ๋ชจ๋ ํ๋์ ๊ฐ์ด ๋์ผํด์ผ ๊ฐ์ ๊ฐ์ฒด๋ผ๊ณ ํ๋จํฉ๋๋ค
equals๋ฅผ ๊ตณ์ด overridingํ ํ์์๋ ์ํฉ์์ overriding์ ํ๋ค๋ฉด HashSet์ด๋ HashMap์ ์ํฅ์ ์ฃผ์ด ์์์น ๋ชปํ ์ํฉ์ด ๋ฐ์ํ ์๋ ์์ต๋๋ค
๋ฐ๋ผ์ User๋ฅผ ์๋ณํ๊ธฐ ์ํด์๋ "id"๋ก ์ถฉ๋ถํ๊ธฐ ๋๋ฌธ์ equals๋ฅผ overridingํ์ง ์์๋๋๋ค ๋ผ๋ ์๊ฐ์
๋๋ค |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | canDeleteQuestion์ ์ง๋ฌธ์ ์ญ์ ํ ์ ์๋์ง ํ๋จํ๋ ๋ฉ์๋์
๋๋ค
- ๋ต๊ธ์ด ์์ ๊ฒฝ์ฐ ์ญ์ ๊ฐ๋ฅ
- ๋ต๊ธ์ด ์์ผ๋ ์์ฑ์ ๋ชจ๋ ์ง๋ฌธ ์์ฑ์์ ๊ฐ์ ๊ฒฝ์ฐ ์ญ์ ๊ฐ๋ฅ
ํด๋น ๋ฉ์๋๋ Question์ด ์ญ์ ๋ ์ ์์ด?๋ผ๊ณ ๋ฌป๊ณ , Question์ด ์ญ์ ๋ ์ ์์ด/์์ด๋ฅผ ํ๋จํฉ๋๋ค
๊ทธ๋์ ์ ๋ ์ด ๋ถ๋ถ์ด Question์๊ฒ ๋ฌผ์ด๋ณด๊ณ Question์ด ๊ฒฐ์ ํ๋ ๊ฒ์ด๋ผ๋ ์๊ฐ์ด ๋ค์ด Question ํด๋์ค์ ์์ด์ผํ ๊น๋ผ๋ ์๊ฐ์ ํ์ต๋๋ค.
ํ์ง๋ง ์ด ๋
ผ๋ฆฌ๋ผ๋ฉด ์๋ isQuestionMatchUser(์ง๋ฌธ ์์ฑ์์ ๋ก๊ทธ์ธ ๋ User๊ฐ ๊ฐ์์ง ํ๋จํ๋ ๋ฉ์๋)๋ Question์ ์์ด์ผํ์ง ์์๊น๋ผ๋ ์๊ฐ์ ํ์ง๋ง, ๊ทธ๋ ๊ฒ ๋๋ฉด Question ํด๋์ค๊ฐ ๋๋ฌด ๋ฌด๊ฑฐ์์ง์ง ์์๊น๋ผ๋ ์๊ฐ๋ ๋ค์์ต๋๋ค
๋ฆฌ๋ทฐ์ด๋์ ์ด๋ป๊ฒ ์๊ฐํ์๋์ง ๊ถ๊ธํด์ comment ๋จ๊ฒจ๋ด
๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | Answer์ ๋น์ฆ๋์ค ๋ก์ง์ ๋ด๋นํ๋ AnswerService์์ Question๊ด๋ จ ๋ฐ์ดํฐ๊ฐ ํ์ํ ๋ QuestionRepository๋ฅผ ์ง์ ์ฐธ์กฐํ๋ ๋ฐฉ๋ฒ๋ ์์ง๋ง, QuestionService๋ฅผ ํตํด ์ฐธ์กฐํ๋๋ก ํ ์๋ ์์ ๊ฑฐ ๊ฐ์๋ฐ ์ด๋ค ์ฐจ์ด๊ฐ ์์๊น์? |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | Answer๋ฅผ db์์ ์กฐํํ๋ ๋ก์ง ๋ค์ ์ธ์
์ ์ ์ฒดํฌ๊ฐ ์ด๋ค์ง๊ณ ์์ต๋๋ค. ๊ฐ์ ํ ์ ์ด ์์ด๋ณด์ด๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,27 @@
+package codesquad.answer;
+
+import codesquad.response.Result;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpSession;
+
+@RestController
+@RequiredArgsConstructor
+@Slf4j
+public class ApiAnswerController {
+
+ private final AnswerService answerService;
+
+ @PostMapping("/questions/{question-id}/answers")
+ public Result<ResponseAnswerDto> create(@PathVariable("question-id") Long questionId, @RequestBody RequestAnswerDto requestAnswerDto, HttpSession session) {
+ return answerService.create(questionId, requestAnswerDto, session);
+ }
+
+ @DeleteMapping("/questions/{question-id}/answers/{answer-id}")
+ public Result<ResponseAnswerDto> remove(@PathVariable("question-id") Long questionId,
+ @PathVariable("answer-id") Long answerId, HttpSession session) {
+ return answerService.remove(questionId, answerId, session);
+ }
+} | Java | ์ด ์์ฒญ์ ์๋ต ์ํ์ฝ๋๋ ์ด๋ป๊ฒ ๋๊ฐ๊น์? |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | 1. Service๊ฐ์ฒด๊ฐ HttpSession๋ฅผ ์์์ผํ ํ์๊ฐ ์์๊น์?
2. ํ์ฌ ์์ฒญ์ ๋ํ ์ธ์
์ ๋ณด๊ฐ ์กด์ฌํ๋์ง ํ๋จํ๋ ๋ฉ์๋๋ก ๋ณด์ด๋๋ฐ, ํ์ฌ ๋ฉ์๋๋ช
์ด ์ค์ ์ญํ ์ ์ถฉ๋ถํ ์ค๋ช
ํ์ง ๋ชปํ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ์ธ์
์ ์ ์ ์ ๋ณด๊ฐ ํฌํจ๋์ผ๋งํ๋ ๋ชจ๋ ๋ฉ์๋์์ ํด๋น ๋ก์ง์ด ์์ฑ๋๊ณ ์๋๋ฐ ์ด๋ป๊ฒ ํ๋ฉด ์ค๋ณต์ ์ค์ผ ์ ์์๊น์? |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ๋ฉ์๋๋ช
์ ๋ณด๊ณ Question์ ๋ํ ๋น์ฆ๋์ค๋ก์ง์ ์ํํ๋ ๊ฐ์ฒด์์ Form๊น์ง ๊ด์ฌํ๋ ๊ฑด๊ฐ๋ผ๋ ์๊ฐ์ด ๋ค์์ต๋๋ค. |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ์ ๋ ์ฝ๋ ์ฌ์ฌ์ฉ์ฑ ์ธก๋ฉด์์ ์๊ฐํด๋ดค์ ๋ ์ด ๋ก์ง์ด ํด๋น Service์์๋ง ์ฌ์ฉ๋๋ ๊ฑฐ๋ผ๋ฉด Question์ด ๋ฌด๊ฑฐ์์ง๋ ๊ฒ์ ๊ณ ๋ คํด์ Service์์ ๋ด๋นํ๋๋ก ๊ตฌํํ ๊ฒ ๊ฐ์ต๋๋ค. ๋ฐ๋ฉด ์ด Service๋ฅผ ๋ฒ์ด๋ ์์ญ์์๋ ์ฌ์ฉ๋๋ ๋ก์ง์ด๋ผ๋ฉด Question์์ ๋ด๋นํ๋ ๊ฒ์ด ์ค๋ณต์ ์ค์ด๋ ๋ฐฉ๋ฒ์ด์ง ์์๊น ์๊ฐํฉ๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ResponseAnswerDto๋ฅผ Result๋ก ํ๋ฒ ๋ ๊ฐ์ธ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ์
จ๋๋ฐ ์ด๋ค ์ด์ ๊ฐ ์์๊น์? |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | ์ด๋ฏธ ๋ณด์
จ์ ์๋ ์์ง๋ง ํ๋ฒ ์ฝ์ด๋ณด์๋ฉด ์ข์ ๊ฑฐ ๊ฐ์ ๊ณต์ ๋๋ฆฝ๋๋ค!
https://tecoble.techcourse.co.kr/post/2020-08-17-custom-exception/ |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | ์ค ๋ง์ต๋๋ค ์ ๋ ์ฌ์ฉ์ ์ ์ ์์ธ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ ์ ์ฌ๋ ค์ฃผ์ ๋งํฌ๋ฅผ ๋ดค์ต๋๋ค.
๋งํฌ์ ๋ํด์ ๋ณด๋ฉด ๊ตณ์ด ๋๋ ํ์ ์์ด, IllegalArgumentException, IllegalstateException์ ๋ฐ๋ผ ๋ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์ฌ์ค ์ ์์ง๋ง, ์ด๋๋ ๋ช
์์ ์ผ๋ก ๋ณด์ฌ์ฃผ๋๊ฒ ๋ซ์ง ์์๊น ๋ผ๋ ์๊ฐ์ ํ์ต๋๋ค |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | updateํ๊ธฐ ์ํด์๋ ์กฐ๊ฑด์ด ํ์ํ๋ฐ ์ด ์กฐ๊ฑด์ ๊ฒ์ฆํ๋ ๊ฒ๋ Question์ ๋ํ ๋น์ฆ๋์ค๋ก์ง์ด๋ผ๊ณ ์๊ฐํด์ ์์ฑํ์ต๋๋ค.
ํน์ ๋ฉ์๋๋ช
์ ์์ ํ๋๊ฒ ์ข์๋ณด์ผ ๊ฒ ๊ฐ์ ๋ง์์ด์ค๊น์~~?? |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ์ค,, ์ด ๋ถ๋ถ์ DB ์ ๊ทผ์ ๋ฌด๊ฑฐ์ด ์์
์ด๊ธฐ ๋๋ฌธ์ ์ธ์
์ ์ฒดํฌํ๊ณ ๋์ DB ์ ๊ทผํ๋ ๊ฒ์ด ์ข์๋ณด์
๋๋ค
๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ์ด ๋ถ๋ถ๋ง ๊ทธ๋ฐ๊ฒ ์๋๋ผ ๋ค๋ฅธ ๊ณณ๋ ๊ทธ๋ ๊ฒ ์์ฑ๋์ด์๋ค์!! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ๋ฏธ์
๋ช
์ธ์์ Result๋ฅผ ๋ฐํํ๋ผ๊ณ ํด์ ์ด๋ ๊ฒ ์์ฑํ์ต๋๋ค! |
@@ -0,0 +1,27 @@
+package codesquad.answer;
+
+import codesquad.response.Result;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpSession;
+
+@RestController
+@RequiredArgsConstructor
+@Slf4j
+public class ApiAnswerController {
+
+ private final AnswerService answerService;
+
+ @PostMapping("/questions/{question-id}/answers")
+ public Result<ResponseAnswerDto> create(@PathVariable("question-id") Long questionId, @RequestBody RequestAnswerDto requestAnswerDto, HttpSession session) {
+ return answerService.create(questionId, requestAnswerDto, session);
+ }
+
+ @DeleteMapping("/questions/{question-id}/answers/{answer-id}")
+ public Result<ResponseAnswerDto> remove(@PathVariable("question-id") Long questionId,
+ @PathVariable("answer-id") Long answerId, HttpSession session) {
+ return answerService.remove(questionId, answerId, session);
+ }
+} | Java | create๋ฉ์๋๋ ์ฑ๊ณต, ์คํจ ์ฌ๋ถ์์ด Result ๋ฅผ ๋ฐํํ๊ธฐ ๋๋ฌธ์ 200 OK๊ฐ ๋๊ฐ ๊ฒ์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค! |
@@ -55,6 +55,7 @@ captures/
.idea/caches
# Keystore files
+keystore.properties
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
@@ -100,3 +101,6 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk
+app/src/main/java/kr/co/connect/boostcamp/livewhere/ui/bookmark/
+app/src/main/java/kr/co/connect/boostcamp/livewhere/ui/search/
+app/src/main/res/layout-v26/ | Unknown | #82 ์์
์ด ์ด๋ค๊ฑด์ง ํ์คํ ๋ฆฌ๊ฐ ์์ด์ ์ ์ถ๊ฐ๋์๋์ง ๋ชจ๋ฅด๊ฒ ๋๋ฐ
1) ๋ณด์๊ณผ ๊ด๋ จ๋์ด ๊ณต์ ๋์ง ์์์ผ ํ๋ ํ์ผ
2) ๊ฐ์ธ๋ณ ํ๊ฒฝ์ค์ ํ์ผ
3) ์บ์ ํ์ผ
4) ์ฐ๋ ๊ธฐ ํ์ผ
๋ฑ์ ์ฌ์ ๊ฐ ์๋๋ผ๋ฉด .gitignore์ ๋ค์ด๊ฐ๋๊ฒ ๋ถ์ ์ ํด ๋ณด์
๋๋ค.
ํด๋น ํด๋๋ฅผ git์์ ์ ๊ฑฐํ๋ ค๋ค ํธ๋ฒ์ ์ด๊ฒ ์๋๊น ์ถ์ธก์ด ๋๋๋ฐ ์ฌ๋ฐ๋ฅด์ง ๋ชปํ ๋ฐฉ๋ฒ์ธ๊ฑฐ ๊ฐ์์. |
@@ -0,0 +1,68 @@
+# ์์ธ ์ด์ด <img width="85" alt="kakaotalk_20190212_204520833" src="https://user-images.githubusercontent.com/22374750/52834626-1efe2080-3126-11e9-92c3-66ac08c1f2c9.png">
+
+
+[](https://insert-koin.io)
+[](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+[](https://github.com/amitshekhariitbhu/RxJava2-Android-Samples)
+[](https://developer.android.com/topic/libraries/architecture/room.html)
+[](https://developer.android.com/topic/libraries/architecture/livedata.html)
+
+booscamp3_Cํ์ ์์ธ์ด์ด repository์
๋๋ค. ํด๋น ํ๋ก์ ํธ๋ MVVM๊ธฐ๋ฐ์ Androidํ๋ก์ ํธ์
๋๋ค.
+์์กด์ฑ ์ฃผ์
์ ์ํด์ koin์ด ์ฌ์ฉ๋์๊ณ , RxJava, Room, LiveData, MotionLayout๋ฑ ๊พธ์คํ ํ์ต์ ์ํด์ ์งํ๋๊ณ ์์ต๋๋ค.
+<hr/>
+
+#### ํ์ ์๊ฐ : ๋ฌธ๋ณํ, ์ ์ง์, ์ต์ค์(๋งํฌ ์ถ๊ฐ ์์ )
+
+์์ธ์ด์ด๋ ์์ธ์ด์ด๋ฅผ ์์ํ๋ ์ฌ๋๋ค์๊ฒ ์ฃผํ์ ๊ดํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ์ดํ๋ฆฌ์ผ์ด์
์
๋๋ค.
+
+<p>ํ์ฌ ์ํํธ์ ๋ํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ๋ค์ํ ์ดํ๋ฆฌ์ผ์ด์
์ด ์กด์ฌํ์ง๋ง, ์๋์ ์ผ๋ก ์ฃผํ์ ๊ด๋ จ๋ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ์ดํ๋ฆฌ์ผ์ด์
์ ๋ถ์กฑํฉ๋๋ค.
+๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์ด๋ฌํ ๋ถ์กฑํ ์ ๋ณด๋ฅผ ์์ธ์ด์ด๋ผ๋ ์ดํ๋ฆฌ์ผ์ด์
์ ํตํด์ ์ฃผํ์ ๊ด๋ จ๋ ์ /์์ธ, ์ฃผ๋ณ ์ง์ญ ์ ๋ณด, ์ฃผํ ์ ๋ณด๋ฑ์ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ค๊ณ ํฉ๋๋ค.</p>
+<hr/>
+
+
+#### ํ๋กํ ํ์
UI: [](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+ํด๋น ํ๋ก์ ํธ๋ ํ์
ํด์ Zeplin์ ์ฌ์ฉํ์ต๋๋ค. ๊ตฌ์ฒด์ ์ธ ๋ด์ฉ์ ํด๋น ๋ฑ์ง๋ฅผ ๋๋ฅด๋ฉด ํ์ธํ ์ ์์ต๋๋ค.<br>
+์ ํฌ๋ Zeplin์ ํตํด์ Style ๊ฐ์ด๋๋ฅผ ์์ฑํ๊ณ , ๊ฐ์ข
xml์ ๊ฐ์ด๋ ๊ธฐ์ค์ ์ ํ์ต๋๋ค.
+
+#### ํจํค์ง ์๊ฐ:
+1. **api**: Retrofit์ ์ฌ์ฉํ๊ธฐ ์ํ interface๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+2. **di**: Koin์ ์ฌ์ฉํ์ฌ ์์กด์ฑ ์ฃผ์
์ ํ๊ณ , ํด๋น ํจํค์ง์ di ๊ด๋ จ ๋ชจ๋์ ๋ง๋ค์์ต๋๋ค.
+3. **firebase**: Firebase์ ๊ด๋ จํ ์ ํธ๋ฆฌํฐ์ฑ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+4. **model**: ์ฃผ์, ๋ถ๋งํฌ, ์ง์ ๋ณด, ๊ฐ๊ฒฉ๋ฑ์ ๊ด๋ จํ ๋ฐ์ดํฐ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+5. **repository**: ViewModel๊ณผ Model์ฌ์ด์ repositoryํจํด์ ์ฌ์ฉํด์ ๊ฐ์ข
๊ฐ์ ๋ฐ์์ค๋ ํด๋์ค๋ฅผ ๋ชจ์๋ ํจํค์ง์
๋๋ค.
+6. **ui**: View์ ํด๋นํ๋ ํด๋์ค๋ค์ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+7. **util**: ํ๋ก์ ํธ๋ด์์ ๊ฐ์ข
์ ํธ๋ฆฌํฐ์ฑ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+
+### [๊ธฐํ์](https://drive.google.com/file/d/1ui4lvMc81kCAki4UVtxirsg0szLEbqD2/view?usp=sharing)
+### [์ผ์ ๊ด๋ฆฌ](https://docs.google.com/spreadsheets/d/1nQlae8ONeO42Rk9Pr0tZFxilmCsfuNRmOOc4p7cFlYY/edit?usp=sharing)
+### [UI๊ธฐํ](https://drive.google.com/file/d/13BLtMr3i-YnhjuDIkYmLRVolUX6OQnIu/view?usp=sharing)
+### [๊ธฐ๋ฅ๋ช
์ธ์](https://docs.google.com/spreadsheets/d/1Y4Xpb8lSP5qQ53e1NPewsZMmYud5io1H1SQxxZZOmY4/edit?usp=sharing)
+
+### [์๋ฒ](https://github.com/seoul42/seoul42-server)
+<hr/>
+
+## 1์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+[DOCS](https://github.com/boostcampth/boostcamp3_C/tree/dev/docs) ๋ฌธ์ ์์
(๊ธฐํ์, ๊ธฐ๋ฅ์ ์์, ํ๋ก์ ํธ ์ผ์ , Api๋ช
์ธ์)
+
+Zeplin[](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+## 2์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+
+Seoul42 API [](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+### 2์ฃผ์ฐจ ํ๊ณ ๋ก
+
+
+์ค์๋ ํ์ผ ์ฌ์
๋ก๋ ํ์
+
+## 3์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+
+### 3์ฃผ์ฐจ ํ๊ณ ๋ก
+
+
+ | Unknown | ์ฐธ๊ณ ํ ์ ์๋ ์ด๋ฏธ์ง์ ๋งํฌ๋ฅผ ์ ๋ฃ์ด์ฃผ์
์
์ด๋ค ํ๋ก์ ํธ์ธ์ง ๋ฐ๋ก ์ ์ ์์์ต๋๋ค.
์ข๋ค์ :+1: |
@@ -1,21 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="kr.co.connect.boostcamp.livewhere">
-
+ xmlns:tools="http://schemas.android.com/tools" package="kr.co.connect.boostcamp.livewhere">
+ <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
+ android:name=".LiveApplication"
+ android:allowBackup="false"
+ android:icon="@drawable/icon_logo"
+ android:roundIcon="@drawable/icon_logo"
android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
- <activity android:name=".MainActivity">
+
+ <uses-library android:name="org.apache.http.legacy"
+ android:required="false"/>
+
+ <meta-data
+ android:name="com.google.android.geo.API_KEY"
+ android:value="@string/key_street_view"/>
+ <activity android:name=".ui.main.SplashActivity"
+ android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
+ <activity android:name=".ui.login.LoginActivity">
+
+ </activity>
+ <activity android:name=".ui.main.HomeActivity">
+ </activity>
+ <activity android:name=".ui.detail.DetailActivity"
+ android:windowSoftInputMode="adjustResize">
+
+ </activity>
+ <activity android:name=".ui.map.MapActivity"
+ android:screenOrientation="portrait">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW"/>
+
+ <category android:name="android.intent.category.LAUNCHER"/>
+ </intent-filter>
+ </activity>
+ <activity android:name=".ui.map.StreetMapActivity"
+ android:screenOrientation="portrait">
+ </activity>
+
</application>
</manifest>
\ No newline at end of file | Unknown | `android:screenOrientation` ์์ฑ์ด ์ผ๋ถ Activity์๋ง ์ ์ฉ๋์ด ์๋๋ฐ ์๋ํ์ ๊ฒ ์๋๋ผ ๋น ํธ๋ฆฌ์ ๊ฑฐ ๊ฐ๋ค์ |
@@ -0,0 +1,45 @@
+package kr.co.connect.boostcamp.livewhere
+
+import android.content.Context
+import androidx.multidex.MultiDex
+import androidx.multidex.MultiDexApplication
+import com.bumptech.glide.Glide
+import com.crashlytics.android.Crashlytics
+import com.facebook.stetho.Stetho
+import com.naver.maps.map.NaverMapSdk
+import io.fabric.sdk.android.Fabric
+import kr.co.connect.boostcamp.livewhere.di.appModules
+import org.koin.android.ext.android.startKoin
+
+
+// FIXME MultiDex ์ด์๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ์ถฉ๋ถํ๊ธฐ๋๋ฌธ์ gradle๊ณผ Applicationํด๋์ค์์ Multidex ํ๊ฒฝ์ ๊ตฌ์ฑํด์ฃผ์ธ์
+class LiveApplication : MultiDexApplication() {
+ override fun onCreate() {
+ super.onCreate()
+ //debug๋ณ์๋ฅผ ๋๊ณ debug ์ธ์ง ์บ์นํจ.
+ if (BuildConfig.isDebug) {
+ Stetho.initializeWithDefaults(this)
+ }
+ startKoin(this, appModules)
+ //Firebase Crashlytics
+ Fabric.with(this, Crashlytics())
+ NaverMapSdk.getInstance(this).client = NaverMapSdk.NaverCloudPlatformClient(BuildConfig.NaverClientId)
+ }
+
+ //application class์์ MultiDex ์ฌ์ฉ
+ override fun attachBaseContext(base: Context?) {
+ super.attachBaseContext(base)
+ MultiDex.install(this)
+ }
+
+
+ override fun onLowMemory() {
+ super.onLowMemory()
+ Glide.get(this).clearMemory()
+ }
+
+ override fun onTrimMemory(level: Int) {
+ super.onTrimMemory(level)
+ Glide.get(this).trimMemory(level)
+ }
+}
\ No newline at end of file | Kotlin | https://github.com/boostcamp-3rd/android_teamC/pull/8/files#diff-51a0b488f963eb0be6c6599bf5df497313877cf5bdff3950807373912ac1cdc9R21
์ด๋ฏธ multidex ์ค์ ๋์ด ์์ต๋๋ค.
๋ถํ์ํ ์ฃผ์์ด ๋จ์์๋๊ฑด ์ฝ๋๋ฅผ ์ฝ๋๋ฐ ์ด๋ ค์์ ์ฃผ๋ ์ ๊ฑฐํด์ฃผ์ธ์. |
@@ -0,0 +1,45 @@
+package kr.co.connect.boostcamp.livewhere
+
+import android.content.Context
+import androidx.multidex.MultiDex
+import androidx.multidex.MultiDexApplication
+import com.bumptech.glide.Glide
+import com.crashlytics.android.Crashlytics
+import com.facebook.stetho.Stetho
+import com.naver.maps.map.NaverMapSdk
+import io.fabric.sdk.android.Fabric
+import kr.co.connect.boostcamp.livewhere.di.appModules
+import org.koin.android.ext.android.startKoin
+
+
+// FIXME MultiDex ์ด์๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ์ถฉ๋ถํ๊ธฐ๋๋ฌธ์ gradle๊ณผ Applicationํด๋์ค์์ Multidex ํ๊ฒฝ์ ๊ตฌ์ฑํด์ฃผ์ธ์
+class LiveApplication : MultiDexApplication() {
+ override fun onCreate() {
+ super.onCreate()
+ //debug๋ณ์๋ฅผ ๋๊ณ debug ์ธ์ง ์บ์นํจ.
+ if (BuildConfig.isDebug) {
+ Stetho.initializeWithDefaults(this)
+ }
+ startKoin(this, appModules)
+ //Firebase Crashlytics
+ Fabric.with(this, Crashlytics())
+ NaverMapSdk.getInstance(this).client = NaverMapSdk.NaverCloudPlatformClient(BuildConfig.NaverClientId)
+ }
+
+ //application class์์ MultiDex ์ฌ์ฉ
+ override fun attachBaseContext(base: Context?) {
+ super.attachBaseContext(base)
+ MultiDex.install(this)
+ }
+
+
+ override fun onLowMemory() {
+ super.onLowMemory()
+ Glide.get(this).clearMemory()
+ }
+
+ override fun onTrimMemory(level: Int) {
+ super.onTrimMemory(level)
+ Glide.get(this).trimMemory(level)
+ }
+}
\ No newline at end of file | Kotlin | ๋์์ด ์๋ช
ํ ์ฝ๋๋ผ ์ฃผ์์ด ๋ถํ์ํด ๋ณด์
๋๋ค. |
@@ -0,0 +1,40 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Single
+import kr.co.connect.boostcamp.livewhere.model.HouseResponse
+import kr.co.connect.boostcamp.livewhere.model.PlaceResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.POST
+import retrofit2.http.Query
+
+interface Api {
+ @GET("house/search/info")
+ fun getHouseDetail(
+ @Query("address") address: String
+ ): Single<Response<List<Any>>>
+
+ @GET("house/search/infos")
+ fun getDetail(
+ @Query("address") address: String
+ ): Single<Response<HouseResponse>>
+
+ @GET("place/search/infos")
+ fun getPlace(
+ @Query("lat") lat: String,
+ @Query("lng") lng: String,
+ @Query("radius") radius: String,
+ @Query("category") category: String
+ ): Single<Response<PlaceResponse>>
+
+ @GET("house/search/find/infos")
+ fun getDetailWithAddress(
+ @Query("address") address: String
+ ): Single<Response<HouseResponse>>
+
+ @POST("")
+ fun postReview(
+ @Query("nickname") nickname: String, @Query("id") id: String, @Query("contents") contents: String
+ ): Single<Response<Any>>
+
+}
\ No newline at end of file | Kotlin | ์ด๋ ํ ์์๋ ๊ฐ๋ฆฌํค๊ณ ์์ง ์๋ค๋ฉด RESTful ํ์ง ์์ต๋๋ค.
์ฌ๋ฐ๋ฅด์ง ๋ชปํ ์ค๊ณ์
๋๋ค. |
@@ -0,0 +1,20 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Observable
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.TmapResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Query
+
+interface TmapApi {
+ @GET("tmap/pois")
+ fun getAddress(
+ @Query("searchKeyword") searchKeyword: String,
+ @Query("appKey") appKey: String = BuildConfig.TmapApiKey,
+ @Query("count") count: String = "10",
+ @Query("areaLLCode") code: String = "11"
+ ): Observable<Response<TmapResponse>>
+
+
+}
\ No newline at end of file | Kotlin | `10`, `11`์ ์ด๋ค ๊ธฐ์ค์ผ๋ก ์ ํด์ง default ๊ฐ์ธ์ง ์ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค.
์์๋ก ๋นผ๋ด๊ณ ๋ณ์๋ช
์ ์๋ฏธ๋ฅผ ๋ด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,20 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Observable
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.TmapResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Query
+
+interface TmapApi {
+ @GET("tmap/pois")
+ fun getAddress(
+ @Query("searchKeyword") searchKeyword: String,
+ @Query("appKey") appKey: String = BuildConfig.TmapApiKey,
+ @Query("count") count: String = "10",
+ @Query("areaLLCode") code: String = "11"
+ ): Observable<Response<TmapResponse>>
+
+
+}
\ No newline at end of file | Kotlin | Retrofit์ผ๋ก ๊ตฌํ๋๋๋ฐ Observable์ผ ํ์๊ฐ ์์ต๋๋ค. Http๋๊น์. |
@@ -0,0 +1,19 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Single
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.ReverseGeo
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Headers
+import retrofit2.http.Query
+
+interface ReverseGeoApi {
+ @Headers("Authorization: KakaoAK " + BuildConfig.KakaoServiceKey)
+ @GET("geo/coord2address.json")
+ fun getAddress(
+ @Query("y") latitude: String,
+ @Query("x") longitude: String,
+ @Query("input_coord") inputCoord: String
+ ): Single<Response<ReverseGeo>>
+}
\ No newline at end of file | Kotlin | gps ์ขํ ์ ๋ณด์ธ๊ฑธ๋ก ๋ณด์ด๋๋ฐ String์ด ๋ง๋์? |
@@ -0,0 +1,12 @@
+package kr.co.connect.boostcamp.livewhere.data.entity
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "recent_search")
+data class RecentSearchEntity(
+ @PrimaryKey var text: String,
+ @ColumnInfo(name = "Longitude") var longitude: String,
+ @ColumnInfo(name = "Latitude") var latitude: String
+)
\ No newline at end of file | Kotlin | ๋ค๋ฅธ ํ
์ด๋ธ์ ์ปฌ๋ผ๋ค์ ์๋ฌธ์๋ก ์์ํ๋ snake case๋ฅผ ์ฌ์ฉํ๊ณ ์์ต๋๋ค.
ํต์ผ์ด ํ์ํด๋ณด์ฌ์ |
@@ -0,0 +1,13 @@
+package kr.co.connect.boostcamp.livewhere.di
+
+
+val appModules = arrayListOf(
+ apiModule
+ , loginModule
+ , sharedModule
+ , databaseModule
+ , homeModule
+ , mapModule
+ , reverseGeoApiModule
+ , detailModule
+) | Kotlin | ๋ค๋ฅธ ์ฝ๋๋ค๊ณผ ์ ํ ๋ค๋ฅธ code format์ธ๋ฐ ํต์ผ์ด ํ์ํด ๋ณด์
๋๋ค. |
@@ -0,0 +1,24 @@
+package kr.co.connect.boostcamp.livewhere.di
+
+import androidx.room.Room
+import kr.co.connect.boostcamp.livewhere.data.database.AppDataBase
+import org.koin.android.ext.koin.androidContext
+import org.koin.dsl.module.module
+
+const val DATABASE_NAME = "mdatabase.db"
+
+val databaseModule = module {
+ single("databaseModule") {
+ Room.databaseBuilder(androidContext(), AppDataBase::class.java, DATABASE_NAME)
+ .fallbackToDestructiveMigration()
+ .build()
+ }
+
+ single("bookmarkDAO") {
+ get<AppDataBase>().bookmarkDao()
+ }
+
+ single("recentSearchDAO") {
+ get<AppDataBase>().recentSearchDao()
+ }
+}
\ No newline at end of file | Kotlin | ์ด ๋ชจ๋์ ์ ์๋ 3๊ฐ์ง injection๋ค์ named inject๊ฐ ํ์ํ๊ฐ์?
๋ถํ์ํด๋ณด์
๋๋ค. |
@@ -0,0 +1,50 @@
+package christmas.domain;
+
+public enum Calendar {
+ WEEKEND(1, 2, 8, 9, 15, 16, 22, 23, 29, 30),
+ WEEKDAY(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31),
+ SPECIAL_DAY(3, 10, 17, 24, 25, 31);
+
+ private final int[] days;
+
+ Calendar(int... days) {
+ this.days = days;
+ }
+
+ public int[] getDays() {
+ return days;
+ }
+
+ public static boolean isWeekday(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekday : calendar.getDays()) {
+ if (weekday == date && calendar == WEEKDAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekend : calendar.getDays()) {
+ if (weekend == date && calendar == WEEKEND) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ for (Calendar calendar : values()) {
+ for (int specialDay : calendar.getDays()) {
+ if (specialDay == date && calendar == SPECIAL_DAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+} | Java | ๋ ์ง ๊ด๋ จ๋ ๋ก์ง์ `LocalDate`์ `DayOfWeek`๋ฅผ ์ ์ฉํ๋ฉด ํจ์ฌ ๊ฐ๊ฒฐํ๊ฒ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค!! |
@@ -0,0 +1,50 @@
+package christmas.domain;
+
+public enum Calendar {
+ WEEKEND(1, 2, 8, 9, 15, 16, 22, 23, 29, 30),
+ WEEKDAY(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31),
+ SPECIAL_DAY(3, 10, 17, 24, 25, 31);
+
+ private final int[] days;
+
+ Calendar(int... days) {
+ this.days = days;
+ }
+
+ public int[] getDays() {
+ return days;
+ }
+
+ public static boolean isWeekday(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekday : calendar.getDays()) {
+ if (weekday == date && calendar == WEEKDAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekend : calendar.getDays()) {
+ if (weekend == date && calendar == WEEKEND) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ for (Calendar calendar : values()) {
+ for (int specialDay : calendar.getDays()) {
+ if (specialDay == date && calendar == SPECIAL_DAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+} | Java | ํด๋น ๋ก์ง์ depth๊ฐ 3์ด๊ธฐ์ ์ ์ ํ ๋ฉ์๋ ์ถ์ถ, ๋๋ ๋ฆฌํฉํ ๋ง์ด ํ์ํ ๊ฒ ๊ฐ์๋ฐ์.
์ฃผ๋ง์ ํ์ธํ๊ธฐ ์ํด์ ๋ชจ๋ `Calandar`์ `enum` ์์๋ฅผ ํ์ํ ํ์๋ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
๋ํ, ์คํธ๋ฆผ์ ์ฌ์ฉํ๋ค๋ฉด ๋๋ก ์ฒด์ธ๋ค๋ก ๊ฐ๊ฐ์ ๋จ๊ณ๊ฐ ๊ตฌ๋ถ๋๊ธฐ์ ๊ฐ๋
์ฑ์ด ์ข์์ง๊ธฐ๋ ํ๋ ์คํธ๋ฆผ์ ์ ๊ทน ํ์ฉํ์๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
```suggestion
return Arrays.stream(WEEKEND.days)
.anyMatch(day -> day == date);
``` |
@@ -0,0 +1,37 @@
+package christmas.domain;
+
+import java.util.Arrays;
+
+public enum Menu {
+ ์์ก์ด์ํ(6_000), ํํ์ค(5_500), ์์ ์๋ฌ๋(8_000),
+ ํฐ๋ณธ์คํ
์ดํฌ(55_000), ๋ฐ๋นํ๋ฆฝ(54_000), ํด์ฐ๋ฌผํ์คํ(35_000), ํฌ๋ฆฌ์ค๋ง์คํ์คํ(25_000),
+ ์ด์ฝ์ผ์ดํฌ(15_000), ์์ด์คํฌ๋ฆผ(5_000),
+ ์ ๋ก์ฝ๋ผ(3_000), ๋ ๋์์ธ(60_000), ์ดํ์ธ(25_000);
+
+ private final int price;
+
+ Menu(int price) {
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public boolean isBeverage() {
+ return this == ์ ๋ก์ฝ๋ผ || this == ๋ ๋์์ธ || this == ์ดํ์ธ;
+ }
+
+ public boolean isDessert() {
+ return this == ์ด์ฝ์ผ์ดํฌ || this == ์์ด์คํฌ๋ฆผ;
+ }
+
+ public boolean isMain() {
+ return this == ํฐ๋ณธ์คํ
์ดํฌ || this == ๋ฐ๋นํ๋ฆฝ || this == ํด์ฐ๋ฌผํ์คํ || this == ํฌ๋ฆฌ์ค๋ง์คํ์คํ;
+ }
+
+ public static boolean contains(String itemName) {
+ return Arrays.stream(Menu.values())
+ .anyMatch(menu -> menu.name().equalsIgnoreCase(itemName));
+ }
+} | Java | ์ด ๊ฒฝ์ฐ ๋ฉ๋ด์ ์ถ๊ฐ ๋ฐ ๋ณ๊ฒฝ์ด ์์ ๋ ๋ง๋ค ๋ฉ์๋ ๋ก์ง์ ๋ณ๊ฒฝ ๋ํ ํจ๊ป ๋ฐ์ํด์ผ ํ๋๋ฐ์.
๊ฐ ๋ฉ๋ด์ ์ ๋ณด๊ฐ ๋ฉ๋ด ํ์
์ ํจ๊ป ์ ์ฅํ๊ณ ์๊ฑฐ๋, ๋ฉ๋ด ํ์
์ด ๋ฆฌ์คํธ ํ์์ผ๋ก ๋ฉ๋ด๋ค์ ์ ์ฅํ๊ณ ์๋๋ก ํ๋ฉด `public boolean isTypeOf(MenuType expectedType)`๊ณผ ๊ฐ์ ๋ฉ์๋ ํ๋๋ง ์ ๊ณตํด ์ฃผ๋ ๊ฒ์ผ๋ก ๋ณํ์ ์ฝ๊ฒ ๋์ํ ์๊ฐ ์์ด์! |
@@ -0,0 +1,24 @@
+package christmas.domain;
+
+public enum DiscountType {
+ MIN_EVENT_CONDITION(10000),
+ CHAMPAGNE_CONDITION(120000),
+ CHAMPAGNE(25000),
+ SERVICE_MENU_CONDITION(1),
+ DDAY_CONDITION(25),
+ BASE_AMOUNT(900),
+ DAY_BONUS(100),
+ SPECIALDAY_CONDITION(2023),
+ INIT_COUNT(0),
+ SPECIAL_DISCOUNT(1000);
+
+ private final int type;
+
+ DiscountType(int type) {
+ this.type = type;
+ }
+
+ public int getType() {
+ return type;
+ }
+} | Java | ์ซ์์ ์๋ฆฌ์๊ฐ ๋ง์์ง๋ค๋ฉด _ ์ผ๋ก ์๋ฆฌ์ ๊ตฌ๋ถ์ด ๊ฐ๋ฅํฉ๋๋ค!
```suggestion
CHAMPAGNE_CONDITION(120_000),
``` |
@@ -0,0 +1,36 @@
+package christmas.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Menu;
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.exception.ValidatorException;
+import christmas.validator.Validator;
+import java.util.Map;
+
+public class InputView {
+
+ public static Reservation createReservation() {
+ try {
+ String input = Console.readLine();
+ int date = Validator.convertDateStringToInt(input);
+
+ return Reservation.from(date);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createReservation();
+ }
+ }
+
+ public static Order createOrder() {
+ try {
+ String input = Console.readLine();
+ Validator.isValidOrderFormat(input);
+ Map<Menu, Integer> order = Validator.parseOrder(input);
+ return Order.from(order);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createOrder();
+ }
+ }
+} | Java | `InputView`์ ์กด์ฌํ๋ ์ฝ๋ ํ๋ฆ์ ์ค๋ณต์ ๋ค์๊ณผ ๊ฐ์ด ์ ๊ฑฐํ ์ ์์ต๋๋ค!
๋์ ํ๋ผ๋ฏธํฐํ๋ก ๋ณ๊ฒฝ์ด ํ์ํ ๋ก์ง์ ๋ถ๋ถ๋ง ์ค๋ณต๋๋ ํ๋ฆ ์ฌ์ด์ ์ ๋ฌํด ์ฃผ๋ ๋ฐฉ์์ด์์!
```suggestion
public static Order createOrder() {
return getResult(() -> {
String input = Console.readLine();
Validator.isValidOrderFormat(input);
Map<Menu, Integer> order = Validator.parseOrder(input);
return Order.from(order);
});
}
public static <T> T getResult(Supplier<T> supplier){
try{
return supplier.get();
} catch (ValidatorException e){
OutputView.println(e.getMessage());
return getResult(supplier);
}
}
``` |
@@ -0,0 +1,36 @@
+package christmas.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Menu;
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.exception.ValidatorException;
+import christmas.validator.Validator;
+import java.util.Map;
+
+public class InputView {
+
+ public static Reservation createReservation() {
+ try {
+ String input = Console.readLine();
+ int date = Validator.convertDateStringToInt(input);
+
+ return Reservation.from(date);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createReservation();
+ }
+ }
+
+ public static Order createOrder() {
+ try {
+ String input = Console.readLine();
+ Validator.isValidOrderFormat(input);
+ Map<Menu, Integer> order = Validator.parseOrder(input);
+ return Order.from(order);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createOrder();
+ }
+ }
+} | Java | `View`์์ ๋๋ฉ์ธ ํด๋์ค ์์ฒด๊ฐ ์์ฑ๋์ด ๋ฐํ๋๋ ๊ฒ์ด `View` ํด๋์ค์ ๋๋ฌด ๋ง์ ์ฑ
์์ด ์กด์ฌํ๋ ๊ฒ ์ฒ๋ผ ๋ณด์ด๊ธฐ๋ ํ๋๋ฐ ์ด ๋ถ๋ถ์ ๋ํด์ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,48 @@
+package christmas.view.messages;
+
+public enum PrintMessage {
+ INPUT_INTRODUCE("์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."),
+ INPUT_RESERVATION("12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"),
+ INPUT_ORDER("์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"),
+
+ OUTPUT_RESULT("12์ 26์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"),
+ OUTPUT_ORDER("<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ OUTPUT_TOTAL_BEFORE_DISCOUNT("<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ OUTPUT_GIFT_MENU("<์ฆ์ ๋ฉ๋ด>"),
+ OUTPUT_BENEFIT("<ํํ ๋ด์ญ>"),
+ OUTPUT_TOTAL_BENEFIT("<์ดํํ ๊ธ์ก>"),
+ OUTPUT_TOTAL_AFTER_DISCOUNT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ OUTPUT_EVENT_BADGE("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"),
+ OUTPUT_PRECAUTIONS("์ด์ฃผ๋ฌธ ๊ธ์ก 10,000์ ์ด์๋ถํฐ ์ด๋ฒคํธ๊ฐ ์ ์ฉ๋ฉ๋๋ค.\n"
+ + "์๋ฃ๋ง ์ฃผ๋ฌธ ์, ์ฃผ๋ฌธํ ์ ์์ต๋๋ค.\n"
+ + "๋ฉ๋ด๋ ํ ๋ฒ์ ์ต๋ 20๊ฐ๊น์ง๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค.\n"
+ + "(e.g. ์์ ์๋ฌ๋-1, ํฐ๋ณธ์คํ
์ดํฌ-1, ํฌ๋ฆฌ์ค๋ง์คํ์คํ-1, ์ ๋ก์ฝ๋ผ-3, ์์ด์คํฌ๋ฆผ-1์ ์ด๊ฐ์๋ 7๊ฐ)\n"),
+ MONEY("์"),
+ COUNT("๊ฐ"),
+ NONE("์์"),
+ PREVIEW("12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"),
+ CHRISTMAS_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ํ ์ธ: -"),
+ WEEKDAY_DISCOUNT("ํ์ผ ํ ์ธ: -"),
+ WEEKEND_DISCOUNT("์ฃผ๋ง ํ ์ธ: -"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ: -"),
+ SERVICE_DISCOUNT("์ฆ์ ์ด๋ฒคํธ: -"),
+ BENEFIT_ALL_DISCOUNT("<์ดํํ ๊ธ์ก>"),
+ AFTER_BENEFIT_DISCOUNT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ BADGE_DISCOUNT("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"),
+ SERVICE_MENU("์ดํ์ธ 1๊ฐ");
+
+
+ private final String message;
+
+ PrintMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getMessage(int day) {
+ return String.format(message, day);
+ }
+} | Java | ์ฌ๋ฌ ์ค๋ก ๊ตฌ์ฑ๋ `String`์ `"""`๋ก ๊ฐ์ธ์ค ์ ์๋ ๊ฒ์ผ๋ก ์๊ณ ์์ต๋๋ค! |
@@ -0,0 +1,150 @@
+package christmas.validator;
+
+import christmas.domain.Menu;
+import christmas.exception.ErrorMessage;
+import christmas.exception.ValidatorException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Validator {
+ private static final String DELIMITER = ",";
+ private static final int FIRST_DAY = 1;
+ private static final int LAST_DAY = 31;
+ private static final int MAX_MENU_COUNT = 20;
+ private static final int MIN_MUST_COUNT = 1;
+ private static final int TRUE = 1;
+ private static final int FALSE = 0;
+ public static int convertDateStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_DATE, exception);
+ }
+ }
+
+ public static int convertOrderStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static boolean isNumeric(String input) {
+ return input.matches("\\d+");
+ }
+
+ public static void isInRange(int date) {
+ if (date < FIRST_DAY || date > LAST_DAY) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static boolean isValidOrderFormat(String order) {
+ try {
+ String regex = "([\\w๊ฐ-ํฃ]+-\\d+,)*[\\w๊ฐ-ํฃ]+-\\d+";
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(order);
+ return matcher.matches();
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+
+ public static Map<Menu, Integer> parseOrder(String order) {
+ try {
+ Map<Menu, Integer> orderMap = new HashMap<>();
+ Set<Menu> uniqueMenus = new HashSet<>();
+ String[] items = order.split(",");
+ int count = 0;
+ int beverageFlag = FALSE;
+ for (String item : items) {
+ String[] parts = item.split("-");
+ validateNonNumericString(parts[0]); // ์ฒ์ ๋ค์ด์จ ๊ฐ์ด ์ซ์๋ฉด ์๋ฌ
+ Menu menu = getMenuByName(parts[0]);
+ if (!menu.isBeverage()) {
+ beverageFlag = TRUE;
+ }
+ isDuplicate(uniqueMenus, menu);
+ if (parts.length == 2) {
+ int quantity = convertOrderStringToInt(parts[1]);
+ isMinCount(quantity);
+ count += quantity;
+ orderMap.put(menu, quantity);
+ }
+ }
+ isOnlyBeverageOrder(beverageFlag);
+ isMaxCount(count);
+ return orderMap;
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static void isOnlyBeverageOrder(int beverageFlag) {
+ if (beverageFlag == FALSE) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isDuplicate(Set<Menu> uniqueMenus, Menu menu) {
+ if (!uniqueMenus.add(menu)) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMinCount(int quantity) {
+ if (quantity < MIN_MUST_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMaxCount(int count) {
+ if (count > MAX_MENU_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static void validateNonNumericString(String input) {
+ if (isNumeric(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ public static Menu getMenuByName(String menuName) {
+ for (Menu menu : Menu.values()) {
+ if (menu.name().equalsIgnoreCase(menuName)) {
+ return menu;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+
+
+ public static void validateContainWhiteSpace(String input) {
+ if (hasWhiteSpace(input)) {
+ throw ValidatorException.from(ErrorMessage.CONTAIN_WHITESPACE);
+ }
+ }
+
+ public static void validateEndsWithDelimiter(String input) {
+ if (isEndsWithDelimiter(input)) {
+ throw ValidatorException.from(ErrorMessage.ENDS_WITH_DELIMITER);
+ }
+ }
+
+ private static boolean hasWhiteSpace(String input) {
+ return input.chars().anyMatch(Character::isWhitespace);
+ }
+
+ private static boolean isEndsWithDelimiter(String input) {
+ return input.endsWith(DELIMITER);
+ }
+} | Java | ํด๋น ๋ก์ง์ 26๋ผ์ธ์ผ๋ก ๊ตฌ์ฑ๋์ด ์์ด์.
๊ฐ ๋จ๊ณ๋ฅผ ๋ฉ์๋๋ก ์ถ์ถํด ๋ณด๋ ๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,50 @@
+package christmas.domain;
+
+public enum Calendar {
+ WEEKEND(1, 2, 8, 9, 15, 16, 22, 23, 29, 30),
+ WEEKDAY(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31),
+ SPECIAL_DAY(3, 10, 17, 24, 25, 31);
+
+ private final int[] days;
+
+ Calendar(int... days) {
+ this.days = days;
+ }
+
+ public int[] getDays() {
+ return days;
+ }
+
+ public static boolean isWeekday(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekday : calendar.getDays()) {
+ if (weekday == date && calendar == WEEKDAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekend : calendar.getDays()) {
+ if (weekend == date && calendar == WEEKEND) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ for (Calendar calendar : values()) {
+ for (int specialDay : calendar.getDays()) {
+ if (specialDay == date && calendar == SPECIAL_DAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+} | Java | ์๊ฐํ์ง ๋ชปํ๋ ๋ถ๋ถ์ธ๋ฐ ๊ฐ์ฌํฉ๋๋ค. |
@@ -0,0 +1,50 @@
+package christmas.domain;
+
+public enum Calendar {
+ WEEKEND(1, 2, 8, 9, 15, 16, 22, 23, 29, 30),
+ WEEKDAY(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31),
+ SPECIAL_DAY(3, 10, 17, 24, 25, 31);
+
+ private final int[] days;
+
+ Calendar(int... days) {
+ this.days = days;
+ }
+
+ public int[] getDays() {
+ return days;
+ }
+
+ public static boolean isWeekday(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekday : calendar.getDays()) {
+ if (weekday == date && calendar == WEEKDAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekend : calendar.getDays()) {
+ if (weekend == date && calendar == WEEKEND) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ for (Calendar calendar : values()) {
+ for (int specialDay : calendar.getDays()) {
+ if (specialDay == date && calendar == SPECIAL_DAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+} | Java | ํ.. ๊ทธ๋ ์ง ์์๋ Stream์ ๋ํด ๊ณ์ ๊ณต๋ถํ๊ณ ์๋๋ฐ ๋ณต์ตํ๋ฉฐ ์ ์ฉํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,24 @@
+package christmas.domain;
+
+public enum DiscountType {
+ MIN_EVENT_CONDITION(10000),
+ CHAMPAGNE_CONDITION(120000),
+ CHAMPAGNE(25000),
+ SERVICE_MENU_CONDITION(1),
+ DDAY_CONDITION(25),
+ BASE_AMOUNT(900),
+ DAY_BONUS(100),
+ SPECIALDAY_CONDITION(2023),
+ INIT_COUNT(0),
+ SPECIAL_DISCOUNT(1000);
+
+ private final int type;
+
+ DiscountType(int type) {
+ this.type = type;
+ }
+
+ public int getType() {
+ return type;
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,37 @@
+package christmas.domain;
+
+import java.util.Arrays;
+
+public enum Menu {
+ ์์ก์ด์ํ(6_000), ํํ์ค(5_500), ์์ ์๋ฌ๋(8_000),
+ ํฐ๋ณธ์คํ
์ดํฌ(55_000), ๋ฐ๋นํ๋ฆฝ(54_000), ํด์ฐ๋ฌผํ์คํ(35_000), ํฌ๋ฆฌ์ค๋ง์คํ์คํ(25_000),
+ ์ด์ฝ์ผ์ดํฌ(15_000), ์์ด์คํฌ๋ฆผ(5_000),
+ ์ ๋ก์ฝ๋ผ(3_000), ๋ ๋์์ธ(60_000), ์ดํ์ธ(25_000);
+
+ private final int price;
+
+ Menu(int price) {
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public boolean isBeverage() {
+ return this == ์ ๋ก์ฝ๋ผ || this == ๋ ๋์์ธ || this == ์ดํ์ธ;
+ }
+
+ public boolean isDessert() {
+ return this == ์ด์ฝ์ผ์ดํฌ || this == ์์ด์คํฌ๋ฆผ;
+ }
+
+ public boolean isMain() {
+ return this == ํฐ๋ณธ์คํ
์ดํฌ || this == ๋ฐ๋นํ๋ฆฝ || this == ํด์ฐ๋ฌผํ์คํ || this == ํฌ๋ฆฌ์ค๋ง์คํ์คํ;
+ }
+
+ public static boolean contains(String itemName) {
+ return Arrays.stream(Menu.values())
+ .anyMatch(menu -> menu.name().equalsIgnoreCase(itemName));
+ }
+} | Java | ์ข ๋ ๊ฐ์ฒด์งํฅ์ ์ผ๋ก ์ค๊ณ๊ฐ ๊ฐ๋ฅํ ๋ถ๋ถ์ด๋ค์. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,150 @@
+package christmas.validator;
+
+import christmas.domain.Menu;
+import christmas.exception.ErrorMessage;
+import christmas.exception.ValidatorException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Validator {
+ private static final String DELIMITER = ",";
+ private static final int FIRST_DAY = 1;
+ private static final int LAST_DAY = 31;
+ private static final int MAX_MENU_COUNT = 20;
+ private static final int MIN_MUST_COUNT = 1;
+ private static final int TRUE = 1;
+ private static final int FALSE = 0;
+ public static int convertDateStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_DATE, exception);
+ }
+ }
+
+ public static int convertOrderStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static boolean isNumeric(String input) {
+ return input.matches("\\d+");
+ }
+
+ public static void isInRange(int date) {
+ if (date < FIRST_DAY || date > LAST_DAY) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static boolean isValidOrderFormat(String order) {
+ try {
+ String regex = "([\\w๊ฐ-ํฃ]+-\\d+,)*[\\w๊ฐ-ํฃ]+-\\d+";
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(order);
+ return matcher.matches();
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+
+ public static Map<Menu, Integer> parseOrder(String order) {
+ try {
+ Map<Menu, Integer> orderMap = new HashMap<>();
+ Set<Menu> uniqueMenus = new HashSet<>();
+ String[] items = order.split(",");
+ int count = 0;
+ int beverageFlag = FALSE;
+ for (String item : items) {
+ String[] parts = item.split("-");
+ validateNonNumericString(parts[0]); // ์ฒ์ ๋ค์ด์จ ๊ฐ์ด ์ซ์๋ฉด ์๋ฌ
+ Menu menu = getMenuByName(parts[0]);
+ if (!menu.isBeverage()) {
+ beverageFlag = TRUE;
+ }
+ isDuplicate(uniqueMenus, menu);
+ if (parts.length == 2) {
+ int quantity = convertOrderStringToInt(parts[1]);
+ isMinCount(quantity);
+ count += quantity;
+ orderMap.put(menu, quantity);
+ }
+ }
+ isOnlyBeverageOrder(beverageFlag);
+ isMaxCount(count);
+ return orderMap;
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static void isOnlyBeverageOrder(int beverageFlag) {
+ if (beverageFlag == FALSE) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isDuplicate(Set<Menu> uniqueMenus, Menu menu) {
+ if (!uniqueMenus.add(menu)) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMinCount(int quantity) {
+ if (quantity < MIN_MUST_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMaxCount(int count) {
+ if (count > MAX_MENU_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static void validateNonNumericString(String input) {
+ if (isNumeric(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ public static Menu getMenuByName(String menuName) {
+ for (Menu menu : Menu.values()) {
+ if (menu.name().equalsIgnoreCase(menuName)) {
+ return menu;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+
+
+ public static void validateContainWhiteSpace(String input) {
+ if (hasWhiteSpace(input)) {
+ throw ValidatorException.from(ErrorMessage.CONTAIN_WHITESPACE);
+ }
+ }
+
+ public static void validateEndsWithDelimiter(String input) {
+ if (isEndsWithDelimiter(input)) {
+ throw ValidatorException.from(ErrorMessage.ENDS_WITH_DELIMITER);
+ }
+ }
+
+ private static boolean hasWhiteSpace(String input) {
+ return input.chars().anyMatch(Character::isWhitespace);
+ }
+
+ private static boolean isEndsWithDelimiter(String input) {
+ return input.endsWith(DELIMITER);
+ }
+} | Java | 15๋ผ์ธ์ผ๋ก ์ค์ด๋๋ก ๋
ธ๋ ฅํด๋ณด๊ฒ ์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,36 @@
+package christmas.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Menu;
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.exception.ValidatorException;
+import christmas.validator.Validator;
+import java.util.Map;
+
+public class InputView {
+
+ public static Reservation createReservation() {
+ try {
+ String input = Console.readLine();
+ int date = Validator.convertDateStringToInt(input);
+
+ return Reservation.from(date);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createReservation();
+ }
+ }
+
+ public static Order createOrder() {
+ try {
+ String input = Console.readLine();
+ Validator.isValidOrderFormat(input);
+ Map<Menu, Integer> order = Validator.parseOrder(input);
+ return Order.from(order);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createOrder();
+ }
+ }
+} | Java | ์ต๊ทผ์ ๊ณต๋ถํ๋ฉฐ View๋ ์ปจํธ๋กค๋ฌ์์ Model์ ๋ฐ๊ธฐ๋ง ํด์ผ ํ๋ค๋ ์๊ฐ์ด ๋ค์์ต๋๋ค. ์ด ๋น์์๋ View์์ Model์ ์์ฑํด์ ๋ฐํํ๋ ๋ฐฉ๋ฒ์ด ์ ๋ ๋ง๋๊ฑด๊ฐ? ์๊ฐ์ ํ์๋๋ฐ ๊ฐ๋ง ๋ฐํํด์ฃผ๋ ํ์์ผ๋ก ์์ ํด๋ด์ผ๊ฒ ๋ค์. ๊ฐ์ฌํฉ๋๋ค. |
@@ -0,0 +1,36 @@
+package christmas.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Menu;
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.exception.ValidatorException;
+import christmas.validator.Validator;
+import java.util.Map;
+
+public class InputView {
+
+ public static Reservation createReservation() {
+ try {
+ String input = Console.readLine();
+ int date = Validator.convertDateStringToInt(input);
+
+ return Reservation.from(date);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createReservation();
+ }
+ }
+
+ public static Order createOrder() {
+ try {
+ String input = Console.readLine();
+ Validator.isValidOrderFormat(input);
+ Map<Menu, Integer> order = Validator.parseOrder(input);
+ return Order.from(order);
+ } catch (ValidatorException exception) {
+ OutputView.println(exception.getMessage());
+ return createOrder();
+ }
+ }
+} | Java | ํ ์ด๋ฐ์์ผ๋ก ์ฝ๋๋ฅผ ์์ฑํ ์ ์๊ตฐ์. ์๋ ค์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค. ์ข ๋ ๊ณต๋ถํด์ ์ ์ฉํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,48 @@
+package christmas.view.messages;
+
+public enum PrintMessage {
+ INPUT_INTRODUCE("์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."),
+ INPUT_RESERVATION("12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"),
+ INPUT_ORDER("์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"),
+
+ OUTPUT_RESULT("12์ 26์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"),
+ OUTPUT_ORDER("<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ OUTPUT_TOTAL_BEFORE_DISCOUNT("<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ OUTPUT_GIFT_MENU("<์ฆ์ ๋ฉ๋ด>"),
+ OUTPUT_BENEFIT("<ํํ ๋ด์ญ>"),
+ OUTPUT_TOTAL_BENEFIT("<์ดํํ ๊ธ์ก>"),
+ OUTPUT_TOTAL_AFTER_DISCOUNT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ OUTPUT_EVENT_BADGE("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"),
+ OUTPUT_PRECAUTIONS("์ด์ฃผ๋ฌธ ๊ธ์ก 10,000์ ์ด์๋ถํฐ ์ด๋ฒคํธ๊ฐ ์ ์ฉ๋ฉ๋๋ค.\n"
+ + "์๋ฃ๋ง ์ฃผ๋ฌธ ์, ์ฃผ๋ฌธํ ์ ์์ต๋๋ค.\n"
+ + "๋ฉ๋ด๋ ํ ๋ฒ์ ์ต๋ 20๊ฐ๊น์ง๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค.\n"
+ + "(e.g. ์์ ์๋ฌ๋-1, ํฐ๋ณธ์คํ
์ดํฌ-1, ํฌ๋ฆฌ์ค๋ง์คํ์คํ-1, ์ ๋ก์ฝ๋ผ-3, ์์ด์คํฌ๋ฆผ-1์ ์ด๊ฐ์๋ 7๊ฐ)\n"),
+ MONEY("์"),
+ COUNT("๊ฐ"),
+ NONE("์์"),
+ PREVIEW("12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"),
+ CHRISTMAS_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ํ ์ธ: -"),
+ WEEKDAY_DISCOUNT("ํ์ผ ํ ์ธ: -"),
+ WEEKEND_DISCOUNT("์ฃผ๋ง ํ ์ธ: -"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ: -"),
+ SERVICE_DISCOUNT("์ฆ์ ์ด๋ฒคํธ: -"),
+ BENEFIT_ALL_DISCOUNT("<์ดํํ ๊ธ์ก>"),
+ AFTER_BENEFIT_DISCOUNT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ BADGE_DISCOUNT("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"),
+ SERVICE_MENU("์ดํ์ธ 1๊ฐ");
+
+
+ private final String message;
+
+ PrintMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getMessage(int day) {
+ return String.format(message, day);
+ }
+} | Java | ์! ๊น๋จน๊ณ ์์๋ค์. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,15 @@
+package christmas.controller;
+
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.domain.Result;
+
+public class EventPlannerController {
+ public static void run() {
+ Reservation reservation = ReservationController.inputReservation();
+ Order order = OrderController.inputOrder();
+ Result result = ResultController.createResult(order, reservation);
+ ResultController.printResult(result);
+
+ }
+} | Java | ์ด๋ค ์ด์ ๋ก static ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์
จ์๊น์?
static๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํธ๋ฆฌํ ์ ์๋๋ฐ ๋ค๋ฅธ ์ฌ์ด๋ ์ดํํธ๊ฐ ์์๊น์? |
@@ -0,0 +1,20 @@
+package christmas.controller;
+
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.domain.Result;
+import christmas.view.OutputView;
+
+public class ResultController {
+
+ public static Result createResult(Order order, Reservation reservation) {
+ OutputView.printIntroduce(reservation.getDate());
+ OutputView.printOrder(order);
+ System.out.println();
+ return Result.from(order.getOrderedItems(), reservation.getDate());
+ }
+
+ public static void printResult(Result result) {
+ OutputView.printAllEvents(result);
+ }
+} | Java | ์ฌ๋ฌ ์ปจํธ๋กค๋ฌ ํด๋์ค๋ฅผ ๋ถ๋ฆฌํ์ ์ด์ ๊ฐ ๋ฌด์์ธ๊ฐ์? |
@@ -0,0 +1,50 @@
+package christmas.domain;
+
+public enum Calendar {
+ WEEKEND(1, 2, 8, 9, 15, 16, 22, 23, 29, 30),
+ WEEKDAY(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31),
+ SPECIAL_DAY(3, 10, 17, 24, 25, 31);
+
+ private final int[] days;
+
+ Calendar(int... days) {
+ this.days = days;
+ }
+
+ public int[] getDays() {
+ return days;
+ }
+
+ public static boolean isWeekday(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekday : calendar.getDays()) {
+ if (weekday == date && calendar == WEEKDAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ for (Calendar calendar : values()) {
+ for (int weekend : calendar.getDays()) {
+ if (weekend == date && calendar == WEEKEND) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ for (Calendar calendar : values()) {
+ for (int specialDay : calendar.getDays()) {
+ if (specialDay == date && calendar == SPECIAL_DAY) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+} | Java | calendar๋ผ๋ enum์ด 2023๋
12์์ ๋ ์ง๋ง ์์ผ๋ ์กฐ๊ธ ์ด์ํ ๊ฒ ๊ฐ์์ ํด๋์ค ๋ช
์ ์ข ๋ ๋ช
ํํ๊ฒ ํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,29 @@
+package christmas.domain;
+
+public enum EventBadge {
+ SANTA(20000, "์ฐํ"),
+ TREE(10000, "ํธ๋ฆฌ"),
+ STAR(5000, "๋ณ"),
+ NONE(0, "์์");
+
+ private final int threshold;
+ private final String description;
+
+ EventBadge(int threshold, String description) {
+ this.threshold = threshold;
+ this.description = description;
+ }
+
+ public static EventBadge getBadge(int totalAfterBenefit) {
+ for (EventBadge badge : values()) {
+ if (totalAfterBenefit >= badge.threshold) {
+ return badge;
+ }
+ }
+ return EventBadge.NONE;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+} | Java | ์ด๊ฒ๋ ์คํธ๋ฆผ์ผ๋ก ํด๊ฒฐํ ์ ์๊ฒ ๋ค์
ํด๋ํฐ์ผ๋ก ํ๋ ๊ฒ์ด๋ผ ์ฝ๋์น๊ธฐ๊ฐ ๋ถํธํด์ ์คํธ๋ฆผ, filter, findAny, orElseGet ์ ์ฌ์ฉํ๋ฉด ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,37 @@
+package christmas.domain;
+
+import java.util.Arrays;
+
+public enum Menu {
+ ์์ก์ด์ํ(6_000), ํํ์ค(5_500), ์์ ์๋ฌ๋(8_000),
+ ํฐ๋ณธ์คํ
์ดํฌ(55_000), ๋ฐ๋นํ๋ฆฝ(54_000), ํด์ฐ๋ฌผํ์คํ(35_000), ํฌ๋ฆฌ์ค๋ง์คํ์คํ(25_000),
+ ์ด์ฝ์ผ์ดํฌ(15_000), ์์ด์คํฌ๋ฆผ(5_000),
+ ์ ๋ก์ฝ๋ผ(3_000), ๋ ๋์์ธ(60_000), ์ดํ์ธ(25_000);
+
+ private final int price;
+
+ Menu(int price) {
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public boolean isBeverage() {
+ return this == ์ ๋ก์ฝ๋ผ || this == ๋ ๋์์ธ || this == ์ดํ์ธ;
+ }
+
+ public boolean isDessert() {
+ return this == ์ด์ฝ์ผ์ดํฌ || this == ์์ด์คํฌ๋ฆผ;
+ }
+
+ public boolean isMain() {
+ return this == ํฐ๋ณธ์คํ
์ดํฌ || this == ๋ฐ๋นํ๋ฆฝ || this == ํด์ฐ๋ฌผํ์คํ || this == ํฌ๋ฆฌ์ค๋ง์คํ์คํ;
+ }
+
+ public static boolean contains(String itemName) {
+ return Arrays.stream(Menu.values())
+ .anyMatch(menu -> menu.name().equalsIgnoreCase(itemName));
+ }
+} | Java | ์ฌ๊ธฐ๋ง ๋ณ์๋ช
์ ํ๊ธ๋ก ํ์ ์ด์ ๊ฐ ์๋์? ์ ๋ ํ๊ธ ๋ณ์๊ฐ ๊ฐ๋
์ฑ์ด ์ข๋ค๊ณ ์๊ฐํ์ง๋ง ์๋์์ฑ์์ ๋ถํธํ๋๋ผ๊ณ ์
๊ทธ๋ฆฌ๊ณ ์๋์ is~~~ ๋ฉ์๋๊ฐ ๋ง์๋ฐ ๋ฉ๋ด์ ๊ฐ๊ฒฉ๊ณผ ํ์
๋ ๊ฐ์ด ๊ฐ์ง๊ณ ์๋ค๋ฉด ์ข ๋ ๊น๋ํ๊ฒ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ ๊ฒ ๊ฐ๋ค์ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.