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
์ฆ๊ฒจ์ฐพ๊ธฐ ์ƒ์„ฑ ํ›„ ๋ฐ˜ํ™˜๊ฐ’์— ๋Œ€ํ•œ ์š”๊ตฌ์‚ฌํ•ญ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”! ๐Ÿ˜„ ![แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-02-22 แ„‹แ…ฉแ„’แ…ฎ 7 58 34](https://user-images.githubusercontent.com/48339310/155118827-d664b3b1-32e7-4255-a58c-e5d09ce3550d.png)
@@ -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"> +![Seoul42 Service](https://img.shields.io/badge/service-android-green.svg) +![Seoul42 Pattern](https://img.shields.io/badge/pattern-MVVM-blue.svg) +[![Seoul42 DI](https://img.shields.io/badge/DI-koin-blue.svg)](https://insert-koin.io) +[![Seoul42_UI](https://img.shields.io/badge/UI-zeplin-blue.svg)](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard) + +[![Seoul42_UI](https://img.shields.io/badge/library-RxJava2-blue.svg)](https://github.com/amitshekhariitbhu/RxJava2-Android-Samples) +[![Seoul42_UI](https://img.shields.io/badge/library-Room-blue.svg)](https://developer.android.com/topic/libraries/architecture/room.html) +[![Seoul42_UI](https://img.shields.io/badge/library-LiveData-blue.svg)](https://developer.android.com/topic/libraries/architecture/livedata.html) + +booscamp3_CํŒ€์˜ ์„œ์šธ์‚ด์ด repository์ž…๋‹ˆ๋‹ค. ํ•ด๋‹น ํ”„๋กœ์ ํŠธ๋Š” MVVM๊ธฐ๋ฐ˜์˜ Androidํ”„๋กœ์ ํŠธ์ž…๋‹ˆ๋‹ค. +์˜์กด์„ฑ ์ฃผ์ž…์„ ์œ„ํ•ด์„œ koin์ด ์‚ฌ์šฉ๋˜์—ˆ๊ณ , RxJava, Room, LiveData, MotionLayout๋“ฑ ๊พธ์ค€ํ•œ ํ•™์Šต์— ์˜ํ•ด์„œ ์ง„ํ–‰๋˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. +<hr/> + +#### ํŒ€์› ์†Œ๊ฐœ : ๋ฌธ๋ณ‘ํ•™, ์œ ์ง€์›, ์ตœ์ค€์˜(๋งํฌ ์ถ”๊ฐ€ ์˜ˆ์ •) + +์„œ์šธ์‚ด์ด๋Š” ์„œ์šธ์‚ด์ด๋ฅผ ์‹œ์ž‘ํ•˜๋Š” ์‚ฌ๋žŒ๋“ค์—๊ฒŒ ์ฃผํƒ์— ๊ด€ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ž…๋‹ˆ๋‹ค. + +<p>ํ˜„์žฌ ์•„ํŒŒํŠธ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋‹ค์–‘ํ•œ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์กด์žฌํ•˜์ง€๋งŒ, ์ƒ๋Œ€์ ์œผ๋กœ ์ฃผํƒ์— ๊ด€๋ จ๋œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. +๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ด๋Ÿฌํ•œ ๋ถ€์กฑํ•œ ์ •๋ณด๋ฅผ ์„œ์šธ์‚ด์ด๋ผ๋Š” ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ํ†ตํ•ด์„œ ์ฃผํƒ์— ๊ด€๋ จ๋œ ์ „/์›”์„ธ, ์ฃผ๋ณ€ ์ง€์—ญ ์ •๋ณด, ์ฃผํƒ ์ •๋ณด๋“ฑ์˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.</p> +<hr/> + + +#### ํ”„๋กœํ† ํƒ€์ž… UI: [![Seoul42_UI](https://img.shields.io/badge/UI-zeplin-blue.svg)](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard) +![image](https://user-images.githubusercontent.com/22374750/52126227-17dd0a00-2672-11e9-9678-2cf1e2aeb6fc.png) + +ํ•ด๋‹น ํ”„๋กœ์ ํŠธ๋Š” ํ˜‘์—…ํˆด์„ 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[![Seoul42_UI](https://img.shields.io/badge/UI-zeplin-blue.svg)](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard) +![image](https://user-images.githubusercontent.com/22374750/52126227-17dd0a00-2672-11e9-9678-2cf1e2aeb6fc.png) + +## 2์ฃผ์ฐจ ์‚ฐ์ถœ๋ฌผ + +Seoul42 API [![Seoul42_API](https://img.shields.io/badge/API-SwaggerHub-blue.svg)](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard) +![image](https://user-images.githubusercontent.com/22374750/52177071-3f151200-27ff-11e9-8b58-ebc916b21c75.png) + +### 2์ฃผ์ฐจ ํšŒ๊ณ ๋ก +![kakaotalk_20190214_181143100](https://user-images.githubusercontent.com/22374750/52834631-26bdc500-3126-11e9-9b4e-1c2eb4ff5895.jpg) +![kakaotalk_20190214_181143373](https://user-images.githubusercontent.com/22374750/52834632-26bdc500-3126-11e9-8f68-95c67e153998.jpg) +์ค€์˜๋‹˜ ํŒŒ์ผ ์žฌ์—…๋กœ๋“œ ํ•„์š” + +## 3์ฃผ์ฐจ ์‚ฐ์ถœ๋ฌผ + +### 3์ฃผ์ฐจ ํšŒ๊ณ ๋ก +![kakaotalk_20190214_181144018](https://user-images.githubusercontent.com/22374750/52834634-27565b80-3126-11e9-98fa-45f600706af6.jpg) +![kakaotalk_20190214_181144329](https://user-images.githubusercontent.com/22374750/52834636-27565b80-3126-11e9-8b02-ccb4046a729f.jpg) +![kakaotalk_20190214_181144629](https://user-images.githubusercontent.com/22374750/52834637-27565b80-3126-11e9-8a4c-f851f327d334.jpg)
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~~~ ๋ฉ”์„œ๋“œ๊ฐ€ ๋งŽ์€๋ฐ ๋ฉ”๋‰ด์— ๊ฐ€๊ฒฉ๊ณผ ํƒ€์ž…๋„ ๊ฐ™์ด ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด ์ข€ ๋” ๊น”๋”ํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋„ค์š”